repo
stringclasses
245 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
SirMallard/Iris
SirMallard-Iris-5b77f59/src/client/helloIris.client.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local Iris = require(ReplicatedStorage.Iris).Init() Iris:Connect(Iris.ShowDemoWindow)
36
SirMallard/Iris
SirMallard-Iris-5b77f59/src/libraries/UserInputService/Signal.lua
-------------------------------------------------------------------------------- -- Batched Yield-Safe Signal Implementation -- -- This is a Signal class which has effectively identical behavior to a -- -- normal RBXScriptSignal, with the only difference being a couple extra -- -- stack frames at the bottom of the stack trace when an error is thrown. -- -- This implementation caches runner coroutines, so the ability to yield in -- -- the signal handlers comes at minimal extra cost over a naive signal -- -- implementation that either always or never spawns a thread. -- -- -- -- API: -- -- local Signal = require(THIS MODULE) -- -- local sig = Signal.new() -- -- local connection = sig:Connect(function(arg1, arg2, ...) ... end) -- -- sig:Fire(arg1, arg2, ...) -- -- connection:Disconnect() -- -- sig:DisconnectAll() -- -- local arg1, arg2, ... = sig:Wait() -- -- -- -- Licence: -- -- Licenced under the MIT licence. -- -- -- -- Authors: -- -- stravant - July 31st, 2021 - Created the file. -- -------------------------------------------------------------------------------- -- The currently idle thread to run the next handler on local freeRunnerThread = nil -- Function which acquires the currently idle handler runner thread, runs the -- function fn on it, and then releases the thread, returning it to being the -- currently idle one. -- If there was a currently idle runner thread already, that's okay, that old -- one will just get thrown and eventually GCed. local function acquireRunnerThreadAndCallEventHandler(fn, ...) local acquiredRunnerThread = freeRunnerThread freeRunnerThread = nil fn(...) -- The handler finished running, this runner thread is free again. freeRunnerThread = acquiredRunnerThread end -- Coroutine runner that we create coroutines of. The coroutine can be -- repeatedly resumed with functions to run followed by the argument to run -- them with. local function runEventHandlerInFreeThread() -- Note: We cannot use the initial set of arguments passed to -- runEventHandlerInFreeThread for a call to the handler, because those -- arguments would stay on the stack for the duration of the thread's -- existence, temporarily leaking references. Without access to raw bytecode -- there's no way for us to clear the "..." references from the stack. while true do acquireRunnerThreadAndCallEventHandler(coroutine.yield()) end end -- Connection class local Connection = {} Connection.__index = Connection function Connection.new(signal, fn) return setmetatable({ _connected = true, _signal = signal, _fn = fn, _next = false, }, Connection) end function Connection:Disconnect() self._connected = false -- Unhook the node, but DON'T clear it. That way any fire calls that are -- currently sitting on this node will be able to iterate forwards off of -- it, but any subsequent fire calls will not hit it, and it will be GCed -- when no more fire calls are sitting on it. if self._signal._handlerListHead == self then self._signal._handlerListHead = self._next else local prev = self._signal._handlerListHead while prev and prev._next ~= self do prev = prev._next end if prev then prev._next = self._next end end end -- Make Connection strict setmetatable(Connection, { __index = function(_, key) error(("Attempt to get Connection::%s (not a valid member)"):format(tostring(key)), 2) end, __newindex = function(_, key, _) error(("Attempt to set Connection::%s (not a valid member)"):format(tostring(key)), 2) end, }) -- Signal class local Signal = {} Signal.__index = Signal function Signal.new() return setmetatable({ _handlerListHead = false, }, Signal) end function Signal:Connect(fn) local connection = Connection.new(self, fn) if self._handlerListHead then connection._next = self._handlerListHead self._handlerListHead = connection else self._handlerListHead = connection end return connection end -- Disconnect all handlers. Since we use a linked list it suffices to clear the -- reference to the head handler. function Signal:DisconnectAll() self._handlerListHead = false end -- Signal:Fire(...) implemented by running the handler functions on the -- coRunnerThread, and any time the resulting thread yielded without returning -- to us, that means that it yielded to the Roblox scheduler and has been taken -- over by Roblox scheduling, meaning we have to make a new coroutine runner. function Signal:Fire(...) local item = self._handlerListHead while item do if item._connected then if not freeRunnerThread then freeRunnerThread = coroutine.create(runEventHandlerInFreeThread) -- Get the freeRunnerThread to the first yield coroutine.resume(freeRunnerThread) end task.spawn(freeRunnerThread, item._fn, ...) end item = item._next end end -- Implement Signal:Wait() in terms of a temporary connection using -- a Signal:Connect() which disconnects itself. function Signal:Wait() local waitingCoroutine = coroutine.running() local cn cn = self:Connect(function(...) cn:Disconnect() task.spawn(waitingCoroutine, ...) end) return coroutine.yield() end -- Implement Signal:Once() in terms of a connection which disconnects -- itself before running the handler. function Signal:Once(fn) local cn cn = self:Connect(function(...) if cn._connected then cn:Disconnect() end fn(...) end) return cn end -- Make signal strict setmetatable(Signal, { __index = function(_, key) error(("Attempt to get Signal::%s (not a valid member)"):format(tostring(key)), 2) end, __newindex = function(_, key, _) error(("Attempt to set Signal::%s (not a valid member)"):format(tostring(key)), 2) end, }) return Signal
1,419
SirMallard/Iris
SirMallard-Iris-5b77f59/src/libraries/UserInputService/init.lua
local Signal = require(script.Signal) local UserInputService: UserInputService = game:GetService("UserInputService") local Input = {} Input.X = 0 Input.Y = 0 Input.KeyDown = {} Input._connections = {} -- This frame will act as our UserInputService detector. Most events should go through it. -- it's not perfect, but there's not a better alternative (I think) local SinkFrame: Frame = Instance.new("Frame") SinkFrame.Name = "SinkFrame" SinkFrame.AnchorPoint = Vector2.new(0.5, 0.5) SinkFrame.Position = UDim2.fromScale(0.5, 0.5) SinkFrame.Size = UDim2.fromScale(1, 1) SinkFrame.BackgroundTransparency = 1 SinkFrame.ZIndex = 1024 ^ 2 Input.SinkFrame = SinkFrame -- Methods and events Input.InputBegan = Signal.new() Input.InputChanged = Signal.new() Input.InputEnded = Signal.new() Input.MouseMoved = Signal.new() Input.TouchTapInWorld = Signal.new() function Input:GetMouseLocation() return Vector2.new(Input.X, Input.Y) end function Input:IsKeyDown(keyCode: Enum.KeyCode) if Input.KeyDown[keyCode] == true then return true end return false end -- UserInputService hooks function inputBegan(input: InputObject) Input.KeyDown[input.KeyCode] = true Input.InputBegan:Fire(input, true) end function inputChanged(input: InputObject) Input.InputChanged:Fire(input, true) end function inputEnded(input: InputObject) Input.KeyDown[input.KeyCode] = nil Input.InputEnded:Fire(input, true) end function mouseMoved(x: number, y: number) Input.X = x Input.Y = y end SinkFrame.InputBegan:Connect(inputBegan) SinkFrame.InputChanged:Connect(inputChanged) SinkFrame.InputEnded:Connect(inputEnded) SinkFrame.MouseMoved:Connect(mouseMoved) table.insert(Input._connections, UserInputService.InputBegan:Connect(inputBegan)) table.insert(Input._connections, UserInputService.InputChanged:Connect(inputChanged)) table.insert(Input._connections, UserInputService.InputEnded:Connect(inputEnded)) return Input
480
SirMallard/Iris
SirMallard-Iris-5b77f59/src/plugins/examplePlugin.client.lua
local Iris = require(script.Parent.Iris) local Input = require(script.Parent.UserInputService) -- Create the plugin toolbar, button and dockwidget for Iris to work in. local widgetInfo = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, false, false, 200, 300) local Toolbar = plugin:CreateToolbar("Iris") local ToggleButton = Toolbar:CreateButton("Toggle Iris", "Toggle Iris running in a plugin window.", "rbxasset://textures/AnimationEditor/icon_checkmark.png") local IrisWidget = plugin:CreateDockWidgetPluginGuiAsync("IrisWidget", widgetInfo) -- defein the widget and button properties IrisWidget.Name = "Iris" IrisWidget.Title = "Iris" IrisWidget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling ToggleButton.ClickableWhenViewportHidden = true local IrisEnabled = false Input.SinkFrame.Parent = IrisWidget -- configure a few things within Iris. We need to provide our own UserInputService and change the config. Iris.Internal._utility.UserInputService = Input Iris.UpdateGlobalConfig({ UseScreenGUIs = false, }) Iris.Disabled = true Iris.Init(IrisWidget) -- We can start defining our code. This just uses the demo window and then forces it to be the same size -- as the Plugin Widget. You don't have to do it this way. Iris:Connect(function() local window = Iris.ShowDemoWindow() window.state.size:set(IrisWidget.AbsoluteSize) window.state.position:set(Vector2.zero) end) IrisWidget:BindToClose(function() IrisEnabled = false IrisWidget.Enabled = false Iris.Disabled = true ToggleButton:SetActive(false) end) ToggleButton.Click:Connect(function() IrisEnabled = not IrisEnabled IrisWidget.Enabled = IrisEnabled Iris.Disabled = not IrisEnabled ToggleButton:SetActive(IrisEnabled) end) -- This is quite important. We need to ensure Iris properly shutdowns and closes any connections. plugin.Unloading:Connect(function() Iris.Shutdown() for _, connection in Input._connections do connection:Disconnect() end Input.SinkFrame:Destroy() IrisEnabled = false IrisWidget.Enabled = false Iris.Disabled = true ToggleButton:SetActive(false) end)
493
SirMallard/Iris
SirMallard-Iris-5b77f59/stories/exampleStory.story.lua
local ReplicatedStorage = game:GetService("ReplicatedStorage") local Types = require(ReplicatedStorage.Iris.PubTypes) return function(parent: GuiObject) local Iris: Types.Iris = require(ReplicatedStorage.Iris) local Input = require(script.Parent.UserInputService) Input.SinkFrame.Parent = parent Iris.Internal._utility.UserInputService = Input Iris.UpdateGlobalConfig({ UseScreenGUIs = false, }) Iris.Internal._utility.GuiOffset = Input.SinkFrame.AbsolutePosition Iris.Internal._utility.MouseOffset = Input.SinkFrame.AbsolutePosition Input.SinkFrame:GetPropertyChangedSignal("AbsolutePosition"):Connect(function() Iris.Internal._utility.GuiOffset = Input.SinkFrame.AbsolutePosition Iris.Internal._utility.MouseOffset = Input.SinkFrame.AbsolutePosition end) Iris.Init(parent) -- Actual Iris code here: Iris:Connect(Iris.ShowDemoWindow) return function() Iris.Shutdown() for _, connection in Input._connections do connection:Disconnect() end Input.SinkFrame:Destroy() end end
239
1Axen/blink
1Axen-blink-3cb8d3d/.lune/build.luau
local fs = require("@lune/fs") local log = require("./libs/log") local process = require("@lune/process") type Archs = | "aarch64" | "x86_64" type Platforms = | "macos" | "linux" | "windows" local EXE_NAME = "blink" local RELEASE_DIR = "release" local PLUGIN_SOURCE_DIR = `plugin/src` local PLUGIN_RELEASE_DIR = `{RELEASE_DIR}/plugin` local CLI_PATH = "src/CLI/init.luau" local BUNDLE_PATH = `{RELEASE_DIR}/blink.luau` local PESDE_RELEASE_PATH = `{RELEASE_DIR}/blink_pesde.luau` local BUNDLE_CONFIG = "build/.darklua.json" local PLUGIN_ROJO_CONFIG = "build/plugin.project.json" local function build_executable(platform: Platforms, arch: Archs) local target = `{platform}-{arch}` local exe_name = `{EXE_NAME}{platform == "windows" and ".exe" or ""}` local exe_path = `{RELEASE_DIR}/{exe_name}` local build_result = process.exec("lune", { "build", BUNDLE_PATH, "--output", exe_path, "--target", target, }, { stdio = "forward" }) assert(build_result.ok, build_result.stderr) local archive_result: process.ExecResult if platform == "windows" then archive_result = process.exec("tar", { "-czvf", `{RELEASE_DIR}/blink-{target}.tar.gz`, "-C", RELEASE_DIR, exe_name, }, { stdio = "forward" }) else archive_result = process.exec("tar", { "-cJvf", `{RELEASE_DIR}/blink-{target}.tar.xz`, "-C", RELEASE_DIR, exe_name, }, { stdio = "forward" }) end assert(archive_result.ok, archive_result.stderr) fs.removeFile(exe_path) log(`Built executable for {target}`) end local function build_pesde() local darklua_result = process.exec("darklua", { "process", "--config", BUNDLE_CONFIG, CLI_PATH, PESDE_RELEASE_PATH }) assert(darklua_result.ok, darklua_result.stderr) log("Build pesde source") end local function build_executables() local bundle_result = process.exec("darklua", { "process", "--config", BUNDLE_CONFIG, CLI_PATH, BUNDLE_PATH }) assert(bundle_result.ok, bundle_result.stderr) log("Bundled CLI source code") build_executable("macos", "x86_64") build_executable("macos", "aarch64") build_executable("linux", "x86_64") build_executable("linux", "aarch64") build_executable("windows", "x86_64") fs.removeFile(BUNDLE_PATH) end local function build_studio_plugin() fs.writeDir(PLUGIN_RELEASE_DIR) for _, filename in fs.readDir(PLUGIN_SOURCE_DIR) do if string.split(filename, ".")[2] == "rbxmx" then fs.copy(`{PLUGIN_SOURCE_DIR}/{filename}`, `{PLUGIN_RELEASE_DIR}/{filename}`) end end local bundle_result = process.exec("darklua", { "process", "--config", BUNDLE_CONFIG, `{PLUGIN_SOURCE_DIR}/init.server.luau`, `{PLUGIN_RELEASE_DIR}/init.server.luau`, }) assert(bundle_result.ok, bundle_result.stderr) local rojo_result = process.exec("rojo", { "build", PLUGIN_ROJO_CONFIG, "--output", `{RELEASE_DIR}/blink-plugin.rbxm`, }) assert(rojo_result.ok, rojo_result.stderr) log("Built studio plugin") fs.removeDir(PLUGIN_RELEASE_DIR) end do if fs.isDir(RELEASE_DIR) then fs.removeDir(RELEASE_DIR) end fs.writeDir(RELEASE_DIR) end local start = os.clock() build_pesde() build_executables() build_studio_plugin() local elapsed = (os.clock() - start) print(string.format("Finished build in %.2f seconds", elapsed))
895
1Axen/blink
1Axen-blink-3cb8d3d/.lune/bump.luau
local darklua_version = require("./libs/darklua_version") local pesde_version = require("./libs/pesde_version") local stdio = require("@lune/stdio") local PESDE_CONFIG = "pesde.toml" local DARKLUA_CONFIG = "build/.darklua.json" local curr_version = darklua_version.read_from(DARKLUA_CONFIG) local new_version = stdio.prompt("text" :: "text", `What version is being built? (Current version is {curr_version})`) darklua_version.write_to(DARKLUA_CONFIG, new_version) pesde_version.write_to(PESDE_CONFIG, new_version)
134
1Axen/blink
1Axen-blink-3cb8d3d/.lune/libs/darklua_version.luau
local fs = require("@lune/fs") local serde = require("@lune/serde") local log = require("./log") type DarkluaRules = | "inject_global_value" | "N/A" type DarkluaConfig = { rules: { DarkluaRules | { rule: DarkluaRules, identifier: string, value: any } } } local function read_version(config_path: string): string local contents = fs.readFile(config_path) local config = serde.decode("json", contents) :: DarkluaConfig for _, rule in config.rules do if type(rule) == "string" then continue end if rule.rule ~= "inject_global_value" then continue end if rule.identifier == "VERSION" then return rule.value end end return "?" end local function write_version(config_path: string, version: string) local contents = fs.readFile(config_path) local config = serde.decode("json", contents) :: DarkluaConfig for _, rule in config.rules do if type(rule) == "string" then continue end if rule.rule ~= "inject_global_value" then continue end if rule.identifier == "VERSION" then rule.value = version end end contents = serde.encode("json", config, true) fs.writeFile(config_path, contents) log(`Updated darklua config version to {version}`) end return table.freeze({ read_from = read_version, write_to = write_version })
347
1Axen/blink
1Axen-blink-3cb8d3d/.lune/libs/pesde_version.luau
local fs = require("@lune/fs") local log = require("./log") local serde = require("@lune/serde") type PesdeConfig = { version: string, } local function read_version(config_path: string): string local contents = fs.readFile(config_path) local config = serde.decode("toml", contents) :: PesdeConfig return config.version or "?" end local function write_version(config_path: string, version: string) local contents = fs.readFile(config_path) local config = serde.decode("toml", contents) :: PesdeConfig config.version = version contents = serde.encode("toml", config, true) fs.writeFile(config_path, contents) log(`Updated pesde config version to {version}`) end return table.freeze({ read_from = read_version, write_to = write_version, })
172
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/run.luau
local RunService = game:GetService("RunService") if not RunService:IsRunning() then print("Press F5 to start the benchmark.") while task.wait(9e9) do end end local Result: StringValue while Result == nil do Result = game:FindFirstChild("Result") task.wait(1) end print("--RESULTS JSON--") print(Result.Value)
82
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/client/init.client.luau
local Benches = require("./shared/benches") local Modes = require("./shared/modes") local HttpService = game:GetService("HttpService") local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local StarterGui = game:GetService("StarterGui") local Stats = game:GetService("Stats") local MAXIMUM_FRAMERATE = 60 local Camera = workspace.CurrentCamera Camera.FieldOfView = 1 Camera.CFrame = CFrame.new(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) Players.LocalPlayer.PlayerGui:ClearAllChildren() Players.LocalPlayer.PlayerScripts:ClearAllChildren() for _, Item in Enum.CoreGuiType:GetEnumItems() do while true do local Success = pcall(function() StarterGui:SetCoreGuiEnabled(Item, false) end) if Success then break end end end type Benchmark = { Sent: number, Recieve: number, Bandwidth: { number }, Framerate: { number }, } type Results = { [string]: { [string]: Benchmark, }, } local function Percentile(Samples: { number }, Percentile: number) assert( (Percentile // 1) == Percentile and Percentile >= 0 and Percentile <= 100, "Percentile must be an integer between 0 and 100" ) local Index = ((#Samples * (Percentile / 100)) // 1) Index = math.max(Index, 1) return Samples[Index] end local function WaitForPacketsToProcess() print("Waiting for packets to be processed.") while Stats.DataSendKbps > 0.5 do RunService.Heartbeat:Wait() end task.wait(5) end local function RunBenchmark(Tool: string, Bench: string): Benchmark local Total = 0 local Frames = 0 local Bandwidth = {} local Framerates = {} local Sent = 0 local Data = Benches[Bench] local Events = Modes[Tool] local Event = Events[Bench] local Method if Tool == "warp" then Method = function(Data) Event:Fire(true, Data) end elseif Tool == "roblox" then Method = function(Data) Event:FireServer(Data) end else Method = Event.Fire or Event.send end local Connection = RunService.PostSimulation:Connect(function(DeltaTime: number) Total += DeltaTime Frames += 1 if Total >= 1 then Total -= 1 local Scale = (MAXIMUM_FRAMERATE / Frames) table.insert(Bandwidth, Stats.DataSendKbps * Scale) table.insert(Framerates, Frames) Frames = 0 end for Index = 1, 1000 do Sent += 1 Method(Data) end end) task.wait(10) Connection:Disconnect() print(`> Finished running with {Tool}`) --> Generate results table.sort(Bandwidth) table.sort(Framerates, function(a, b) return a > b end) local FrameratePercentiles = {} local BandwidthPercentiles = {} for _, Percentage in { 50, 0, 80, 90, 95, 100 } do table.insert(BandwidthPercentiles, Percentile(Bandwidth, Percentage)) table.insert(FrameratePercentiles, Percentile(Framerates, Percentage)) end return { Sent = Sent, Recieve = 0, Bandwidth = BandwidthPercentiles, Framerate = FrameratePercentiles, } end local function RunBenchmarks() local Results: Results = {} for Bench in Benches do warn(`Running {Bench} benchmark`) Results[Bench] = {} for Tool in Modes do print(`> Running with {Tool}`) Results[Bench][Tool] = RunBenchmark(Tool, Bench) --> Give ROBLOX some time to rest in-between tools WaitForPacketsToProcess() end --> Give ROBLOX some time to rest in-between benchmarks WaitForPacketsToProcess() end local Recieved = ReplicatedStorage.Shared.GetRecieved:InvokeServer() for Bench, Tools in Recieved do for Tool, Recieve in Tools do Results[Bench][Tool].Recieve = Recieve end end print("Finished running benchmarks, generating results...") ReplicatedStorage.Shared.Generate:FireServer(HttpService:JSONEncode(Results)) end RunBenchmarks()
1,052
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/server/init.server.luau
local HttpService = game:GetService("HttpService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local Benches = require("./shared/benches") local Modes = require("./shared/modes") function CompareTables(a, b) if a == b then return true end if type(a) ~= type(b) then return false end if type(a) ~= "table" then return false end local Keys = {} for Key, Value in a do local SecondaryValue = b[Key] if SecondaryValue == nil or not CompareTables(Value, SecondaryValue) then return false end Keys[Key] = true end for Key, _ in b do if not Keys[Key] then return false end end return true end local function CompareValues(a, b): boolean if type(a) == "table" or type(b) == "table" then return CompareTables(a, b) end return (a == b) end local Recieved = {} for Name, Data in Benches do local BenchRecieved = {} Recieved[Name] = BenchRecieved local function OnRecieve(Tool: string) BenchRecieved[Tool] = 0 return function(Player, Recieve) BenchRecieved[Tool] += 1 if BenchRecieved[Tool] > 1 then return end if Tool == "bytenet" then Player, Recieve = Recieve, Player end if not CompareValues(Data, Recieve) then warn(`Recieved incorrect data with {Tool} for {Name}`) else print(`> {Tool} passed {Name} validation!`) end end end for Tool, Events in Modes do local Event = Events[Name] local Callback = OnRecieve(Tool) if Tool == "warp" then Event:Connect(Callback) continue elseif Tool == "roblox" then Event.OnServerEvent:Connect(Callback) continue end local Method = Event.On or Event.SetCallback or Event.listen Method(Callback) end end ReplicatedStorage.Shared.GetRecieved.OnServerInvoke = function() return Recieved end ReplicatedStorage.Shared.Generate.OnServerEvent:Connect(function(Player, JSON) local OutputJSON = Instance.new("StringValue") OutputJSON.Name = "Result" OutputJSON.Value = JSON OutputJSON.Parent = game print("Generated results") end)
562
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/benches/Entities.luau
local Array = {} for Index = 1, 100 do table.insert(Array, { id = math.random(1, 255), x = math.random(1, 255), y = math.random(1, 255), z = math.random(1, 255), orientation = math.random(1, 255), animation = math.random(1, 255), }) end return Array
93
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/benches/init.luau
local Benches = {} for Index, Bench in script:GetChildren() do --> Reset random seed to a constant value --> This results in the same values being generated on both server and client math.randomseed(0) Benches[Bench.Name] = require(Bench) end return Benches
67
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/modes/blink.luau
local RunService = game:GetService("RunService") if RunService:IsServer() then return require("../blink/Server") elseif RunService:IsClient() then return require("../blink/Client") end
43
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/modes/init.luau
local DISABLED_MODES = { warp = true, } local Modes = {} for Index, Mode in script:GetChildren() do if DISABLED_MODES[Mode.Name] then continue end Modes[Mode.Name] = require(Mode) end return Modes
60
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/modes/roblox.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local Benches = require("../benches") local Events = {} local IsServer = RunService:IsServer() for Name in Benches do local Event: RemoteEvent if IsServer then Event = Instance.new("RemoteEvent") Event.Name = Name Event.Parent = ReplicatedStorage else Event = ReplicatedStorage:WaitForChild(Name) end Events[Name] = Event end return Events
116
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/modes/warp.luau
local RunService = game:GetService("RunService") local Benches = require("../benches") local Warp = require("../../../packages/warp") local Events = {} local Method = RunService:IsServer() and "Server" or "Client" for Name in Benches do Events[Name] = Warp[Method](Name, { interval = 0, maxEntrance = math.huge, }) end return Events
93
1Axen/blink
1Axen-blink-3cb8d3d/benchmark/src/shared/modes/zap.luau
local RunService = game:GetService("RunService") if RunService:IsServer() then return require("../zap/Server") elseif RunService:IsClient() then return require("../zap/Client") end
43
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/Editor/Styling/AutoBracket.luau
local Hook = {} local Brackets = { ["("] = ")", ["{"] = "}", ["["] = "]", ["<"] = ">", } local ClosingBrackets = { [")"] = true, ["}"] = true, ["]"] = true, [">"] = true, } local IgnoredCharacters = { ["\n"] = true, [""] = true, [")"] = true, ["}"] = true, ["]"] = true, [">"] = true, } local function OnGain(Text: string, Cursor: number): (string, number) local Next = string.sub(Text, Cursor, Cursor) local Previous = string.sub(Text, Cursor - 1, Cursor - 1) local ClosingBracket = Brackets[Previous] if ClosingBracket and IgnoredCharacters[Next] then Text = string.sub(Text, 1, Cursor - 1) .. ClosingBracket .. string.sub(Text, Cursor) return Text, Cursor end return Text, Cursor end local function OnRemove(Text: string, PreviousText: string, Cursor: number): (string, number) local Next = string.sub(Text, Cursor, Cursor) local Previous = string.sub(PreviousText, Cursor, Cursor) if Brackets[Previous] and ClosingBrackets[Next] then Text = string.sub(Text, 1, Cursor - 1) .. string.sub(Text, Cursor + 1) return Text, Cursor end return Text, Cursor end function Hook.OnSourceChanged(Text: string, PreviousText: string, Cursor: number, Gain: number): (string, number) if Gain >= 1 then return OnGain(Text, Cursor) elseif Gain <= -1 then return OnRemove(Text, PreviousText, Cursor) end return Text, Cursor end return Hook
401
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/Editor/Styling/AutoIndent.luau
local Utility = require("../Utility") local Hook = {} local IndentKeywords = { "{\n", } local function ShouldAutoIndent(Text: string, Cursor: number): boolean for Index, Keyword in IndentKeywords do local Position = (Cursor - #Keyword) if Position <= 0 then continue end local Previous = string.sub(Text, Position, Cursor - 1) if Previous == Keyword then return true end end return false end local function GetLineIndentation(Line: string): number return #(string.match(Line, "^\t*") :: string) end function Hook.OnSourceChanged(Text: string, PreviousText: string, Cursor: number, Gain: number): (string, number) if Gain ~= 1 then return Text, Cursor end local CanIndent = false local AdditionalIndent = 0 local Line, Lines = Utility.GetCurrentLine(Text, Cursor) local Current = Lines[Line] local Previous = Lines[Line - 1] local JustReached = (Previous and Current == "") if ShouldAutoIndent(Text, Cursor) then CanIndent = true AdditionalIndent = 1 elseif JustReached then if GetLineIndentation(Previous) > 0 then CanIndent = true end end if not CanIndent then return Text, Cursor end --> Update text and cursor local NextCharacter = string.sub(Text, Cursor, Cursor) if string.gsub(NextCharacter, "%c", "") == "" then NextCharacter = nil end local Indentation = GetLineIndentation(Previous) + AdditionalIndent Text = string.sub(Text, 1, Cursor - 1) .. string.rep("\t", Indentation) .. (NextCharacter and `\n{string.rep("\t", Indentation - 1)}` or "") .. string.sub(Text, Cursor) return Text, Cursor + Indentation end return Hook
433
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/Editor/init.luau
--!strict -- ******************************* -- -- AX3NX / AXEN -- -- ******************************* -- ---- Services ---- local ContentProvider = game:GetService("ContentProvider") local RunService = game:GetService("RunService") local TextService = game:GetService("TextService") ---- Imports ---- local State = require("./State") local Utility = require("@self/Utility") local Profiler = require("./Profiler") local Lexer = require("@compiler/Lexer") local Parser = require("@compiler/Parser") local Settings = require("@compiler/Settings") local Error = require("@compiler/Modules/Error") local StylingHooks: { { OnSourceChanged: (Text: string, PreviousText: string, Cursor: number, Gain: number) -> (string, number) } } = { require("@self/Styling/AutoIndent"), require("@self/Styling/AutoBracket"), } ---- Settings ---- local ICONS = { Event = "rbxassetid://16506730516", Field = "rbxassetid://16506725096", Snippet = "rbxassetid://16506712161", Keyword = "rbxassetid://16506695241", Variable = "rbxassetid://16506719167", Primitive = "rbxassetid://16506695241", } local THEME = { Text = Color3.fromHex("#FFFFFF"), Keyword = Color3.fromHex("#6796E6"), Primitive = Color3.fromHex("#4EC9B0"), Identifier = Color3.fromHex("#9CDCFE"), Class = Color3.fromHex("#B5CEA8"), Number = Color3.fromHex("#B5CEA8"), String = Color3.fromHex("#ADF195"), Bracket = Color3.fromHex("#FFFFFF"), Boolean = Color3.fromHex("#B5CEA8"), Comment = Color3.fromHex("#529955"), Error = Color3.fromHex("#FF5050"), Warning = Color3.fromHex("#FF5050"), Complete = Color3.fromHex("#04385f"), Line = { Active = Color3.fromHex("FFFFFF"), Inactive = Color3.fromHex("787878"), }, } -- This is a comment local PRIMITIVES = {} for Primitive in Settings.Primtives do table.insert(PRIMITIVES, { Label = Primitive, Insert = Primitive }) end local SYMBOLS: { [string]: { { Label: string, Insert: string } } } = { Event = {}, Field = {}, Snippet = {}, Keyword = { { Label = "set", Insert = "set %s = {}" }, { Label = "map", Insert = "map %s = {[]: }" }, { Label = "type", Insert = "type %s = " }, { Label = "enum", Insert = "enum %s = {}" }, { Label = "struct", Insert = "struct %s {}" }, { Label = "event", Insert = "event %s {}" }, { Label = "function", Insert = "function %s {}" }, { Label = "import", Insert = "import %s as " }, { Label = "scope", Insert = "scope %s {}" }, { Label = "export", Insert = "export " }, }, Variable = {}, Primitive = PRIMITIVES, } local BRACKETS = { OpenParentheses = true, CloseParentheses = true, OpenBraces = true, CloseBraces = true, OpenBrackets = true, CloseBrackets = true, } local RICH_TEXT_ESCAPES: { [string]: string } = { --["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", --["\""] = "&quot;", --["\'"] = "&apos;", } local SCROLL_LINES = 2 local CURSOR_BLINK_RATE = 0.5 local PRE_ALLOCATED_LINES = 2_000 type CompletionItem = { Icon: string, Label: string, Insert: string, } ---- Constants ---- local Editor = {} --> Interface Instances local Container: typeof(script.Parent.Widget) = script.Widget local EditorContainer = Container.Editor local CompletionContainer = Container.Completion local TextContainer = EditorContainer.Text local LinesContainer = EditorContainer.Lines local Input = TextContainer.Input local Cursor = TextContainer.Cursor local Display = TextContainer.Display local Selection = TextContainer.Selection local ErrorSelection = TextContainer.Error local ErrorContainer = Container.Error local ErrorText = ErrorContainer.Text local LineTemplate = LinesContainer.Line:Clone() local ErrorTemplate = ErrorSelection.Line:Clone() local SelectionTemplate = Selection.Line:Clone() local CompletionTemplate = CompletionContainer.Option:Clone() local TextSize = Input.TextSize local TextHeight = (Input.TextSize + 3) --> Objects local SourceLexer = Lexer.new("Highlighting") local SourceParser = Parser.new() local EditorWidget: DockWidgetPluginGui ---- Variables ---- local Lines = 0 local Scroll = State.new(0) local Predictions: State.Class<{ Index: number, Items: { CompletionItem } }> = State.new({ Index = 1, Items = {} }) local CursorTimer = 0 local PreviousText = Input.Text local PreviousLine: TextLabel? local AnalysisError: State.Class<Error.Class?> = State.new(nil :: any) local AbstractSyntaxTree: Parser.Body? ---- Private Functions ---- local function ScrollTowards(Direction: number) local Value = Scroll:Get() local Maximum = math.max(1, (Input.TextBounds.Y - EditorContainer.AbsoluteSize.Y) // TextHeight + SCROLL_LINES) Scroll:Set(math.clamp(Value + (Direction * SCROLL_LINES), 0, Maximum)) end local function Color(Text: string, Color: Color3): string return `<font color="#{Color:ToHex()}">{Text}</font>` end local function Escape(Text: string) for Symbol, Escape in RICH_TEXT_ESCAPES do Text = string.gsub(Text, Symbol, Escape) end return Text end local function ClearChildrenWhichAre(Parent: Instance, Class: string) for Index, Child in Parent:GetChildren() do if Child:IsA(Class) then Child:Destroy() end end end local function GetPrediction(): CompletionItem? local Items = Predictions:Get() local Item = Items.Items[Items.Index] if not Item then return end return Item end local DOTS = "%.%." local NUMBER = "%-?%d*%.?%d+" local function UpdateColors() local Source = Input.Text local RichText = {} --> Render text immediately Display.Text = Source Display.TextColor3 = THEME.Text --> Initiialize lexer SourceLexer:Initialize(Source) --> Highlight state local Keyword = "none" local Token = SourceLexer:GetNextToken() while Token and (Token.Type ~= "EndOfFile") do local Type: Lexer.Types = Token.Type local Value = Token.Value local String = Escape(Value) if Type == "Keyword" or Type == "Import" or Type == "As" then Keyword = Value String = Color(Value, THEME.Keyword) elseif Type == "Primitive" then String = Color(Value, THEME.Primitive) elseif Type == "Identifier" then local LookAhead = SourceLexer:GetNextToken(true) local IsField = (LookAhead and LookAhead.Type == "FieldAssign" and Keyword ~= "map") String = Color(Value, IsField and THEME.Text or THEME.Identifier) elseif Type == "Array" or Type == "Range" then --> Exact size array/range local Single = string.match(Value, `%[({NUMBER})%]`) or string.match(Value, `%(({NUMBER})%)`) local Lower = string.match(Value, `%[({NUMBER}){DOTS}`) or string.match(Value, `%(({NUMBER}){DOTS}`) local Upper = string.match(Value, `{DOTS}({NUMBER})%]`) or string.match(Value, `{DOTS}({NUMBER})%)`) if Single then String = string.gsub(Value, Single, Color(Single, THEME.Number)) elseif Lower and Upper then String = `{string.sub(Value, 1, 1)}{Color(Lower, THEME.Number)}..{Color(Upper, THEME.Number)}{string.sub( Value, #Value, #Value )}` end elseif Type == "Component" then local Primitive = string.match(Value, "(%w+)") or "" String = `{Color("<", THEME.Bracket)}{Color(Primitive, THEME.Primitive)}{Color(">", THEME.Bracket)}` elseif BRACKETS[Type] then String = Color(Value, THEME.Bracket) elseif Type == "Class" then String = `({Color(string.sub(Value, 2, #Value - 1), THEME.Class)})` elseif Type == "String" then String = Color(Value, THEME.String) elseif Type == "Boolean" then String = Color(Value, THEME.Boolean) elseif Type == "Comment" then String = Color(Value, THEME.Comment) elseif Type == "Unknown" then String = Color(Value, THEME.Error) end table.insert(RichText, String) Token = SourceLexer:GetNextToken() end --> Render highlighted text Display.Text = table.concat(RichText) end local function UpdateAnalysis() local Success, Result = pcall(function() return SourceParser:Parse(Editor.GetSource()) end) if Success then AnalysisError:Set(nil) AbstractSyntaxTree = Result end end local function UpdateCompletion() local Line = Utility.GetLineRangeAtPosition(Input.Text, Input.CursorPosition) local Items: { CompletionItem } = {} --> Match Keywords local function MatchSymbols() local Word = Utility.GetWordRangeAtPosition(Line.Text, Input.CursorPosition - Line.Start) local Text = Word.Text if #Text == 0 then return end --> Match keywords if Word.Index == 1 then for _, Symbol in SYMBOLS.Keyword do local Label = Symbol.Label local Stub = string.sub(Label, 1, #Text) if Stub ~= Text or Stub == Label then continue end table.insert(Items, { Icon = ICONS.Keyword, Label = Label, Insert = Symbol.Insert, }) end end --> Match symbols local Previous = Utility.GetWordRangeBeforePosition(Line.Text, Word.Start - 1) if Previous.Text == "" then return end if string.match(Previous.Text, ":$") or Previous.Text == "=" then for _, Symbol in SYMBOLS.Primitive do local Label = Symbol.Label local Stub = string.sub(Label, 1, #Text) if Stub ~= Text or Stub == Label then continue end table.insert(Items, { Icon = ICONS.Primitive, Label = Label, Insert = Label, }) end if AbstractSyntaxTree then for Symbol in AbstractSyntaxTree.Value.Symbols do local Stub = string.sub(Symbol, 1, #Text) if Stub ~= Text or Stub == Symbol then continue end table.insert(Items, { Icon = ICONS.Variable, Label = Symbol, Insert = Symbol, }) end end end end MatchSymbols() --> Update predictions Predictions:Set({ Index = 1, Items = Items, }) end local function UpdateHighlightedLine() local Line = Utility.GetCurrentLine(Input.Text, Input.CursorPosition) Line = math.clamp(Line, 1, PRE_ALLOCATED_LINES) local Label: TextLabel = LinesContainer[tostring(Line)] if PreviousLine then PreviousLine.TextColor3 = THEME.Line.Inactive end PreviousLine = Label Label.TextColor3 = THEME.Line.Active end ---- Event Functions ----- local function OnErrorEmitted(Object: Error.Class) AnalysisError:Set(Object) end local function OnPreRender(DeltaTime: number) if Input.CursorPosition == -1 then return end CursorTimer += DeltaTime if CursorTimer < CURSOR_BLINK_RATE then return end CursorTimer -= CURSOR_BLINK_RATE Cursor.Visible = not Cursor.Visible end --> State functions local function OnLinesChanged(Value: number) --> Insert new or delete lines local Difference = (Value - Lines) if Difference > 0 then for Index = (Lines + 1), Value do local Name = tostring(Index) local Line = LinesContainer[Name] Line.TextTransparency = 0 end elseif Difference < 0 then for Index = Lines, (Value + 1), -1 do local Name = tostring(Index) local Line = LinesContainer[Name] Line.TextTransparency = 1 end end Lines = Value --> Update highlighted line UpdateHighlightedLine() end local function OnScrollChanged(Value: number) EditorContainer.Position = UDim2.fromOffset(EditorContainer.Position.X.Offset, TextHeight * -Value) end local function OnPredictionsChanged() local Value = Predictions:Get() local Items = Value.Items if #Items == 0 then CompletionContainer.Visible = false return end --> Update completion position local AbsoluteSize = EditorContainer.AbsoluteSize local AbsolutePosition = Cursor.AbsolutePosition local HorisontalWidth = math.max(0, (AbsoluteSize.X - CompletionContainer.Size.X.Offset) - 10) CompletionContainer.Position = UDim2.fromOffset(math.clamp(AbsolutePosition.X, 0, HorisontalWidth), AbsolutePosition.Y + TextSize) CompletionContainer.Visible = true ClearChildrenWhichAre(CompletionContainer, "Frame") for Index, Item in Items do local Frame = CompletionTemplate:Clone() Frame.Icon.Image = Item.Icon Frame.Text.Text = Item.Label if Index == Value.Index then Frame.BackgroundColor3 = THEME.Complete end Frame.Parent = CompletionContainer end end local function OnAnalysisErrorChanged() local Error = AnalysisError:Get() --> Clear previous error ErrorContainer.Visible = false ClearChildrenWhichAre(ErrorSelection, "Frame") --> No errors if not Error then return end local Labels = Error.Labels if #Labels == 0 then return end --> Error message local Message = `{Error.GetNameFromCode(Error.Code)}: {Error.RawMessage} <font transparency="0.5"><i>Blink({Error.Code})</i></font>` for _, Label in Labels do local Line = Utility.GetCurrentLine(Input.Text, Label.Span.Start) Message ..= `\n{Label.Text} [L{Line}]` end ErrorText.Text = Message --> Highlight error local Primary = Labels[#Labels] local Span = Primary.Span local Start = Span.Start local Finish = Span.End local Text = string.sub(Input.ContentText, 1, Finish) local Slices = string.split(Text, "\n") local Offset = 0 for Index, Slice in Slices do local First = Offset Offset += (#Slice + 1) local Line = ErrorTemplate:Clone() local Fill = Line.Fill if Offset < Start then Line.Fill.MaxVisibleGraphemes = 0 Line.Parent = ErrorSelection continue end --> Calculate selection bounds local Substring = Slice if First < Start then Substring = string.sub(Slice, (Start - First), #Slice) elseif Index == #Slices then Substring = string.sub(Slice, 1, math.max(1, Finish - First)) end --> Empty lines should appear as one space thick selections if Substring == "" then Substring = " " end local SelectionBoundsParams = Instance.new("GetTextBoundsParams") SelectionBoundsParams.Text = Substring SelectionBoundsParams.Size = TextSize SelectionBoundsParams.Font = Display.FontFace local SelectionBounds = TextService:GetTextBoundsAsync(SelectionBoundsParams) Fill.Size = UDim2.new(0, SelectionBounds.X, 1, 0) --> Calculate selection offset if Start > First then local Prefix = string.sub(Slice, 1, (Start - First) - 1) if Prefix ~= "" then local OffsetBoundsParams = Instance.new("GetTextBoundsParams") OffsetBoundsParams.Text = Prefix OffsetBoundsParams.Size = TextSize OffsetBoundsParams.Font = Input.FontFace local OffsetBounds = TextService:GetTextBoundsAsync(OffsetBoundsParams) Fill.Position = UDim2.new(0, OffsetBounds.X, 0, 10) end end Line.MouseEnter:Connect(function() local Position = EditorWidget:GetRelativeMousePosition() ErrorContainer.Visible = true ErrorContainer.Position = UDim2.fromOffset(Position.X + 4, Position.Y) end) Line.MouseLeave:Connect(function() ErrorContainer.Visible = false end) Line.Fill.MaxVisibleGraphemes = #Substring Line.Parent = ErrorSelection break end end --> RBXScriptSignal functions local function OnCursorPositionChanged() local CursorPosition = Input.CursorPosition if CursorPosition == -1 then Cursor.Visible = false return end Profiler.profileBegin("Cursor") local Text = string.sub(Input.Text, 1, CursorPosition - 1) local Slices = string.split(Text, "\n") --> Calculate current end line position local Line = Slices[#Slices] or "" local GetTextBoundsParams = Instance.new("GetTextBoundsParams") GetTextBoundsParams.Text = Line GetTextBoundsParams.Size = TextSize GetTextBoundsParams.Font = Display.FontFace local TextBounds = TextService:GetTextBoundsAsync(GetTextBoundsParams) --> Update cursor size and position Cursor.Size = UDim2.fromOffset(2, TextSize) Cursor.Position = UDim2.fromOffset(TextBounds.X - 1, TextHeight * (#Slices - 1)) --> Update highlighted line Profiler.profileBegin("Highlight LN") UpdateHighlightedLine() Profiler.profileEnd() Profiler.profileEnd() end local function OnSelectionChanged() --> Clear previous selection ClearChildrenWhichAre(Selection, "Frame") --> Nothing is selected local CursorPosition = Input.CursorPosition local SelectionStart = Input.SelectionStart if CursorPosition == -1 or SelectionStart == -1 then return end local Start = math.min(CursorPosition, SelectionStart) local Finish = math.max(CursorPosition, SelectionStart) local Text = string.sub(Input.ContentText, 1, Finish - 1) local Slices = string.split(Text, "\n") local Offset = 0 for Index, Slice in Slices do local First = Offset Offset += (#Slice + 1) local Line = SelectionTemplate:Clone() local Fill = Line.Fill if Offset < Start then Fill.BackgroundTransparency = 1 Line.Parent = Selection continue end --> Calculate selection bounds local Substring = Slice if First < Start then Substring = string.sub(Slice, (Start - First), #Slice) elseif Index == #Slices then Substring = string.sub(Slice, 1, math.max(1, Finish - First)) end --> Empty lines should appear as one space thick selections if Substring == "" then Substring = " " end local SelectionBoundsParams = Instance.new("GetTextBoundsParams") SelectionBoundsParams.Text = Substring SelectionBoundsParams.Size = TextSize SelectionBoundsParams.Font = Display.FontFace local SelectionBounds = TextService:GetTextBoundsAsync(SelectionBoundsParams) Fill.Size = UDim2.new(0, SelectionBounds.X, 1, 0) --> Calculate selection offset if Start > First then local Prefix = string.sub(Slice, 1, (Start - First) - 1) if Prefix ~= "" then local OffsetBoundsParams = Instance.new("GetTextBoundsParams") OffsetBoundsParams.Text = Prefix OffsetBoundsParams.Size = TextSize OffsetBoundsParams.Font = Display.FontFace local OffsetBounds = TextService:GetTextBoundsAsync(OffsetBoundsParams) Fill.Position = UDim2.new(0, OffsetBounds.X, 0, 0) end end Line.Parent = Selection end end local function OnSourceChanged() --> Pressing enter inserts a carriage return (ROBLOX please fix) local Text = Input.Text local Gain = math.sign(#Text - #PreviousText) local NoReturnCarriage = string.gsub(Text, "\r", "") if NoReturnCarriage ~= Text then Input.Text = NoReturnCarriage return end --> Auto complete if Gain == 1 then Profiler.profileBegin("Insertion") local Item = GetPrediction() local Cursor = (Input.CursorPosition - 1) local Character = string.sub(Text, Cursor, Cursor) if Item and Character == "\t" then local Insert = Item.Insert local Offset = (#Insert + 1) local Start, End = string.find(Insert, "%s", 1, true) if Start and End then Offset = Start Insert = string.sub(Insert, 1, Start - 1) .. string.sub(Insert, End + 1) end --> Move cursor behind tab character Cursor -= 1 local Line = Utility.GetLineRangeAtPosition(Text, Cursor) local Position = (Cursor - Line.Start + 1) local Word = Utility.GetWordRangeAtPosition(Line.Text, Position) local Length = #Word.Text Cursor -= Length --> Match characters before replacement and after tab (2) Text = (string.sub(Text, 1, Cursor) .. Insert .. string.sub(Text, Cursor + Length + 2)) PreviousText = Text Input.Text = Text Input.CursorPosition = -1 Input.CursorPosition = (Cursor + Offset) Profiler.profileEnd() return end Profiler.profileEnd() end --> Run styling hooks Profiler.profileBegin("Styling") local FinalText, FinalCursor = Text, Input.CursorPosition for Index, Hook in StylingHooks do FinalText, FinalCursor = Hook.OnSourceChanged(FinalText, PreviousText, FinalCursor, Gain) end Profiler.profileEnd() --> Update previous text PreviousText = FinalText --> If a styling hook altered the final text then don't do any additional work if FinalText ~= Text then Input.Text = FinalText Input.CursorPosition = FinalCursor return end --> Update line counter Profiler.profileBegin("Line counter") local Slices = string.split(Text, "\n") if #Slices ~= Lines then OnLinesChanged(#Slices) end Profiler.profileEnd() --> Perform lexer pass Profiler.profileBegin("Analysis") UpdateAnalysis() Profiler.profileEnd() Profiler.profileBegin("Completion") UpdateCompletion() Profiler.profileEnd() Profiler.profileBegin("Highlighting") UpdateColors() Profiler.profileEnd() end --> Create lines in the background local function GenerateLinesAsync() local Tick = os.clock() for Index = 1, PRE_ALLOCATED_LINES do local Elapsed = (os.clock() - Tick) if Elapsed > (1 / 120) then task.wait() Tick = os.clock() end local Line = LineTemplate:Clone() Line.Name = tostring(Index) Line.Text = tostring(Index) Line.TextColor3 = THEME.Line.Inactive Line.TextTransparency = 1 Line.Position = UDim2.fromOffset(0, 19 * (Index - 1)) Line.Parent = LinesContainer end end ---- Public Functions ---- function Editor.GetSource(): string return Input.Text end function Editor.SetSource(Source: string) Scroll:Set(0) Input.Text = Source end ---- Initialization ---- function Editor.Initialize(Widget: DockWidgetPluginGui) EditorWidget = Widget task.spawn(GenerateLinesAsync) --> Preload fira sans ContentProvider:PreloadAsync({ Display }, function(AssetId: string, AssetFetchStatus: Enum.AssetFetchStatus) if AssetId ~= "" and AssetFetchStatus ~= Enum.AssetFetchStatus.Success then warn("[BLINK] There was an issue preloading the editors font.") end end) --> Remove templates Selection.Line:Destroy() ErrorSelection.Line:Destroy() LinesContainer.Line:Destroy() CompletionContainer.Option:Destroy() --> Sort auto complete symbols for _, Symbols in SYMBOLS do table.sort(Symbols, function(a, b) return #a.Label < #b.Label end) end --> Connections Error.OnEmit = OnErrorEmitted Scroll:OnChange(OnScrollChanged) Predictions:OnChange(OnPredictionsChanged) AnalysisError:OnChange(OnAnalysisErrorChanged) --> Fixes a weird bug with the cursor being moved to character 6000 Input.Focused:Once(function() Input:ReleaseFocus(true) RunService.PreRender:Wait() Input:CaptureFocus() Input.CursorPosition = 1 end) Input:GetPropertyChangedSignal("Text"):Connect(function() Profiler.profileBegin("Total") OnSourceChanged() Profiler.profileEnd() end) Input:GetPropertyChangedSignal("SelectionStart"):Connect(OnSelectionChanged) Input:GetPropertyChangedSignal("CursorPosition"):Connect(OnSelectionChanged) Input:GetPropertyChangedSignal("CursorPosition"):Connect(OnCursorPositionChanged) Input.InputChanged:Connect(function(InputObject) if InputObject.UserInputType == Enum.UserInputType.MouseWheel then ScrollTowards(-InputObject.Position.Z) end end) RunService.PreRender:Connect(OnPreRender) end ---- Connections ---- return Editor
5,786
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/Profiler.luau
--!strict ---- Services ---- ---- Imports ---- ---- Settings ---- ---- Constants ---- local Profiler = {} --> Interface Instances local Container: typeof(script.Parent.Widget) = script.Widget local DebugContainer = Container.Debug local MetricTemplate = DebugContainer.Metric:Clone() type Profile = { Label: string, Metric: typeof(MetricTemplate), Tick: number, Time: number, Previous: Profile?, Children: { Profile }, } ---- Variables ---- local ActiveProfile: Profile? ---- Private Functions ---- local function isActive() return DebugContainer.Visible end local function formatPercentage(Percentage: number): string return `{math.floor(Percentage * 100)} %` end local function formatMilliseconds(Seconds: number): string return string.format("%.2f ms", Seconds * 1000) end local function updatePercentages(Time: number, Children: { Profile }) for _, Profile in Children do Profile.Metric.Percentage.Text = formatPercentage(Profile.Time / Time) updatePercentages(Time, Profile.Children) end end ---- Public Functions ---- function Profiler.profileBegin(Label: string) if not isActive() then return end local Metric = DebugContainer:FindFirstChild(Label) if not Metric then local New = MetricTemplate:Clone() New.Name = Label New.Time.Text = "? ms" New.Label.Text = string.upper(Label) New.Parent = DebugContainer Metric = New end local Profile: Profile = { Label = Label, Metric = Metric, Tick = os.clock(), Time = 0, Children = {}, Previous = ActiveProfile, } if ActiveProfile then table.insert(ActiveProfile.Children, Profile) end ActiveProfile = Profile end function Profiler.profileDiscard() if not isActive() then return end assert(ActiveProfile ~= nil, "No active profile.") ActiveProfile = ActiveProfile.Previous end function Profiler.profileEnd() if not isActive() then return end assert(ActiveProfile ~= nil, "No active profile.") local Elapsed = (os.clock() - ActiveProfile.Tick) ActiveProfile.Time = Elapsed ActiveProfile.Metric.Time.Text = formatMilliseconds(Elapsed) if not ActiveProfile.Previous then updatePercentages(Elapsed, ActiveProfile.Children) end ActiveProfile = ActiveProfile.Previous end function Profiler.toggle() DebugContainer.Visible = not DebugContainer.Visible end ---- Initialization ---- function Profiler.Initialize() DebugContainer.Metric:Destroy() end ---- Connections ---- return Profiler
562
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/State.luau
--!strict -- ******************************* -- -- AX3NX / AXEN -- -- ******************************* -- ---- Services ---- ---- Imports ---- ---- Settings ---- ---- Constants ---- local State = {} State.__index = State export type Class<T> = typeof(setmetatable( {} :: { Value: T, Observers: { [(T) -> ()]: boolean }, }, State )) ---- Variables ---- ---- Private Functions ---- ---- Public Functions ---- function State.new<T>(Value: T): Class<T> return setmetatable({ Value = Value, Observers = {}, }, State) end function State.Get<T>(self: Class<T>): T return self.Value end function State.Set<T>(self: Class<T>, Value: T) if self.Value ~= Value or type(Value) == "table" then self.Value = Value self:_updateObservers() end end function State.OnChange<T>(self: Class<T>, Observer: (T) -> ()): () -> () self.Observers[Observer] = true task.defer(function() self:_updateObservers() end) return function() self.Observers[Observer] = nil end end function State._updateObservers<T>(self: Class<T>) for Observer in self.Observers do task.spawn(Observer, self.Value) end end ---- Initialization ---- ---- Connections ---- return State
302
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/Table.luau
local Table = {} function Table.MergeArrays(a: { any }, b: { any }): { any } local Array = table.create(#a + #b) for _, Element in a do table.insert(Array, Element) end for _, Element in b do table.insert(Array, Element) end return Array end function Table.MergeDictionaries(a: { [any]: any }, b: { [any]: any }): { [any]: any } local Dictionary = table.clone(a) for Key, Value in b do if Dictionary[Key] then warn(`Key "{Key}" already exists in the first dictionary.`) continue end Dictionary[Key] = Value end return Dictionary end function Table.GetDictionaryKeys(Dictionary: { [any]: any }): { any } local Keys = {} for Key in Dictionary do table.insert(Keys, Key) end return Keys end return Table
199
1Axen/blink
1Axen-blink-3cb8d3d/plugin/src/init.server.luau
--!strict -- ******************************* -- -- AX3NX / AXEN -- -- ******************************* -- ---- Services ---- local RunService = game:GetService("RunService") local ScriptEditorService = game:GetService("ScriptEditorService") local Selection = game:GetService("Selection") local ServerStorage = game:GetService("ServerStorage") local StudioService = game:GetService("StudioService") local TweenService = game:GetService("TweenService") if RunService:IsRunning() then return end ---- Imports ---- local Editor = require("@self/Editor") local Profiler = require("@self/Profiler") local State = require("@self/State") local Generator = require("@compiler/Generator") local Parser = require("@compiler/Parser") ---- Settings ---- local FILES_FOLDER = "BLINK_CONFIGURATION_FILES" local TEMPLATE_FILE = { Name = "Template", Source = table.concat({ "type Example = u8", "event MyEvent {", "\tFrom: Server,", "\tType: Reliable,", "\tCall: SingleSync,", "\tData: Example", "}", }, "\n"), } local ERROR_WIDGET = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, false, true, 500, 240, 300, 240) local EDITOR_WIDGET = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Left, false, false, 360, 400, 300, 400) local SAVE_COLOR = Color3.fromRGB(0, 100, 0) local BUTTON_COLOR = Color3.fromRGB(30, 30, 30) local EXPAND_TWEEN = TweenInfo.new(0.2, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut) ---- Constants ---- local Toolbar = plugin:CreateToolbar("Blink Suite") local EditorButton = Toolbar:CreateButton("Editor", "Opens the configuration editor", "rbxassetid://118423040995617") EditorButton.ClickableWhenViewportHidden = true local Template = script.Widget local FileTemplate = Template.Side.Content.Top.Files.File:Clone() --> Remove templates --Template.Editor.Text.Line:Destroy() Template.Side.Content.Top.Files.File:Destroy() local ErrorWidget = plugin:CreateDockWidgetPluginGui("Generation Error", ERROR_WIDGET) ErrorWidget.Name = "Generation Error" ErrorWidget.Title = "Error" ErrorWidget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling local ErrorInterface = script.Error:Clone() ErrorInterface.Visible = true ErrorInterface.Parent = ErrorWidget local ErrorText: TextLabel = ErrorInterface.Text local EditorWidget = plugin:CreateDockWidgetPluginGui("Configuration Editor", EDITOR_WIDGET) EditorWidget.Name = "Blink Editor" EditorWidget.Title = "Configuration Editor" EditorWidget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling local EditorInterface = script.Widget EditorInterface.Size = UDim2.fromScale(1, 1) EditorInterface.Parent = EditorWidget local Side = EditorInterface.Side local Overlay = EditorInterface.Overlay local QuickActions = EditorInterface.Quick local QuickSave = QuickActions.Save local QuickClear = QuickActions.Clear local Content = Side.Content local Expand = Side.Expand local Settings = Side.Settings local Top = Content.Top local Bottom = Content.Bottom local Files = Top.Files local Import = Top.Title.Import local Search = Top.Title.Search.Input local Prompt = Bottom.Save local Buttons = Bottom.Buttons local GeneratePrompt = Bottom.Generate local GenerateButtons = GeneratePrompt.Buttons local Hint = GeneratePrompt.Hint local Generate = GenerateButtons.Generate local CancelGenerate = GenerateButtons.Cancel local Input = Prompt.Input local Save = Buttons.Save local Cancel = Buttons.Cancel --> Tweens local Tweens = { Editor = { Expand = { Side = TweenService:Create(Side, EXPAND_TWEEN, { Position = UDim2.new() }), Content = TweenService:Create(Content, EXPAND_TWEEN, { GroupTransparency = 0 }), Overlay = TweenService:Create(Overlay, EXPAND_TWEEN, { BackgroundTransparency = 0.5 }), Settings = TweenService:Create(Settings, EXPAND_TWEEN, { ImageTransparency = 1 }), }, Retract = { Side = TweenService:Create(Side, EXPAND_TWEEN, { Position = Side.Position }), Content = TweenService:Create(Content, EXPAND_TWEEN, { GroupTransparency = 1 }), Overlay = TweenService:Create(Overlay, EXPAND_TWEEN, { BackgroundTransparency = 1 }), Settings = TweenService:Create(Settings, EXPAND_TWEEN, { ImageTransparency = 0 }), }, }, } ---- Variables ---- local Saving = false local IsFirstTimeOpening = true local Expanded = State.new(false) local Selected: State.Class<Instance?> = State.new(nil :: any) local Generating: State.Class<StringValue?> = State.new(nil :: any) local Editing: string? local ProfilerTick = 0 local ProfilerClicks = 0 ---- Private Functions ---- --> Interface utility functions local function ShowError(Error: string) local Start = string.find(Error, "<font", 1, true) ErrorText.Text = string.sub(Error, Start or 1, #Error) ErrorText.RichText = true ErrorWidget.Enabled = true end local function PlayTweens(Tweens: { [string]: Tween }) for _, Tween in Tweens do Tween:Play() end end local function CreateModuleScript(Name: string, Source: string, Parent: Instance) local ModuleScript = Instance.new("ModuleScript") ModuleScript.Name = Name ModuleScript.Parent = Parent --> Update source after parenting to DM ScriptEditorService:UpdateSourceAsync(ModuleScript, function() return Source end) end local function RequestScriptPermissions(): boolean local Success = pcall(function() local Script = Instance.new("Script", script) Script:Destroy() end) return Success end local function ClearChildrenWhichAre(Parent: Instance, Class: string) for Index, Child in Parent:GetChildren() do if Child:IsA(Class) then Child:Destroy() end end end --> Files utility functions local function GetSaveFolder(): Folder local SaveFolder = ServerStorage:FindFirstChild(FILES_FOLDER) if not SaveFolder then local Folder = Instance.new("Folder") Folder.Name = FILES_FOLDER Folder.Parent = ServerStorage SaveFolder = Folder end return SaveFolder end local function GenerateFile(File: StringValue, Directory: Instance) local Source = File.Value local SourceParser = Parser.new() local Success, Error, AbstractSyntaxTree = pcall(function() return nil, SourceParser:Parse(Source) end) if not Success then ShowError(tostring(Error)) return end if not RequestScriptPermissions() then ShowError("File generation failed, plugin doesn't have script inject permissions.") warn("[BLINK]: File generation failed, plugin doesn't have script inject permissions.") return end local ServerSource = Generator.Generate("Server", AbstractSyntaxTree) local ClientSource = Generator.Generate("Client", AbstractSyntaxTree) local TypesSource = Generator.GenerateShared(AbstractSyntaxTree) local BlinkFolder: Folder = Directory:FindFirstChild("Blink") :: Folder if not BlinkFolder then local Folder = Instance.new("Folder") Folder.Name = "Blink" Folder.Parent = Directory BlinkFolder = Folder end --> Clear previous files BlinkFolder:ClearAllChildren() --> Generate output files CreateModuleScript("Types", TypesSource, BlinkFolder) CreateModuleScript("Server", ServerSource, BlinkFolder) CreateModuleScript("Client", ClientSource, BlinkFolder) end local function LoadFile(File: StringValue) Expanded:Set(false) Editing = File.Name Editor.SetSource(File.Value) end local function LoadFiles() --> Remove previous files Generating:Set() ClearChildrenWhichAre(Files, "Frame") --> Load new files local FileInstances = GetSaveFolder():GetChildren() table.sort(FileInstances, function(a, b) return a.Name < b.Name end) for _, File: StringValue in FileInstances :: { any } do local Name = File.Name local Frame = FileTemplate:Clone() local Buttons = Frame.Buttons Frame.Name = Name Frame.Title.Text = Name Buttons.Edit.MouseButton1Click:Connect(function() LoadFile(File) end) Buttons.Delete.MouseButton1Click:Connect(function() File:Destroy() LoadFiles() end) Buttons.Generate.MouseButton1Click:Connect(function() if GeneratePrompt.Visible then return end Generating:Set(File) end) Frame.Parent = Files end end local function SaveFile(Name: string, Source: string) local SaveFolder = GetSaveFolder() local SaveInstance: StringValue? = SaveFolder:FindFirstChild(Name) :: StringValue if not SaveInstance then local NewSaveInstance = Instance.new("StringValue") NewSaveInstance.Name = Name NewSaveInstance.Value = Source NewSaveInstance.Parent = SaveFolder return end SaveInstance.Value = Source end local function CreateTemplateFile() if ServerStorage:FindFirstChild(FILES_FOLDER) then return end SaveFile(TEMPLATE_FILE.Name, TEMPLATE_FILE.Source) LoadFile(GetSaveFolder():FindFirstChild(TEMPLATE_FILE.Name) :: StringValue) end local function HandleFirstTimeOpen() if IsFirstTimeOpening == false then return end CreateTemplateFile() LoadFiles() IsFirstTimeOpening = false end ---- Public Functions ---- local function OnSearch(PressedEnter: boolean) if not PressedEnter then return end local Query = Search.Text for _, Frame in Files:GetChildren() do if not Frame:IsA("Frame") then continue end if Query == "" then Frame.Visible = true continue end Frame.Visible = (string.find(Frame.Name, Query) ~= nil) end end local function OnSaveCompleted() Saving = false Prompt.Visible = false Cancel.Visible = false Save.BackgroundColor3 = BUTTON_COLOR end local function OnSaveActivated() if Saving then local Name = Input.Text if Name == "" then return end SaveFile(Name, Editor.GetSource()) LoadFiles() OnSaveCompleted() return end Saving = true Input.Text = Editing or "" Prompt.Visible = true Cancel.Visible = true Save.BackgroundColor3 = SAVE_COLOR end local function OnExpandActivated() HandleFirstTimeOpen() Expanded:Set(not Expanded:Get()) end local function OnEditorButtonClicked() HandleFirstTimeOpen() EditorWidget.Enabled = not EditorWidget.Enabled end local function OnEditorWidgetEnabled() EditorButton:SetActive(EditorWidget.Enabled) end local function OnQuickSave() if Expanded:Get() then return end if not Editing then Expanded:Set(true) OnSaveActivated() return end SaveFile(Editing, Editor.GetSource()) end local function OnQuickClear() if Expanded:Get() then return end Editor.SetSource("") end local function OnImport() local File: File? = StudioService:PromptImportFile({ "blink", "txt" }) if not File then return end Editing = nil Expanded:Set(false) Editor.SetSource(File:GetBinaryContents()) end local function OnExpandRightClicked() if ProfilerClicks == 0 then ProfilerTick = os.clock() ProfilerClicks += 1 return end local Elapsed = (os.clock() - ProfilerTick) if Elapsed > 1 then ProfilerTick = os.clock() return end ProfilerTick = 0 ProfilerClicks = 0 Profiler.toggle() end ---- Initialization ---- Editor.Initialize(EditorWidget) Profiler.Initialize() ---- Connections ---- Expanded:OnChange(function(Value) --Content.Visible = Value PlayTweens(Value and Tweens.Editor.Expand or Tweens.Editor.Retract) end) Selected:OnChange(function(Value: Instance?) Generate.TextTransparency = Value and 0 or 0.5 Hint.Text = Value and `<b>Selected</b>\n{Value:GetFullName()}` or "Select the location in which to generate the output scripts." end) Generating:OnChange(function(File: StringValue?) GeneratePrompt.Visible = (File ~= nil) end) Selection.SelectionChanged:Connect(function() local Instances = Selection:Get() Selected:Set(Instances[1]) end) Generate.MouseButton1Click:Connect(function() local File = Generating:Get() if not File then return end local Directory = Selected:Get() if not Directory then return end Generating:Set() GenerateFile(File, Directory) end) CancelGenerate.MouseButton1Click:Connect(function() Generating:Set() end) Import.MouseButton1Click:Connect(OnImport) Search.FocusLost:Connect(OnSearch) Save.MouseButton1Click:Connect(OnSaveActivated) Cancel.MouseButton1Click:Connect(OnSaveCompleted) Expand.MouseButton1Click:Connect(OnExpandActivated) Expand.MouseButton2Click:Connect(OnExpandRightClicked) QuickSave.MouseButton1Click:Connect(OnQuickSave) QuickClear.MouseButton1Click:Connect(OnQuickClear) EditorButton.Click:Connect(OnEditorButtonClicked) EditorWidget:GetPropertyChangedSignal("Enabled"):Connect(OnEditorWidgetEnabled)
2,959
1Axen/blink
1Axen-blink-3cb8d3d/src/CLI/Utility/GetDefinitionFilePath.luau
--!strict ---- Imports ---- local PathParser = require("../../Modules/Path") local fs = require("@lune/fs") ---- Settings ---- local EXTENSIONS = { "", ".txt", ".blink" } return function(Path: string): string local Directory, Filename = PathParser.Components(Path) Directory = Directory or "./" assert(Filename, `Unable to parse filename from {Path}, path may be malformed!`) for _, Extension in EXTENSIONS do local Temporary = `{Directory}{Filename}{Extension}` if fs.isFile(Temporary) then return Temporary end end return Path end
131
1Axen/blink
1Axen-blink-3cb8d3d/src/CLI/Utility/Watch.luau
--!strict ---- Imports ---- local dateTime = require("@lune/datetime") local fs = require("@lune/fs") local stdio = require("@lune/stdio") local task = require("@lune/task") local Compile = require("./Compile") local GetDefinitionFilePath = require("./GetDefinitionFilePath") local PathParser = require("../../Modules/Path") ---- Settings ---- type DateTime = dateTime.DateTime local IMPORT_PATTERN = `import "([%w%/%.-_]+)"` local WATCH_OPTIONS: Compile.CompileOptions = { Debug = false, Silent = true, Compact = false, YesToEverything = true, OutputAbstractSyntaxTree = false, } ---- Constants ---- local Utility = {} ---- Variables ---- ---- Private Functions ---- local function Color(Color: stdio.Color, Text: string): string return `{stdio.color(Color)}{Text}{stdio.color("reset")}` end local function BuildImportsArray(Entry: string, PreviousArray: { string }?): { string } local Array = PreviousArray or {} table.insert(Array, Entry) local Source = fs.readFile(Entry) local Directory = PathParser.Directory(Entry) local Iterator = string.gmatch(Source, IMPORT_PATTERN) while true do local Path = Iterator() if not Path then break end Path = `{Directory}{Path}` Path = GetDefinitionFilePath(Path) if not fs.isFile(Path) then error(`No file to import at "{Path}"`) end --> Prevent repeats if table.find(Array, Path) then continue end BuildImportsArray(Path, Array) end return Array end ---- Public Functions ---- function Utility.Watch(Path: string) local FilePath = GetDefinitionFilePath(Path) local Imports: { string } _G.WATCH_THREAD = true local function Traverse() --> Resolve imports local OldImports = Imports and #Imports or 0 Imports = BuildImportsArray(FilePath) if OldImports ~= #Imports then print( `Blink is watching for changes:\n\tEntry: {Color("yellow", FilePath)}\n\tImports: {Color( "yellow", tostring(#Imports - 1) )}` ) end return true end local function Recompile() Traverse() Compile.Compile(Path, WATCH_OPTIONS) end --> Initial traversal local InitialSuccess, Why = pcall(Traverse) if not InitialSuccess then warn(`There was an error while trying to start the watcher thread:\n{Why}`) return end --> Watch loop local Timestamps: { [string]: number } = {} while true do local FileChanged = false for _, File in Imports do local Metadata = fs.metadata(File) --> Make sure file still exists if not Metadata.exists then continue end local ModifiedAt = Metadata.modifiedAt and Metadata.modifiedAt.unixTimestampMillis or 0 local LastModifiedA = Timestamps[File] Timestamps[File] = ModifiedAt if ModifiedAt ~= LastModifiedA then FileChanged = true end end if FileChanged then pcall(Recompile) end task.wait(1) end end ---- Initialization ---- ---- Connections ---- return Utility
726
1Axen/blink
1Axen-blink-3cb8d3d/src/CLI/init.luau
--!native --!optimize 2 ---- Imports ---- local process = require("@lune/process") local stdio = require("@lune/stdio") local Compile = require("@self/Utility/Compile") local Watch = require("@self/Utility/Watch") ---- Settings ---- type Argument = { Hidden: true?, Aliases: { string }, Description: string, } local ARGUMENTS: { [string]: Argument } = { Help = { Aliases = { "-h", "--help" }, Description = "Print help information", }, Version = { Aliases = { "-v", "--version" }, Description = "Print version information", }, Watch = { Aliases = { "-w", "--watch" }, Description = "Watch [CONFIG] for changes, automatically recompile upon one occuring", }, Silent = { Aliases = { "-q", "--quiet" }, Description = "Silence program output", }, Compact = { Aliases = { "-c", "--compact" }, Description = "Compacts error output, the full message is still printed out after a compacted version.", }, YesToAll = { Aliases = { "-y", "--yes" }, Description = "Accept all prompts", }, OutputAst = { Hidden = true, Aliases = { "--ast" }, Description = "Output the AST of [CONFIG]", }, Statistics = { Hidden = true, Aliases = { "-S", "--stats" }, Description = "Output compilation time statistics", }, } ---- Functions ----- local function Style(Text: string, Style: stdio.Style): string return `{stdio.style(Style)}{Text}{stdio.style("reset")}` end local function Color(Text: string, Color: stdio.Color): string return `{stdio.color(Color)}{Text}{stdio.color("reset")}` end local function PrintHelpMessage() print(Color(Style("USAGE:", "bold"), "yellow")) print("\tblink.exe [CONFIG] [OPTIONS]") print(Color(Style("OPTIONS:", "bold"), "yellow")) local Sorted: { Argument } = {} for _, Argument in ARGUMENTS do if not Argument.Hidden then table.insert(Sorted, Argument) end end table.sort(Sorted, function(a, b) return a.Aliases[1] < b.Aliases[1] end) for _, Argument in Sorted do print( `\t{stdio.color("green")}{table.concat(Argument.Aliases, ", ")}{stdio.color("reset")}\t{Argument.Description}` ) end end ---- Main ---- print(`{Color("Blink", "green")} {_G.VERSION or "DEBUG"}`) local RawArguments = process.args if #RawArguments < 1 then PrintHelpMessage() return nil end local Path = RawArguments[1] --> Parse optional arguments local Arguments = {} for Key, Argument in ARGUMENTS do local IsSupplied = false for _, Alias in Argument.Aliases do if table.find(RawArguments, Alias) ~= nil then IsSupplied = true break end end Arguments[Key] = IsSupplied end if Arguments.Help then PrintHelpMessage() return nil end if Arguments.Version then return nil end if not Arguments.Watch then local CompileOptions: Compile.CompileOptions = { Debug = (_G.RELEASE == nil) or Arguments.Statistics, Silent = Arguments.Silent, Compact = Arguments.Compact, YesToEverything = Arguments.YesToAll, OutputAbstractSyntaxTree = Arguments.OutputAst, } Compile.Compile(Path, CompileOptions) else Watch.Watch(Path) end return nil
821
1Axen/blink
1Axen-blink-3cb8d3d/src/Generator/Blocks.luau
type BranchType = "Conditional" | "Default" type EqualityOperator = "Not" | "Equals" | "Greater" | "Less" | "GreaterOrEquals" | "LessOrEquals" type Method = "Read" | "Allocate" | "None" type Operation = { Method: Method, Bytes: number, Counts: number, Variable: string?, } local DEFAULT_UNIQUE = "BLOCK_START" local ARRAY_UNIQUE = "ARRAY_START" local Operators = { Not = "~=", Equals = "==", Greater = ">", Less = "<", GreaterOrEquals = ">=", LessOrEquals = "<=", } local Block = {} Block.__index = Block export type Block = typeof(setmetatable( {} :: { Unique: string, Parent: Block?, Indent: number, Cursor: number, Unsafe: boolean, Content: { string }, Operation: Operation, Variables: { [string]: boolean }, OperationOffset: number, }, Block )) function Block.new<Parent>(Parent: Block?, Unique: string?): Block local Indent = (Parent and Parent.Indent + 1 or 1) return setmetatable({ Unique = Unique or DEFAULT_UNIQUE, Parent = Parent, Indent = Indent, Cursor = 1, Unsafe = false, Content = table.create(64), Operation = { Method = "None", Bytes = 0, Counts = 0, }, Variables = {}, OperationOffset = 0, }, Block) end function Block.DisableOperationOptimisations(self: Block): Block self.Unsafe = true return self end function Block._operation(self: Block, Method: Method, Bytes: number): string local Operation = self.Operation if Operation.Method ~= "None" and Operation.Method ~= Method then error(`Block can't both Allocate and Read`) end if self.Unsafe then local Counts = Operation.Counts local Variable = `OFFSET_{Counts}` Operation.Counts += 1 self:Line(`local {Variable} = {Method}({Bytes})`) return Variable end local Offset = Operation.Bytes Operation.Bytes += Bytes Operation.Method = Method if self.Unique ~= DEFAULT_UNIQUE then self:Comment(`{Method} {Bytes}`) local OperationOffset = `OPERATION_OFFSET_{self.OperationOffset}` self.OperationOffset += 1 self:Line(`local {OperationOffset} = {self.Unique}`) self:Line(`{self.Unique} += {Bytes}`) return OperationOffset end return `{self.Unique} + {Offset}` end function Block.Read(self: Block, Bytes: number): string return self:_operation("Read", Bytes) end function Block.Allocate(self: Block, Bytes: number): string return self:_operation("Allocate", Bytes) end function Block._lineFront(self: Block, Text: string, Indent: number): Block table.insert(self.Content, self.Cursor, `{string.rep("\t", Indent or self.Indent)}{Text}\n`) return self end function Block._appendOperations(self: Block): Block local Operation = self.Operation local Variable = Operation.Variable if Operation.Method == "None" then return self end local Append = `local {self.Unique} = {Operation.Method}({Operation.Bytes}{Variable and ` * {Variable}` or ""})` self:_lineFront(Append, self.Unique ~= DEFAULT_UNIQUE and self.Indent - 1 or self.Indent) self:_lineFront(`-- {Operation.Method} BLOCK: {Operation.Bytes} bytes`) return self end function Block.Declare(self: Block, Variable: string, Initialize: boolean?): string local Block = self local Declared = false local IsFieldAccess = (string.find(Variable, "[%.%[]", 1) ~= nil) --> Ignore field acceses if IsFieldAccess then return Variable end --> Search for variable declaration in block hierarchy while Block do if Block.Variables[Variable] then Declared = true break end Block = Block.Parent end if Declared then return Variable end --> Declare variable within current block self.Variables[Variable] = true if Initialize then self:Line(`local {Variable}`) end return `local {Variable}` end function Block.EmptyDeclare(self: Block, Variable: string) self.Variables[Variable] = true end function Block.Advance(self: Block, Offset: number): Block self.Cursor += Offset return self end function Block.Line(self: Block, Text: string, Indent: number?): Block table.insert(self.Content, `{string.rep("\t", Indent or self.Indent)}{Text}\n`) return self end function Block.Character(self: Block, Character: string): Block table.insert(self.Content, Character) return self end function Block.Comment(self: Block, Content: string): Block self:Line(`-- {Content}`) return self end function Block.Lines(self: Block, Lines: { string }, Indent: number?): Block local Indent = Indent or 0 --> FAST PATH if Indent == 0 then table.move(Lines, 1, #Lines, #self.Content + 1, self.Content) return self end local Indentation = string.rep("\t", Indent) for Index, Line in Lines do table.insert(self.Content, `{Indentation}{Line}`) end return self end function Block.Multiline(self: Block, Content: string, Indent: number?): Block local Lines = string.split(Content, "\n") for Index, Line in Lines do table.insert(self.Content, `{string.rep("\t", Indent or 0)}{Line}\n`) end return self end function Block.Loop(self: Block, Counter: string, Length: string): Block local Loop = Block.new(self, `{ARRAY_UNIQUE}_{self.Indent}`) Loop:Line(`for {Counter}, {Length} do`, Loop.Indent - 1) Loop.Operation.Variable = Length return Loop end function Block.While(self: Block, Condition: string): Block self:Line(`while ({Condition}) do`) return Block.new(self) end function Block.Iterator(self: Block, Key: string, Value: string, Iterator: string): Block self:Line(`for {Key}, {Value} in {Iterator} do`) return Block.new(self) end function Block.Compare(self: Block, Left: string, Right: string, Operator: EqualityOperator): Block self:Line(`if {Left} {Operators[Operator]} {Right} then`) return Block.new(self) end function Block.Branch( self: Block, Branch: BranchType, Left: string?, Right: string?, Operator: EqualityOperator? ): Block local Parent = self.Parent assert(Parent, "Cannot branch the top level block.") --> Push previous branch content self:_appendOperations() Parent:Lines(self.Content) --> Create new branch if Branch == "Conditional" then Parent:Line(`elseif {Left} {Operators[Operator]} {Right} then`) else Parent:Line(`else`) end return Block.new(Parent) end function Block.Return(self: Block, Return: string): Block self:Line(`return {Return}`) return self end function Block.End(self: Block): Block self:_appendOperations() local Parent = self.Parent if Parent then Parent:Lines(self.Content) Parent:Line("end") return Parent end self:Line("end", 0) return self end function Block.Wrap(self: Block, Front: string, Back: string): Block local First = self.Content[1] self.Content[1] = `{Front}{First}` local Last = self.Content[#self.Content] self.Content[#self.Content] = `{string.gsub(Last, "\n", "")}{Back}\n` return self end function Block.Unwrap(self: Block) return table.concat(self.Content) end local Function = {} Function.__index = Function setmetatable(Function, Block) function Function.new(Name: string, Arguments: string, Return: string?, IsInlined: boolean?, Localised: boolean?): Block local Block = Block.new(nil) setmetatable(Block, Function) local Suffix = Return and `: {Return}` or "" Block:Advance(1) if IsInlined then Block:Line(`{Name} = function({Arguments}){Suffix}`, 0) elseif Localised then Block:Line(`local function {Name}({Arguments}){Suffix}`, 0) else Block:Line(`function {Name}({Arguments}){Suffix}`, 0) end return Block end local Connection = {} Connection.__index = Connection setmetatable(Connection, Block) function Connection.new(Signal: string, Arguments: string): Block local Block = Block.new() setmetatable(Block, Connection) Block:Advance(1) Block:Line(`{Signal}:Connect(function({Arguments})`, 0) return Block end function Connection.End(self: Block, Return: string?): Block self:Line("end)", 0) return self end return { Block = Block.new, Function = Function.new, Connection = Connection.new, }
2,045
1Axen/blink
1Axen-blink-3cb8d3d/src/Generator/Prefabs.luau
--!native --!optimize 2 local Blocks = require("./Blocks") local Parser = require("../Parser") type Block = Blocks.Block type Writer = (Value: string, Block: Block, Range: NumberRange?, Components: { string }?) -> () type Reader = (Variable: string, Block: Block, Range: NumberRange?, Components: { string }?) -> () type Generate = ( Declaration: Parser.Primitive, Variable: string?, Read: Block, Write: Block, WriteValidations: boolean? ) -> () type TypePrefab = { Read: Reader, Write: Writer, } type AssertPrefab = { Lower: string, Upper: string, Exact: string?, } type AssertGenerator = (Variable: string, ...any) -> AssertPrefab local SEND_BUFFER = "SendBuffer" local RECIEVE_BUFFER = "RecieveBuffer" local SEND_POSITION = "SendOffset" local BYTE = 1 local SHORT = 2 local INTEGER = 4 local HALF_FLOAT = 2 local FLOAT = 4 local DOUBLE = 8 local Types = {} local Asserts = { number = function(Variable: string, Min: number, Max: number): AssertPrefab return { Lower = `if {Variable} < {Min} then error(\`Expected "{Variable}" to be larger than {Min}, got \{{Variable}} instead.\`) end`, Upper = `if {Variable} > {Max} then error(\`Expected "{Variable}" to be smaller than {Max}, got \{{Variable}} instead.\`) end`, Exact = `if {Variable} ~= {Max} then error(\`Expected "{Variable}" to be equal to {Max}, got \{{Variable}\} instead.\`) end`, } end, string = function(Variable: string, Min: number, Max: number): AssertPrefab return { Lower = `if #{Variable} < {Min} then error(\`Expected length of "{Variable}" to be larger than {Min}, got \{#{Variable}} instead.\`) end`, Upper = `if #{Variable} > {Max} then error(\`Expected length of "{Variable}" to be smaller than {Max}, got \{#{Variable}} instead.\`) end`, Exact = `if #{Variable} ~= {Max} then error(\`Expected length of "{Variable}" to equal to {Max}, got \{#{Variable}} instead.\`) end`, } end, vector = function(Variable: string, Min: number, Max: number): AssertPrefab return { Lower = `if {Variable}.Magnitude < {Min} then error(\`Expected magnitude of "{Variable}" to be larger than {Min}, got \{{Variable}.Magnitude} instead.\`) end`, Upper = `if {Variable}.Magnitude > {Max} then error(\`Expected magnitude of "{Variable}" to be smaller than {Max}, got \{{Variable}.Magnitude} instead.\`) end`, Exact = `if {Variable}.Magnitude ~= {Max} then error(\`Expected magnitude of "{Variable}" to equal to {Max}, got \{{Variable}.Magnitude} instead.\`) end`, } end, buffer = function(Variable: string, Min: number, Max: number): AssertPrefab return { Lower = `if buffer.len({Variable}) < {Min} then error(\`Expected size of "{Variable}" to be larger than {Min}, got \{buffer.len({Variable})} instead.\`) end`, Upper = `if buffer.len({Variable}) > {Max} then error(\`Expected size of "{Variable}" to be smaller than {Max}, got \{buffer.len({Variable})} instead.\`) end`, Exact = `if buffer.len({Variable}) ~= {Max} then error(\`Expected size of "{Variable}" to equal to {Max}, got \{buffer.len({Variable})} instead.\`) end`, } end, Instance = function(Variable: string, Class: string): AssertPrefab local TypeAssertion = `if typeof({Variable}) ~= "Instance" then error(\`Expected an Instance, got \{typeof({Variable})} instead.\`) end` return { Lower = `error("Something has gone wrong")`, Upper = `error("Something has gone wrong")`, Exact = if Class == "Instance" then TypeAssertion else `{TypeAssertion}\nif not {Variable}:IsA("{Class}") then error(\`Expected an Instance of type "{Class}", got "\{{Variable}.ClassName}" instead.\`) end`, } end, } local Structures = { Array = nil :: any, } local Primitives: { [string]: { Type: string | (Declaration: Parser.Primitive) -> string, Generate: Generate, } } = {} local NumberTypeBounds = { { Bits = 8, Maximum = 255, Type = "u8" }, { Bits = 16, Maximum = 65535, Type = "u16" }, { Bits = 32, Maximum = 4294967295, Type = "u32" }, } local function GetTypeToUse(UpperSize: number): TypePrefab for _, NumberType in NumberTypeBounds do if NumberType.Maximum >= UpperSize then return Types[NumberType.Type] end end error("Value is too large to be written to a buffer.") end local function GetTypeToUseByBits(UpperBits: number): TypePrefab for _, NumberType in NumberTypeBounds do if NumberType.Bits >= UpperBits then return Types[NumberType.Type] end end error("Value is too large to be written to a buffer.") end local function GeneratePrimitivePrefab(Type: string, Prefab: TypePrefab, AssertGenerator: AssertGenerator?): Generate return function( Declaration: Parser.Primitive, Variable: string?, Read: Block, Write: Block, WriteValidations: boolean? ) local Value = Declaration.Value local Tokens = Declaration.Tokens local Variable = Variable or "Value" local Range = Value.Range local Class = Value.Class local Components = Value.Components local Primitive = Tokens.Primitive.Value local IsVariableSize = (Range and Range.Max ~= Range.Min) local function GenerateValidation(Block: Block, Variable: string) if Block == Write and WriteValidations ~= true then return end if Block == Write and Type ~= "any" then Block:Compare(`typeof({Variable})`, `"{Type}"`, "Not") :Line(`error(\`Expected {Variable} to be of type {Type}, got \{type({Variable})} instead.\`)`) :End() end if not AssertGenerator then return end if Range then local Assert = AssertGenerator(Variable, Range.Min, Range.Max) if not IsVariableSize and Assert.Exact then Block:Line(Assert.Exact) else Block:Line(Assert.Lower) Block:Line(Assert.Upper) end elseif Primitive == "Instance" and Class then local Assert = AssertGenerator(Variable, Class) if Block == Write then Block:Compare(Variable, "nil", "Not"):Multiline(Assert.Exact, Block.Indent + 1):End() else Block:Multiline(Assert.Exact, Block.Indent) end end end GenerateValidation(Write, Variable) Prefab.Read(Variable, Read, Range, Components) Prefab.Write(Variable, Write, Range, Components) GenerateValidation(Read, Variable) end end local function GenerateNumberGenerator(Type: string, Size: number): (TypePrefab, { Type: string, Generate: Generate }) local Prefab = { Read = function(Variable: string, Block: Block) Block:Line(`{Block:Declare(Variable)} = buffer.read{Type}({RECIEVE_BUFFER}, {Block:Read(Size)})`) end, Write = function(Value: string, Block: Block) Block:Line(`buffer.write{Type}({SEND_BUFFER}, {Block:Allocate(Size)}, {Value})`) end, } local Primitive = { Type = "number", Generate = GeneratePrimitivePrefab("number", Prefab, Asserts.number), } return Prefab, Primitive end --> Numbers Types.u8, Primitives.u8 = GenerateNumberGenerator("u8", BYTE) Types.u16, Primitives.u16 = GenerateNumberGenerator("u16", SHORT) Types.u32, Primitives.u32 = GenerateNumberGenerator("u32", INTEGER) Types.i8, Primitives.i8 = GenerateNumberGenerator("i8", BYTE) Types.i16, Primitives.i16 = GenerateNumberGenerator("i16", SHORT) Types.i32, Primitives.i32 = GenerateNumberGenerator("i32", INTEGER) Types.f32, Primitives.f32 = GenerateNumberGenerator("f32", FLOAT) Types.f64, Primitives.f64 = GenerateNumberGenerator("f64", DOUBLE) Types.f16 = { Read = function(Variable: string, Block: Block) Types.u16.Read("Encoded", Block) Block:Declare(Variable, true) Block:Line(`local MantissaExponent = Encoded % 0x8000`) Block:Compare("MantissaExponent", "0b0_11111_0000000000 ", "Equals") :Compare("Encoded // 0x8000", "1", "Equals") :Line(`{Variable} = -math.huge`) :Branch("Default") :Line(`{Variable} = math.huge`) :End() :Branch("Conditional", "MantissaExponent", "0b1_11111_0000000000 ", "Equals") :Line(`{Variable} = 0 / 0`) :Branch("Conditional", "MantissaExponent", "0b0_00000_0000000000 ", "Equals") :Line(`{Variable} = 0`) :Branch("Default") :Lines({ "local Mantissa = MantissaExponent % 0x400\n", "local Exponent = MantissaExponent // 0x400\n", "local Fraction;\n", "if Exponent == 0 then\n", " Fraction = Mantissa / 0x400\n", "else\n", " Fraction = Mantissa / 0x800 + 0.5\n", "end\n", "local Result = math.ldexp(Fraction, Exponent - 14)\n", }, Block.Indent + 1) :Line(`{Variable} = if Encoded // 0x8000 == 1 then -Result else Result`) :End() end, Write = function(Value: string, Block: Block) local Allocation = Block:Allocate(HALF_FLOAT) Block:Compare(Value, "65504", "Greater") :Line(`buffer.writeu16({SEND_BUFFER}, {Allocation}, 0b0_11111_0000000000)`) :Branch("Conditional", Value, "-65504", "Less") :Line(`buffer.writeu16({SEND_BUFFER}, {Allocation}, 0b1_11111_0000000000)`) :Branch("Conditional", Value, Value, "Not") :Line(`buffer.writeu16({SEND_BUFFER}, {Allocation}, 0b1_11111_0000000001)`) :Branch("Conditional", Value, "0", "Equals") :Line(`buffer.writeu16({SEND_BUFFER}, {Allocation}, 0)`) :Branch("Default") :Line(`local float = {Value}`) :Lines({ "local Abosulte = math.abs(float)\n", "local Interval = math.ldexp(1, math.floor(math.log(Abosulte, 2)) - 10)\n", "local RoundedValue = (Abosulte // Interval) * Interval\n", "local Fraction, Exponent = math.frexp(RoundedValue)\n", "Exponent += 14\n", "local Mantissa = math.round(if Exponent <= 0\n", " then Fraction * 0x400 / math.ldexp(1, math.abs(Exponent))\n", " else Fraction * 0x800) % 0x400\n", "local Result = Mantissa\n", " + math.max(Exponent, 0) * 0x400\n", " + if float < 0 then 0x8000 else 0\n", }, Block.Indent + 1) :Line(`buffer.writeu16({SEND_BUFFER}, {Allocation}, Result)`) :End() end, } Primitives.f16 = { Type = "number", Generate = GeneratePrimitivePrefab("number", Types.f16, Asserts.number), } --> Boolean do Types.boolean = { Read = function(Variable: string, Block: Block) Block:Line(`{Block:Declare(Variable)} = (buffer.readu8({RECIEVE_BUFFER}, {Block:Read(BYTE)}) == 1)`) end, Write = function(Value: string, Block: Block) Block:Line(`buffer.writeu8({SEND_BUFFER}, {Block:Allocate(BYTE)}, {Value} and 1 or 0)`) end, } Primitives.boolean = { Type = "boolean", Generate = GeneratePrimitivePrefab("boolean", Types.boolean), } end --> String do Types.string = { Read = function(Variable: string, Block: Block, Range: NumberRange?) --> Fixed size string if Range and Range.Min == Range.Max then Block:Line( `{Block:Declare(Variable)} = buffer.readstring({RECIEVE_BUFFER}, {Block:Read(Range.Min)}, {Range.Min})` ) return end local Upper = Range and Range.Max or (2 ^ 16 - 1) local LengthType = GetTypeToUse(Upper) LengthType.Read("Length", Block) Block:Line(`{Block:Declare(Variable)} = buffer.readstring({RECIEVE_BUFFER}, Read(Length), Length)`) end, Write = function(Value: string, Block: Block, Range: NumberRange?) if Range and Range.Min == Range.Max then Block:Line(`buffer.writestring({SEND_BUFFER}, {Block:Allocate(Range.Min)}, {Value}, {Range.Min})`) return end local Upper = Range and Range.Max or (2 ^ 16 - 1) local LengthType = GetTypeToUse(Upper) Block:Line(`local Length = #{Value}`) LengthType.Write("Length", Block) Block:Line(`Allocate(Length)`) Block:Line(`buffer.writestring({SEND_BUFFER}, {SEND_POSITION}, {Value}, Length)`) end, } Primitives.string = { Type = "string", Generate = GeneratePrimitivePrefab("string", Types.string, Asserts.string), } end --> Vector do Types.vector = { Read = function(Variable: string, Block: Block, _, Components: { string }?) local Prefab: TypePrefab = Types.f32 if Components then Prefab = Types[Components[#Components]] or Prefab end Prefab.Read("X", Block) Prefab.Read("Y", Block) Prefab.Read("Z", Block) Block:Line(`{Block:Declare(Variable)} = Vector3.new(X, Y, Z)`) end, Write = function(Value: string, Block: Block, _, Components: { string }?) local Prefab: TypePrefab = Types.f32 if Components then Prefab = Types[Components[#Components]] or Prefab end Block:Line(`local Vector = {Value}`) Prefab.Write("Vector.X", Block) Prefab.Write("Vector.Y", Block) Prefab.Write("Vector.Z", Block) end, } Primitives.vector = { Type = "Vector3", Generate = GeneratePrimitivePrefab("Vector3", Types.vector, Asserts.vector), } end --> Buffer do Types.buffer = { Read = function(Variable: string, Block: Block, Range: NumberRange?) if Range and Range.Min == Range.Max then local Length = Range.Max Block:Line(`{Block:Declare(Variable)} = buffer.create({Length})`) Block:Line(`buffer.copy({Variable}, 0, {RECIEVE_BUFFER}, {Block:Read(Length)}, {Length})`) return end local Upper = Range and Range.Max or (2 ^ 16 - 1) local LengthType = GetTypeToUse(Upper) LengthType.Read("Length", Block) Block:Line(`{Block:Declare(Variable)} = buffer.create(Length)`) Block:Line(`buffer.copy({Variable}, 0, {RECIEVE_BUFFER}, Read(Length), Length)`) end, Write = function(Value: string, Block: Block, Range: NumberRange?) if Range and Range.Min == Range.Max then Block:Line(`buffer.copy({SEND_BUFFER}, {Block:Allocate(Range.Max)}, {Value}, 0, {Range.Max})`) return end local Upper = Range and Range.Max or (2 ^ 16 - 1) local LengthType = GetTypeToUse(Upper) Block:Line(`local Length = buffer.len({Value})`) LengthType.Write("Length", Block) Block:Line(`Allocate(Length)`) Block:Line(`buffer.copy({SEND_BUFFER}, {SEND_POSITION}, {Value}, 0, Length)`) end, } Primitives.buffer = { Type = "buffer", Generate = GeneratePrimitivePrefab("buffer", Types.buffer, Asserts.buffer), } end --> CFrame do Types.CFrame = { Read = function(Variable: string, Block: Block, _, Components: { string }?) local Prefab: TypePrefab = Types.f32 if Components then Prefab = Types[Components[1]] end Types.vector.Read("Position", Block, nil, Components) Prefab.Read("rX", Block) Prefab.Read("rY", Block) Prefab.Read("rZ", Block) Block:Line(`{Block:Declare(Variable)} = CFrame.new(Position) * CFrame.fromOrientation(rX, rY, rZ)`) end, Write = function(Value: string, Block: Block, _, Components: { string }?) local Prefab: TypePrefab = Types.f32 if Components then Prefab = Types[Components[1]] end Types.vector.Write(`{Value}.Position`, Block, nil, Components) Block:Line(`local rX, rY, rZ = {Value}:ToOrientation()`) Prefab.Write("rX", Block) Prefab.Write("rY", Block) Prefab.Write("rZ", Block) end, } Primitives.CFrame = { Type = "CFrame", Generate = GeneratePrimitivePrefab("CFrame", Types.CFrame), } end --> Color3 do Types.Color3 = { Read = function(Variable: string, Block: Block) local R = Block:Read(BYTE) local G = Block:Read(BYTE) local B = Block:Read(BYTE) Block:Line( `{Block:Declare(Variable)} = Color3.fromRGB(buffer.readu8({RECIEVE_BUFFER}, {R}), buffer.readu8({RECIEVE_BUFFER}, {G}), buffer.readu8({RECIEVE_BUFFER}, {B}))` ) end, Write = function(Value: string, Block: Block) Block:Line(`local Color = {Value}`) Types.u8.Write("Color.R * 255", Block) Types.u8.Write("Color.G * 255", Block) Types.u8.Write("Color.B * 255", Block) end, } Primitives.Color3 = { Type = "Color3", Generate = GeneratePrimitivePrefab("Color3", Types.Color3), } end --> DateTime do Types.DateTime = { Read = function(Variable: string, Block: Block) local UnixTimestamp = Block:Read(BYTE) Block:Line( `{Block:Declare(Variable)} = DateTime.fromUnixTimestamp(buffer.readf64({RECIEVE_BUFFER}, {UnixTimestamp}))` ) end, Write = function(Value: string, Block: Block) Block:Line(`local DateTime = {Value}`) Types.f64.Write(`DateTime.UnixTimestamp`, Block) end, } Primitives.DateTime = { Type = "DateTime", Generate = GeneratePrimitivePrefab("DateTime", Types.DateTime), } end --> DateTimeMillis do Types.DateTimeMillis = { Read = function(Variable: string, Block: Block) local UnixTimestampMillis = Block:Read(BYTE) Block:Line( `{Block:Declare(Variable)} = DateTime.fromUnixTimestampMillis(buffer.readf64({RECIEVE_BUFFER}, {UnixTimestampMillis}))` ) end, Write = function(Value: string, Block: Block) Block:Line(`local DateTimeMillis = {Value}`) Types.f64.Write(`DateTimeMillis.UnixTimestampMillis`, Block) end, } Primitives.DateTimeMillis = { Type = "DateTime", Generate = GeneratePrimitivePrefab("DateTime", Types.DateTimeMillis), } end --> BrickColor do Types.BrickColor = { Read = function(Variable: string, Block: Block) local Number = Block:Read(SHORT) Block:Line(`{Block:Declare(Variable)} = BrickColor.new(buffer.readu16({RECIEVE_BUFFER}, {Number}))`) end, Write = function(Value: string, Block: Block) Block:Line(`local BrickColor = {Value}`) Types.u16.Write("BrickColor.Number", Block) end, } Primitives.BrickColor = { Type = "BrickColor", Generate = GeneratePrimitivePrefab("BrickColor", Types.BrickColor), } end --> Instance do Types.Instance = { Read = function(Variable: string, Block: Block) --Block:Line("RecieveInstanceCursor += 1") Block:Line(`{Block:Declare(Variable)} = RecieveInstances[RecieveInstanceCursor]`) end, Write = function(Value: string, Block: Block) Block:Line(`table.insert(SendInstances, {Value} or Null)`) end, } Primitives.Instance = { Type = function(Declaration) return Declaration.Value.Class end, Generate = GeneratePrimitivePrefab("any", Types.Instance, Asserts.Instance), } end --> unknown do Types.unknown = { Read = function(Variable: string, Block: Block) Block:Line("RecieveInstanceCursor += 1") Block:Line(`{Block:Declare(Variable)} = RecieveInstances[RecieveInstanceCursor]`) end, Write = function(Value: string, Block: Block) Block:Line(`table.insert(SendInstances, if {Value} == nil then Null else {Value})`) end, } Primitives.unknown = { Type = "any", Generate = GeneratePrimitivePrefab("any", Types.unknown), } end return { Types = Types, Asserts = Asserts, Primitives = Primitives, Structures = Structures, GetTypeToUse = GetTypeToUse, GetTypeToUseByBits = GetTypeToUseByBits, }
5,303
1Axen/blink
1Axen-blink-3cb8d3d/src/Modules/Builder.luau
--!native --!optimize 2 local Builder = {} function Builder.new(): Builder local Strings = table.create(512) local function PushLines(Lines: { string }, Returns: number?, Tabs: number?) local Size = #Lines local Last = Lines[Size] local Tabs = Tabs or 0 local Returns = Returns or 0 --> FAST PATH :SUNGLASSES: if Tabs == 0 and Returns == 0 then table.move(Lines, 1, Size, #Strings + 1, Strings) return end local Indentation = string.rep("\t", Tabs) if Last == "" then Size -= 1 Lines[Size] = nil end for Index, Line in Lines do table.insert(Strings, `{Indentation}{Line}{Index == Size and string.rep("\n", Returns) or ""}`) end end return { Push = function(Text: string, Returns: number?, Tabs: number?) table.insert(Strings, `{string.rep("\t", Tabs or 0)}{Text}\n{string.rep("\n", Returns or 0)}`) end, PushFront = function(Text: string, Returns: number?, Tabs: number?) table.insert(Strings, 1, `{string.rep("\n", Returns or 1)}{Text}{string.rep("\t", Tabs or 0)}\n`) end, PushLines = PushLines, PushMultiline = function(Text: string, Returns: number?, Tabs: number?) PushLines(string.split(Text, "\n"), Returns, Tabs) end, Print = function() print(table.concat(Strings)) end, DumpNoClear = function() return table.concat(Strings) end, Dump = function(): string local Text = table.concat(Strings) table.clear(Strings) return Text end, DumpLines = function(): { string } return Strings end, } end export type Builder = typeof(Builder.new()) return Builder
459
1Axen/blink
1Axen-blink-3cb8d3d/src/Modules/Error.luau
--!native --!optimize 2 local IS_ROBLOX = (game ~= nil) local stdio local process if not IS_ROBLOX then stdio = require("@lune/stdio") process = require("@lune/process") end type Slice = { Line: number, Text: string, Spaces: number, Underlines: number, } export type Label = { Span: Span, Text: string, } type Color = "red" | "green" | "blue" | "black" | "white" | "cyan" | "purple" | "yellow" | "reset" export type Span = { Start: number, End: number, } local SpecialSymbols = { CLI = { Line = "─", Down = "│", DownDash = "┆", Cross = "┬", RightUp = "╭", LeftDown = "╯", RightDown = "╰", }, ROBLOX = { Line = "-", Down = "|", DownDash = " ", Cross = "-", RightUp = "╭", LeftDown = "╯", RightDown = "╰", }, } local Colors = { black = "rgb(0, 0, 0)", blue = "rgb(0, 0, 255)", cyan = "rgb(0, 255, 255)", green = "rgb(0, 255, 0)", purple = "rgb(163, 44, 196)", red = "rgb(255, 0, 0)", white = "rgb(255, 255, 255)", yellow = "rgb(255, 255, 0)", } local Compact = false local Error = { OnEmit = nil, LexerUnexpectedToken = 1001, ParserUnexpectedEndOfFile = 2001, ParserUnexpectedToken = 2002, ParserUnknownOption = 2003, ParserUnexpectedSymbol = 2004, ParserExpectedExtraToken = 2005, AnalyzeReferenceInvalidType = 3001, AnalyzeInvalidOptionalType = 3002, AnalyzeNestedMap = 3003, AnalyzeDuplicateField = 3004, AnalyzeReservedIdentifier = 3005, AnalyzeNestedScope = 3006, AnalyzeUnknownReference = 3007, AnalyzeInvalidRangeType = 3008, AnalyzeInvalidRange = 3009, AnalyzeDuplicateDeclaration = 3010, AnalyzeDuplicateTypeGeneric = 3011, AnalyzeInvalidGenerics = 3012, AnalyzeInvalidExport = 3013, AnalyzeUnknownImport = 3014, AnalyzeErrorWhileImporting = 3015, AnalyzeOptionAfterStart = 3016, } Error.__index = Error export type Class = typeof(setmetatable( {} :: { Labels: { Label }, Source: { string }, Message: string, Code: number, File: string, RawMessage: string, PrimarySpan: Span?, }, Error )) local Symbols = IS_ROBLOX and SpecialSymbols.ROBLOX or SpecialSymbols.CLI local function Color(Text: string, Color: Color): string if IS_ROBLOX then return `<font color="{Colors[Color]}">{Text}</font>` end return `{stdio.color(Color)}{Text}{stdio.color("reset")}` end local function Style(Text: string, Style: "bold" | "dim"): string if IS_ROBLOX then return Text end return `{stdio.style(Style)}{Text}{stdio.style("reset")}` end function Error.SetCompact(Value: boolean) Compact = Value end function Error.GetNameFromCode(From: number): string for Name, Code in Error do if Code == From then return Name end end error(`Unknown error code: {From}`) end function Error.new(Code: number, Source: string, Message: string, File: string?): Class local Lines = string.split(Source, "\n") local Content = `{Color(`[E{string.format("%04i", Code)}] Error`, "red")}: {Message}` Content ..= `\n {Symbols.RightUp}{Symbols.Line}[{File or "input.blink"}:1:{#Lines}]` Content ..= `\n {Symbols.Down}` return setmetatable({ Labels = {}, Source = Lines, Message = Content, Code = Code, File = File or "input.blink", RawMessage = Message, }, Error) end function Error.Slice(self: Class, Span: Span): { Slice } local Slices = {} local Cursor = 1 for Line, Text in self.Source do local Start = Cursor local Length = #Text --> Advance cursor --> Cursor + #Length = \n => \n + 1 = Next line Cursor += (Length + 1) --> Span end is past cursor if Span.Start > Cursor then continue end local Spaces = (Span.Start - Start) local Underlines = math.clamp(Span.End - Span.Start, 1, Length) table.insert(Slices, { Line = Line, Text = Text, Spaces = Spaces, Underlines = Underlines, }) if Span.End <= Cursor then break end end return Slices end function Error.Label(self: Class, Span: Span, Text: string, TextColor: Color): Class local Slices = self:Slice(Span) --> Analyze hook table.insert(self.Labels, { Span = Span, Text = Text, }) --> Construct message for Index, Slice in Slices do self.Message ..= `\n{Style(string.format("%03i", Slice.Line), "dim")} {Symbols.Down} {Slice.Text}` if Index == #Slices then local Length = (Slice.Underlines // 2) local Indent = ` {Symbols.DownDash} {string.rep(" ", Slice.Spaces)}` local Underlines = Color(string.rep(Symbols.Line, Length), TextColor) local ExtraIndent = string.rep(" ", Length) self.Message ..= `\n{Indent}{Underlines}{Color(Symbols.Cross, TextColor)}{Underlines}` self.Message ..= `\n{Indent}{ExtraIndent}{Color(Symbols.Down, TextColor)}` self.Message ..= `\n{Indent}{ExtraIndent}{Color( `{Symbols.RightDown}{Symbols.Line}{Symbols.Line}`, TextColor )} {Color(Text, TextColor)}` end end return self end function Error.Primary(self: Class, Span: Span, Text: string): Class self.PrimarySpan = Span return self:Label(Span, Text, "red") end function Error.Secondary(self: Class, Span: Span, Text: string): Class return self:Label(Span, Text, "blue") end function Error.Emit(self: Class): never self.Message ..= `\n {Symbols.Down}` self.Message ..= `\n{string.rep(Symbols.Line, 4)}{Symbols.LeftDown}\n` if IS_ROBLOX or _G.RELEASE == nil then local OnEmit: ((Class) -> ())? = Error.OnEmit if OnEmit then OnEmit(self) end error(self.Message, 2) elseif stdio and process then if Compact then local LineStart = 0 local LineFinish = 0 if self.PrimarySpan then local Slices = self:Slice(self.PrimarySpan) LineStart = Slices[1].Line LineFinish = Slices[#Slices].Line end stdio.ewrite( string.format( "[E%04i] [L%03i:L%03i] [%s] Error: %s", self.Code, LineStart, LineFinish, self.File, self.RawMessage ) ) else stdio.ewrite(self.Message) end if _G.WATCH_THREAD then error(self.RawMessage) else process.exit(1) end end error("never") end return Error
1,872
1Axen/blink
1Axen-blink-3cb8d3d/src/Modules/Format.luau
--!strict local stdio = require("@lune/stdio") local function Style(text: any, style: stdio.Style): string return `{stdio.style(style)}{text}{stdio.style("reset")}` end local function Color(text: any, color: stdio.Color): string return `{stdio.color(color)}{text}{stdio.color("reset")}` end local KEYWORDS = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true, } local function ShouldntWrap(value: any): boolean if type(value) ~= "string" then return false end if #value == 0 then return false end if string.find(value, "[^%d%a_]") then return false end if tonumber(string.sub(value, 1, 1)) then return false end if KEYWORDS[value] then return false end return true end local Cache local INDENT = string.rep(" ", 3) local function Noop() end local function Format(Value: any, Filter: ((Value: any) -> boolean)?, Depth: number?): string local Depth = Depth or 0 local Filter = (Filter or Noop) :: (Value: any) -> boolean if Depth == 0 then Cache = {} end if Filter(Value) == false then return "" end local Type = type(Value) if Type == "string" then return Color(`"{Value}"`, "green") elseif Type == "number" then if Value == math.huge then return Color("math.huge", "cyan") end if Value == -math.huge then return Color("-math.huge", "cyan") end return Color(Value, "cyan") elseif Type == "boolean" then return Color(Value, "yellow") elseif Type == "table" then local Address = string.match(tostring(Value), "0x[%w]+") if Cache[Value] then return `{Color("{CACHED}", "red")} {Style(Address, "dim")}` end local Tabs = string.rep(INDENT, Depth) local Newline = ("\n" .. INDENT .. Tabs) local Text = Style(`\{ ({Address})`, "dim") .. Newline Cache[Value] = true local First = true for Key, Value in Value do if Filter(Key) == false then continue end local KeyText = ShouldntWrap(Key) and Key or `["{Format(Key, Filter, Depth + 1)}"]` if not First then Text ..= Style(",", "dim") .. Newline end First = false Text ..= `{KeyText} = {Format(Value, Filter, Depth + 1)}` end Text ..= "\n" .. Tabs .. Style("}", "dim") return Text end return `<{Type}>` end return Format
786
1Axen/blink
1Axen-blink-3cb8d3d/src/Modules/Path.luau
--!strict ---- Imports ---- ---- Settings ---- ---- Constants ---- local Utility = {} ---- Variables ---- ---- Private Functions ---- ---- Public Functions ---- function Utility.PathType(Path: string): "absolute" | "relative" -- on unix-based systems, '/' is root if string.sub(Path, 1, 1) == "/" then return "absolute" end -- on windows systems, it is %w:[\\/] if string.sub(Path, 2, 2) == ":" then return "absolute" end return "relative" end function Utility.Components(Path: string): (string?, string?, string?) local Filename: string? local Directory, FilenameExt, Extension = string.match(Path, "(.-)([^\\/]-%.?([^%.\\/]*))$") if FilenameExt then if FilenameExt == Extension then Extension = nil Filename = FilenameExt elseif Extension then Filename = string.sub(FilenameExt, 1, #FilenameExt - (#Extension + 1)) end end return Directory, Filename, Extension end function Utility.Filename(Path: string): string? local _, Filename = Utility.Components(Path) return Filename end function Utility.Directory(Path: string): string? local Directory = Utility.Components(Path) return Directory end function Utility.Extension(Path: string): string? local _, _, Extension = Utility.Components(Path) return Extension end function Utility.NameWithExtension(Path: string): string? local _, Name, Extension = Utility.Components(Path) if Name and Extension then return `{Name}.{Extension}` end return end ---- Initialization ---- ---- Connections ---- return Utility
355
1Axen/blink
1Axen-blink-3cb8d3d/src/Modules/Table.luau
return { Merge = function(...: { any }): { any } local Tables = { ... } local Allocate = 0 for _, Table in Tables do Allocate += #Table end local Index = 1 local Merged = table.create(Allocate) for _, Table in Tables do table.move(Table, 1, #Table, Index, Merged) Index += #Table end return Merged end, DeepClone = function(Table: { [any]: any }): { [any]: any } local Cache = {} local function Clone(Original) local Cached = Cache[Original] if Cached ~= nil then return Cached end local Copy = Original if type(Original) == "table" then Copy = {} Cache[Original] = Copy for Key, Value in Original do Copy[Clone(Key)] = Clone(Value) end end return Copy end return Clone(Table) end, }
230
1Axen/blink
1Axen-blink-3cb8d3d/src/Settings.luau
type NumberRange = { Min: number, Max: number } local NumberRange = { new = function(Min: number, Max: number?): NumberRange return { Min = Min, Max = Max or Min, } end, } export type Case = "Camel" | "Snake" | "Pascal" export type Cases = { Fire: string, FireAll: string, FireList: string, FireExcept: string, On: string, Invoke: string, StepReplication: string, Next: string, Iter: string, Read: string, Write: string, } export type Primitive = { Bounds: NumberRange?, Integer: boolean?, Component: boolean, AllowsRange: boolean, AllowsOptional: boolean, AllowedComponents: number, } local Indexes = { Pascal = 1, Camel = 2, Snake = 3, } local Cases = { On = { "On", "on", "on" }, Invoke = { "Invoke", "invoke", "invoke" }, Fire = { "Fire", "fire", "fire" }, FireAll = { "FireAll", "fireAll", "fire_all" }, FireList = { "FireList", "fireList", "fire_list" }, FireExcept = { "FireExcept", "fireExcept", "fire_except" }, StepReplication = { "StepReplication", "stepReplication", "step_replication" }, Next = { "Next", "next", "next" }, Iter = { "Iter", "iter", "iter" }, Read = { "Read", "read", "read" }, Write = { "Write", "write", "write" }, } local Primitives: { [string]: Primitive } = { u8 = { Bounds = NumberRange.new(0, 255), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, u16 = { Bounds = NumberRange.new(0, 65535), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, u32 = { Bounds = NumberRange.new(0, 4294967295), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, i8 = { Bounds = NumberRange.new(-128, 127), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, i16 = { Bounds = NumberRange.new(-32768, 32767), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, i32 = { Bounds = NumberRange.new(-2147483648, 2147483647), Integer = true, Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, f16 = { Bounds = NumberRange.new(-65504, 65504), Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, f32 = { Bounds = NumberRange.new(-16777216, 16777216), Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, f64 = { Bounds = NumberRange.new(-2 ^ 53, 2 ^ 53), Component = true, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, boolean = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, string = { Bounds = NumberRange.new(0, 4294967295), Integer = true, Component = false, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, vector = { Component = false, AllowsRange = true, AllowsOptional = true, AllowedComponents = 1, }, buffer = { Bounds = NumberRange.new(0, 4294967295), Integer = true, Component = false, AllowsRange = true, AllowsOptional = true, AllowedComponents = 0, }, Color3 = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, CFrame = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 2, }, Instance = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, BrickColor = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, unknown = { Component = false, AllowsRange = false, AllowsOptional = false, AllowedComponents = 0, }, DateTime = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, DateTimeMillis = { Component = false, AllowsRange = false, AllowsOptional = true, AllowedComponents = 0, }, } return { Keywords = { map = true, set = true, type = true, enum = true, struct = true, event = true, ["function"] = true, scope = true, option = true, export = true, }, Primtives = Primitives, GetCasing = function(Case: Case): Cases local Index = Indexes[Case] if not Index then error(`Unknown casing "{Case}", expectd one of "Pascal" or "Camel" or "Snake"`) end local Casing: any = {} for Key, Options in Cases do Casing[Key] = Options[Index] end return Casing end, }
1,444
1Axen/blink
1Axen-blink-3cb8d3d/src/Templates/Base.luau
return [[local Invocations = 0 local SendSize = 64 local SendOffset = 0 local SendCursor = 0 local SendBuffer = buffer.create(64) local SendInstances = {} local RecieveCursor = 0 local RecieveBuffer = buffer.create(64) local RecieveInstances = {} local RecieveInstanceCursor = 0 local Null = newproxy() type Entry = { value: any, next: Entry? } type Queue = { head: Entry?, tail: Entry? } type BufferSave = { Size: number, Cursor: number, Buffer: buffer, Instances: {Instance} } local function Read(Bytes: number) local Offset = RecieveCursor RecieveCursor += Bytes return Offset end local function Save(): BufferSave return { Size = SendSize, Cursor = SendCursor, Buffer = SendBuffer, Instances = SendInstances } end local function Load(Save: BufferSave?) if Save then SendSize = Save.Size SendCursor = Save.Cursor SendOffset = Save.Cursor SendBuffer = Save.Buffer SendInstances = Save.Instances return end SendSize = 64 SendCursor = 0 SendOffset = 0 SendBuffer = buffer.create(64) SendInstances = {} end local function Invoke() if Invocations == 255 then Invocations = 0 end local Invocation = Invocations Invocations += 1 return Invocation end local function Allocate(Bytes: number) local InUse = (SendCursor + Bytes) if InUse > SendSize then --> Avoid resizing the buffer for every write while InUse > SendSize do SendSize *= 1.5 end local Buffer = buffer.create(SendSize) buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor) SendBuffer = Buffer end SendOffset = SendCursor SendCursor += Bytes return SendOffset end local function CreateQueue(): Queue return { head = nil, tail = nil } end local function Pop(queue: Queue): any local head = queue.head if head == nil then return end queue.head = head.next return head.value end local function Push(queue: Queue, value: any) local entry: Entry = { value = value, next = nil } if queue.tail ~= nil then queue.tail.next = entry end queue.tail = entry if queue.head == nil then queue.head = entry end end local Calls = table.create(256) local Events: any = { Reliable = table.create(256), Unreliable = table.create(256) } local Queue: any = { Reliable = table.create(256), Unreliable = table.create(256) } ]]
658
1Axen/blink
1Axen-blink-3cb8d3d/src/Templates/Client.luau
return [[local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") -- SPLIT -- if not RunService:IsClient() then error("Client network module can only be required from the client.") end local Reliable: RemoteEvent = ReplicatedStorage:WaitForChild(BASE_EVENT_NAME .. "_RELIABLE_REMOTE") :: RemoteEvent local Unreliable: UnreliableRemoteEvent = ReplicatedStorage:WaitForChild(BASE_EVENT_NAME .. "_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent local function StepReplication() if SendCursor <= 0 then return end local Buffer = buffer.create(SendCursor) buffer.copy(Buffer, 0, SendBuffer, 0, SendCursor) Reliable:FireServer(Buffer, SendInstances) SendSize = 64 SendCursor = 0 SendOffset = 0 SendBuffer = buffer.create(64) table.clear(SendInstances) end ]]
216
1Axen/blink
1Axen-blink-3cb8d3d/src/Templates/Server.luau
return [[local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") -- SPLIT -- if not RunService:IsServer() then error("Server network module can only be required from the server.") end local Reliable: RemoteEvent = ReplicatedStorage:FindFirstChild(BASE_EVENT_NAME .. "_RELIABLE_REMOTE") :: RemoteEvent if not Reliable then local RemoteEvent = Instance.new("RemoteEvent") RemoteEvent.Name = BASE_EVENT_NAME .. "_RELIABLE_REMOTE" RemoteEvent.Parent = ReplicatedStorage Reliable = RemoteEvent end local Unreliable: UnreliableRemoteEvent = ReplicatedStorage:FindFirstChild(BASE_EVENT_NAME .. "_UNRELIABLE_REMOTE") :: UnreliableRemoteEvent if not Unreliable then local UnreliableRemoteEvent = Instance.new("UnreliableRemoteEvent") UnreliableRemoteEvent.Name = BASE_EVENT_NAME .. "_UNRELIABLE_REMOTE" UnreliableRemoteEvent.Parent = ReplicatedStorage Unreliable = UnreliableRemoteEvent end local PlayersMap: {[Player]: BufferSave} = {} Players.PlayerRemoving:Connect(function(Player) PlayersMap[Player] = nil end) local function StepReplication() for Player, Send in PlayersMap do if Send.Cursor <= 0 then continue end local Buffer = buffer.create(Send.Cursor) buffer.copy(Buffer, 0, Send.Buffer, 0, Send.Cursor) Reliable:FireClient(Player, Buffer, Send.Instances) Send.Size = 64 Send.Cursor = 0 Send.Buffer = buffer.create(64) table.clear(Send.Instances) end end ]]
380
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/BuildRelease.luau
--!native --!optimize 2 --!strict local Destroy = require("./Utilities/Destroy") local FileInstance = require("./Classes/FileInstance") local PathUtilities = require("./Utilities/PathUtilities") local warn = require("./Utilities/Warn") local fs = require("@lune/fs") local process = require("@lune/process") local serde = require("@lune/serde") local stdio = require("@lune/stdio") local PROJECT_NAME = "built-release.project.json" local SOURCEMAP_NAME = "built-sourcemap.json" local EXTRA_STEPS: { { Enabled: boolean, Name: string, Function: (builtProject: FileInstance.FileInstance) -> boolean, } } = { { Enabled = true; Name = "Fix Promise import"; Function = function(builtProject) local promise = builtProject:FindFirstFile("Promise.luau") if not promise then return false end local promiseFileSource = promise:Read() if not promiseFileSource then return false end promise:Write( ( string.gsub( promiseFileSource, "local Packages = script.Parent.Parent", "local Packages = script.Parent.Packages" ) ) ) return true end; }; } type Cleanup = () -> () local function CreateBuildProject(): Cleanup if fs.isDir("built-project") then Destroy("built-project") end fs.copy("src", "built-project", true) local builtProject = FileInstance.Mark("built-project") if not fs.isDir("Packages") then Destroy("Packages") end local installResult = process.spawn("wally", {"install"}) if not installResult.ok then warn(`wally install failed: {installResult.stderr} ({installResult.code})`) return function() builtProject:Destroy() end end local packages = FileInstance.Mark("Packages") local tests = builtProject:FindFirstDirectory("__tests__") if tests then tests:Destroy() end local configuration = builtProject:FindFirstFile("jest.config.luau") if configuration then configuration:Destroy() end local descendants = builtProject:GetDescendants() for _, child in builtProject:GetChildren() do if child.IsDirectory and #child:GetChildren() == 0 then child:Destroy() end end for _, extraStep in EXTRA_STEPS do if not extraStep.Enabled then continue end extraStep.Function(builtProject) end if not fs.isFile(PROJECT_NAME) then local json = serde.encode("json", { globIgnorePaths = { "**/*.spec.luau"; "**/*.spec.lua"; "**/*.story.luau"; "**/*.story.lua"; "**/__tests__"; "**/*.test.luau"; "**/*.test.lua"; }; name = "Janitor"; tree = { ["$path"] = "built-project"; Packages = {["$path"] = "Packages"}; }; }, false) fs.writeFile(PROJECT_NAME, json) end local sourcemapResult = process.spawn("rojo", {"sourcemap", "--output", SOURCEMAP_NAME, PROJECT_NAME}) if not sourcemapResult.ok then warn(`rojo sourcemap failed: {sourcemapResult.stderr} ({sourcemapResult.code})`) return function() Destroy(PROJECT_NAME) builtProject:Destroy() end end local packageTypesResult = process.spawn("wally-package-types", {"--sourcemap", SOURCEMAP_NAME, "Packages/"}) if not packageTypesResult.ok then warn(`wally-package-types failed: {packageTypesResult.stderr} ({packageTypesResult.code})`) return function() Destroy(PROJECT_NAME) Destroy(SOURCEMAP_NAME) builtProject:Destroy() end end local packageNames: {[string]: string} = {} for _, child in packages:GetChildren() do if child.IsDirectory then continue end local packageName = PathUtilities.FileNameNoExtension(child.Name) if not packageName or packageNames[packageName] then continue end packageNames[packageName] = `local {packageName} = require%(script.(.*).{packageName}%)` print("Adding", packageName) end for _, descendant in descendants do if descendant.IsDirectory or descendant.Name == "README.luau" then continue end local extension = PathUtilities.ExtensionName(descendant.Name) if not extension then warn("No extension found for", descendant:GetFullName()) continue end if extension ~= ".lua" and extension ~= ".luau" then continue end local fileSource = descendant:Read() if not fileSource then warn("Failed to read", descendant:GetFullName()) continue end local splitByNewline = string.split(fileSource, "\n") local wasModified = false for index, line in splitByNewline do for packageName, pattern in packageNames do local parentPath = string.match(line, pattern) if not parentPath then continue end local requirePath = {"script"} local length = 1 local wasFound = false local object = descendant while true do local parent = object.Parent length += 1 requirePath[length] = "Parent" if parent == builtProject then requirePath[length + 1] = "Packages" requirePath[length + 2] = packageName wasFound = true break end if not parent then warn("Failed to find parent for", object:GetFullName()) break end object = parent end if wasFound then local newLine = `local {packageName} = require({table.concat(requirePath, ".")})` splitByNewline[index] = newLine wasModified = true end end end if wasModified then descendant:Write(table.concat(splitByNewline, "\n")) end end return function() Destroy(PROJECT_NAME) Destroy(SOURCEMAP_NAME) builtProject:Destroy() end end local function Install(lastCleanup: Cleanup?): Cleanup local rbxmResult = process.spawn("rojo", {"build", "--output", "Janitor.rbxm", PROJECT_NAME}) if not rbxmResult.ok then warn(`rojo build rbxm failed: {rbxmResult.stderr} ({rbxmResult.code})`) return function() if lastCleanup then lastCleanup() end end end local rbxmxResult = process.spawn("rojo", {"build", "--output", "Janitor.rbxmx", PROJECT_NAME}) if not rbxmxResult.ok then warn(`rojo build rbxmx failed: {rbxmxResult.stderr} ({rbxmxResult.code})`) return function() if lastCleanup then lastCleanup() end end end return function() if lastCleanup then lastCleanup() end end end local cleanup = Install(CreateBuildProject()) stdio.prompt("confirm", "Press enter to continue and cleanup", true) cleanup() local sourcemapResult = process.spawn("rojo", {"sourcemap", "--output", "sourcemap.json", "place.project.json"}) if not sourcemapResult.ok then warn(`rojo sourcemap failed: {sourcemapResult.stderr} ({sourcemapResult.code})`) process.exit(1) end local packageTypesResult = process.spawn("wally-package-types", {"--sourcemap", "sourcemap.json", "Packages/"}) if not packageTypesResult.ok then warn(`wally-package-types failed: {packageTypesResult.stderr} ({packageTypesResult.code})`) process.exit(1) end local devPackageTypesResult = process.spawn("wally-package-types", {"--sourcemap", "sourcemap.json", "DevPackages/"}) if not devPackageTypesResult.ok then warn(`wally-package-types failed: {devPackageTypesResult.stderr} ({devPackageTypesResult.code})`) process.exit(1) end
1,847
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Classes/FileInstance.luau
--!native --!optimize 2 --!strict local Destroy = require("../Utilities/Destroy") local PathUtilities = require("../Utilities/PathUtilities") local fs = require("@lune/fs") local process = require("@lune/process") export type FileInstance = { FilePath: string, IsDirectory: boolean, Name: string, Parent: FileInstance?, GetChildren: (self: FileInstance) -> {FileInstance}, GetDescendants: (self: FileInstance) -> {FileInstance}, GetFullName: (self: FileInstance) -> string, FindFirstFile: (self: FileInstance, name: string, recursive: boolean?) -> FileInstance?, FindFirstDirectory: (self: FileInstance, name: string, recursive: boolean?) -> FileInstance?, Read: (self: FileInstance) -> string?, Write: (self: FileInstance, source: string) -> (), Destroy: (self: FileInstance) -> (), } type Private = { FilePath: string, IsDirectory: boolean, Name: string, Parent: FileInstance?, Children: {FileInstance}?, Descendants: {FileInstance}?, GetChildren: (self: Private) -> {FileInstance}, GetDescendants: (self: Private) -> {FileInstance}, GetFullName: (self: Private) -> string, FindFirstFile: (self: Private, name: string, recursive: boolean?) -> FileInstance?, FindFirstDirectory: (self: Private, name: string, recursive: boolean?) -> FileInstance?, Read: (self: Private) -> string?, Write: (self: Private, source: string) -> (), Destroy: (self: Private) -> (), } type Static = { ClassName: "FileInstance", Mark: (filePath: string, fileName: string?, parent: FileInstance?) -> FileInstance, Is: (value: any) -> boolean, } type PrivateStatic = Static & { __eq: (self: FileInstance, other: FileInstance) -> boolean, __tostring: (self: FileInstance) -> string, } local FileInstance = {} :: FileInstance & Static local Private = FileInstance :: Private & PrivateStatic FileInstance.ClassName = "FileInstance"; (FileInstance :: any).__index = FileInstance function FileInstance.Mark(filePath, fileName, parent): FileInstance local newFilePath = if fileName then `{filePath}/{fileName}` else filePath local self: Private = setmetatable({}, FileInstance) :: never self.Children = nil self.Descendants = nil self.Name = PathUtilities.FileName(newFilePath) self.FilePath = newFilePath self.IsDirectory = fs.isDir(newFilePath) self.Parent = parent if not self.IsDirectory then -- if it's an init.luau file, the parent is actually the next parent up if self.Name == "init.luau" and parent then self.Parent = parent.Parent end end return self end function FileInstance.Is(value) return type(value) == "table" and getmetatable(value) == FileInstance end function FileInstance:GetFullName() local filePath = self.FilePath if string.sub(filePath, 1, 2) == "./" then filePath = string.sub(filePath, 3) end return process.cwd .. filePath end function Private:GetChildren() -- local cached = self.Children -- if cached then -- return cached -- end if self.IsDirectory then local inDirectory = fs.readDir(self.FilePath) local children = table.create(#inDirectory) for index, child in inDirectory do children[index] = FileInstance.Mark(self.FilePath, child, self) end self.Children = children return children end local children = {} self.Children = children return children end function Private:GetDescendants() -- local cached = self.Descendants -- if cached then -- return cached -- end local descendants = self:GetChildren() local totalDescendants = #descendants local length = 0 if totalDescendants > 0 then repeat length += 1 local grandChildren = descendants[length]:GetChildren() for index, grandChild in grandChildren do descendants[totalDescendants + index] = grandChild end totalDescendants += #grandChildren until length == totalDescendants end self.Descendants = descendants return descendants end function FileInstance:FindFirstFile(name, recursive) name = PathUtilities.Join(self.Name, name) if recursive then for _, descendant in self:GetDescendants() do if PathUtilities.OsPath(descendant.Name) == name then return descendant end end return nil end for _, child in self:GetChildren() do if PathUtilities.OsPath(child.Name) == name then return child end end return nil end function FileInstance:FindFirstDirectory(name, recursive) name = PathUtilities.Join(self.Name, name) if recursive then for _, descendant in self:GetDescendants() do if descendant.IsDirectory and PathUtilities.OsPath(descendant.Name) == name then return descendant end end return nil end for _, child in self:GetChildren() do if child.IsDirectory and PathUtilities.OsPath(child.Name) == name then return child end end return nil end function FileInstance:Read() return if self.IsDirectory then nil else fs.readFile(self.FilePath) end function FileInstance:Write(source) if not self.IsDirectory then fs.writeFile(self.FilePath, source) end end function FileInstance:Destroy() Destroy(self.FilePath) table.clear(self) setmetatable(self, nil) end function Private:__eq(other) return self.FilePath == other.FilePath end Private.__tostring = FileInstance.GetFullName return table.freeze(FileInstance :: Static)
1,288
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/EnableLoadModule.luau
--!native --!optimize 2 local fs = require("@lune/fs") local process = require("@lune/process") local serde = require("@lune/serde") if process.env.windir ~= nil then local appDataPath = process.env.LOCALAPPDATA local robloxVersionsPath = `{appDataPath}\\Roblox\\Versions` if not fs.isDir(robloxVersionsPath) then error(`Roblox versions folder not found. Please install Roblox. Checked here: {robloxVersionsPath}`) end local mostRecentStudioVersionPath for _, versionDirName in fs.readDir(robloxVersionsPath) do local versionDirPath = `{robloxVersionsPath}\\{versionDirName}` if not fs.isDir(versionDirPath) or not fs.isFile(`{versionDirPath}\\RobloxStudioBeta.exe`) then continue end mostRecentStudioVersionPath = versionDirPath break end if mostRecentStudioVersionPath == nil then error(`Roblox Studio not found. Please install Roblox. Checked here: {robloxVersionsPath}`) end local clientSettingsDir = `{mostRecentStudioVersionPath}\\ClientSettings` if not fs.isDir(clientSettingsDir) then fs.writeDir(clientSettingsDir) end local clientAppSettingsPath = `{clientSettingsDir}\\ClientAppSettings.json` local clientAppSettings if fs.isFile(clientAppSettingsPath) then clientAppSettings = serde.decode("json", fs.readFile(clientAppSettingsPath)) local metadata = fs.metadata(clientAppSettingsPath) if metadata.permissions and metadata.permissions.readOnly then local result = process.spawn("attrib", {"-r", clientAppSettingsPath}) assert(result.ok, `Failed to remove read-only attribute:\n{result.stderr}`) end else clientAppSettings = {} end clientAppSettings.FFlagEnableLoadModule = true fs.writeFile(clientAppSettingsPath, serde.encode("json", clientAppSettings)) local result = process.spawn("attrib", {"+r", clientAppSettingsPath}) assert(result.ok, `Failed to add read-only attribute:\n{result.stderr}`) print(`Wrote FFlagEnableLoadModule to ClientAppSettings.json at {clientAppSettingsPath}`) process.exit(0) end -- TODO: Get the old iMac and figure out Mac warn(`No support for {process.os} yet. ):`, 2) process.exit(1)
520
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Packages/SemanticVersion.luau
--!native --!optimize 2 --!strict local function ParsePrereleaseAndBuildWithSign(value: string): (string, string) local prereleaseWithSign, buildWithSign = string.match(value, "^(-[^+]+)(+.+)$") if prereleaseWithSign == nil or buildWithSign == nil then prereleaseWithSign = string.match(value, "^(-.+)$") buildWithSign = string.match(value, "^(+.+)$") end if prereleaseWithSign == nil and buildWithSign == nil then error(string.format("The parameter %q must begin with + or - to denote a prerelease or a build", value)) end return prereleaseWithSign :: string, buildWithSign :: string end local function ParsePrerelease(prereleaseWithSign: string?): string? if prereleaseWithSign == nil then return nil end local prerelease = string.match(prereleaseWithSign, "^-(%w[%.%w-]*)$" :: string) if prerelease == nil then error( string.format( "The prerelease %q is not a slash followed by alphanumerics, dots and slashes", prereleaseWithSign ) ) end return prerelease end local function ParseBuild(buildWithSign: string?): string? if buildWithSign == nil then return nil end local build = string.match(buildWithSign, "^%+(%w[%.%w-]*)$" :: string) if build == nil then error(string.format("The build %q is not a + sign followed by alphanumerics, dots and slashes", buildWithSign)) end return build end type Option = { Build: string, Prerelease: string, } | { Build: nil, Prerelease: nil, } local function ParsePrereleaseAndBuild(value: string?): Option if not (value ~= "" and value) then return {} end local prereleaseWithSign, buildWithSign = ParsePrereleaseAndBuildWithSign(value) local prerelease = ParsePrerelease(prereleaseWithSign) local build = ParseBuild(buildWithSign) return { Build = build :: string; Prerelease = prerelease :: string; } end local function ParseVersion(value: string) local stringMajor, stringMinor, stringPatch, stringPrereleaseAndBuild = string.match(value, "^(%d+)%.?(%d*)%.?(%d*)(.-)$") if stringMajor == nil then error(string.format("Could not extract version number(s) from %q", value)) end local major = tonumber(stringMajor) :: number local minor = tonumber(stringMinor) :: number local patch = tonumber(stringPatch) :: number local option = ParsePrereleaseAndBuild(stringPrereleaseAndBuild :: string) return major, minor, patch, option.Prerelease, option.Build end local function _Compare(a: any, b: any) return if a == b then 0 elseif a < b then -1 else 1 end local Compare = (_Compare :: never) :: ((a: number, b: number) -> number) & ((a: string, b: string) -> number) local function CompareIds(selfId: string, otherId: string) if selfId == otherId then return 0 end if selfId == nil then return -1 end if otherId == nil then return 1 end local selfNumber = tonumber(selfId) local otherNumber = tonumber(otherId) if selfNumber and otherNumber then return Compare(selfNumber, otherNumber) end if selfNumber then return -1 end if otherNumber then return 1 end return Compare(selfId, otherId) end local function SmallerIdList(selfIds: {string}, otherIds: {string}) for index, value in selfIds do local comparison = CompareIds(value, otherIds[index]) if comparison ~= 0 then return comparison == -1 end end return #selfIds < #otherIds end local function SmallerPrerelease(mine: string?, other: string?) if mine == other or not mine then return false end if not other then return true end return SmallerIdList(string.split(mine, "."), string.split(other, ".")) end export type SemanticVersion = typeof(setmetatable( {} :: { Major: number, Minor: number, Patch: number, Prerelease: string?, Build: string?, NextMajor: (self: SemanticVersion) -> SemanticVersion, NextMinor: (self: SemanticVersion) -> SemanticVersion, NextPatch: (self: SemanticVersion) -> SemanticVersion, }, {} :: { __eq: (self: SemanticVersion, other: SemanticVersion) -> boolean, __lt: (self: SemanticVersion, other: SemanticVersion) -> boolean, __pow: (self: SemanticVersion, other: SemanticVersion) -> boolean, __tostring: (self: SemanticVersion) -> string, } )) type BaseStatics = { ClassName: "SemanticVersion", new: ( major: number | string, minor: number?, patch: number?, prerelease: string?, build: string? ) -> SemanticVersion, } type SemanticVersionStatics = BaseStatics & { __eq: (self: SemanticVersion, other: SemanticVersion) -> boolean, __lt: (self: SemanticVersion, other: SemanticVersion) -> boolean, __pow: (self: SemanticVersion, other: SemanticVersion) -> boolean, __tostring: (self: SemanticVersion) -> string, } local SemanticVersion = {} :: SemanticVersion & SemanticVersionStatics SemanticVersion.ClassName = "SemanticVersion"; (SemanticVersion :: any).__index = SemanticVersion function SemanticVersion.new( major: number | string, minor: number?, patch: number?, prerelease: string?, build: string? ): SemanticVersion local self = setmetatable({}, SemanticVersion) if type(major) == "string" then major, minor, patch, prerelease, build = ParseVersion(major) end local trueMinor = minor or 0 local truePatch = patch or 0 self.Major = major self.Minor = trueMinor self.Patch = truePatch self.Prerelease = prerelease self.Build = build table.freeze(self) return (self :: any) :: SemanticVersion end function SemanticVersion:NextMajor(): SemanticVersion return SemanticVersion.new(self.Major + 1, 0, 0) end function SemanticVersion:NextMinor(): SemanticVersion return SemanticVersion.new(self.Major, self.Minor + 1, 0) end function SemanticVersion:NextPatch(): SemanticVersion return SemanticVersion.new(self.Major, self.Minor, self.Patch + 1) end function SemanticVersion:__eq(other) return self.Major == other.Major and self.Minor == other.Minor and self.Patch == other.Patch and self.Prerelease == other.Prerelease end function SemanticVersion:__lt(other) if self.Major ~= other.Major then return self.Major < other.Major end if self.Minor ~= other.Minor then return self.Minor < other.Minor end if self.Patch ~= other.Patch then return self.Patch < other.Patch end return SmallerPrerelease(self.Prerelease, other.Prerelease) end function SemanticVersion:__pow(other) return if self.Major == 0 then self == other else self.Major == other.Major and self.Minor <= other.Minor end function SemanticVersion:__tostring() local stringBuilder = {string.format("%*.%*.%*", self.Major, self.Minor, self.Patch)} local build = self.Build local prerelease = self.Prerelease if prerelease ~= "" and prerelease then table.insert(stringBuilder, `-{prerelease}`) end if build ~= "" and build then table.insert(stringBuilder, `+{build}`) end return table.concat(stringBuilder) end return table.freeze(SemanticVersion :: BaseStatics)
1,829
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/UpdateVersion.luau
--!native --!optimize 2 local SemanticVersion = require("./Packages/SemanticVersion") local fs = require("@lune/fs") local serde = require("@lune/serde") local stdio = require("@lune/stdio") local wally = serde.decode("toml", fs.readFile("wally.toml")) local lastVersion = wally.package.version local lastVersionSemantic = SemanticVersion.new(lastVersion) local nextVersion = stdio.prompt("text", "What is the next version?", tostring(lastVersionSemantic:NextMinor())) local nextVersionSemantic = SemanticVersion.new(nextVersion) local function SanitizePattern(value: string) return (string.gsub(value, "([%.%-%*%+%?%%])", "%%%1")) end local function ReplaceVersion(file: string, from: string, to: string) fs.writeFile(file, (string.gsub(fs.readFile(file), SanitizePattern(from), to))) end do ReplaceVersion("docs/installation.md", `@{lastVersionSemantic}`, `@{nextVersionSemantic}`) ReplaceVersion("docs/intro.md", `@{lastVersionSemantic}`, `@{nextVersionSemantic}`) ReplaceVersion("README.md", `@{lastVersionSemantic}`, `@{nextVersionSemantic}`) end do ReplaceVersion("docs/installation.md", `@%^{lastVersionSemantic}`, `@^{nextVersionSemantic}`) ReplaceVersion("docs/intro.md", `@%^{lastVersionSemantic}`, `@^{nextVersionSemantic}`) ReplaceVersion("README.md", `@%^{lastVersionSemantic}`, `@^{nextVersionSemantic}`) end ReplaceVersion("wally.toml", `version = "{lastVersionSemantic}"`, `version = "{nextVersionSemantic}"`)
366
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Utilities/Destroy.luau
--!native --!optimize 2 --!strict local fs = require("@lune/fs") local process = require("@lune/process") local HAS_RIM_RAF = (function() if process.os ~= "windows" then return false end return pcall(function() fs.writeDir("swage") process.spawn("rimraf", {"swage"}) end) end)() local Destroy: (path: string) -> () if HAS_RIM_RAF then function Destroy(path) process.spawn("rimraf", {path}) end else function Destroy(path) process.spawn("rm", {"-rf", path}) end end return Destroy
145
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Utilities/FileSystemUtilities.luau
--!native --!optimize 2 --!strict local fs = require("@lune/fs") local FileSystemUtilities = {} function FileSystemUtilities.JustFileName(path: string) return string.match(string.match(path, "^(.+)%..+$") or path, "([^\\/]+)$") or path end function FileSystemUtilities.JustFileNameWithExtension(path: string) return string.match(path, "([^\\/]+)$") or path end function FileSystemUtilities.WithoutExtension(path: string): string return string.match(path, "^(.+)%..+$") or path end function FileSystemUtilities.GetExtension(path: string) return string.match(path, "%.([^%.]+)$") end type CreatorFunction = (path: string, contents: string?) -> () type SafeCreate = ((name: string, createType: "File", contents: string) -> ()) & ((name: string, createType: "Directory") -> ()) local function SafeCreate(name: string, createType: "File" | "Directory", contents: string?) local CheckerFunction: typeof(fs.isDir) = if createType == "File" then fs.isFile else fs.isDir local CreatorFunction = (if createType == "File" then fs.writeFile else fs.writeDir) :: CreatorFunction if not CheckerFunction(name) then CreatorFunction(name, contents) else local index = 1 while CheckerFunction(`{FileSystemUtilities.WithoutExtension(name)} ({index})`) do index += 1 end local extension = FileSystemUtilities.GetExtension(name) local newFilePath = if extension then `{FileSystemUtilities.WithoutExtension(name)} ({index}).{extension}` else `{FileSystemUtilities.WithoutExtension(name)} ({index})` CreatorFunction(newFilePath, contents) end end FileSystemUtilities.SafeCreate = SafeCreate :: SafeCreate function FileSystemUtilities.GetOrCreateDirectory(name: string) if not fs.isDir(name) then FileSystemUtilities.SafeCreate(name, "Directory") end end return table.freeze(FileSystemUtilities)
435
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Utilities/PathUtilities.luau
--!native --!optimize 2 local process = require("@lune/process") local PathUtilities = {} local SEPARATOR = if process.os == "windows" then "\\" else "/" PathUtilities.Separator = SEPARATOR --- Fixes the path so that it's properly formatted to the local operating system --- @param path The path to format --- @return A fixed path matching the OS format function PathUtilities.OsPath(path: string) local newPath = "" if process.os == "windows" then local index = 1 while index <= #path do local character = string.sub(path, index, index) if character == "/" then character = "\\" end newPath ..= character index += 1 end newPath = string.gsub(newPath, "\\+", "\\") else local index = 1 while index <= #path do local character = string.sub(path, index, index) if character == "\\" then character = "/" end newPath ..= character index += 1 end newPath = string.gsub(newPath, "/+", "/") end return newPath end --- Join multiple path parts into a combined path --- @return A joined path function PathUtilities.Join(...: string) return PathUtilities.OsPath(table.concat({...}, SEPARATOR)) end --- Gets the extension of the given path (if applicable) - otherwise returns nil --- @param path The path to get the extension of --- @return The path extension or nil function PathUtilities.ExtensionName(path: string): string? return string.match(path, ".(%.[A-z0-9_-]+)$") end --- Gets the full directory path of the given path --- @param value The path --- @return The full directory path without the end item function PathUtilities.DirectoryName(value: string): string local parts = string.split(PathUtilities.OsPath(value), SEPARATOR) table.remove(parts) return table.concat(parts, SEPARATOR) end function PathUtilities.FileName(value: string) return string.match(value, `[^{PathUtilities.Separator}]+$`) end function PathUtilities.FileNameNoExtension(value: string) local extension = PathUtilities.ExtensionName(value) local fileName = string.match(value, `[^{PathUtilities.Separator}]+$`) if extension then return if fileName then string.gsub(fileName, `{extension}$`, "") else nil end return fileName end return table.freeze(PathUtilities)
531
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/.lune/Utilities/Warn.luau
--!native --!optimize 2 --!strict local Chalk = require("../Packages/Chalk") local ORANGE = Chalk.Rgb(255, 142, 60) local function Concat(...: unknown) local length = select("#", ...) if length == 0 then return "" end if length == 1 then return tostring(...) end if length == 2 then local a, b = ... return tostring(a) .. " " .. tostring(b) end if length == 3 then local a, b, c = ... return tostring(a) .. " " .. tostring(b) .. " " .. tostring(c) end if length == 4 then local a, b, c, d = ... return tostring(a) .. " " .. tostring(b) .. " " .. tostring(c) .. " " .. tostring(d) end if length == 5 then local a, b, c, d, e = ... return tostring(a) .. " " .. tostring(b) .. " " .. tostring(c) .. " " .. tostring(d) .. " " .. tostring(e) end if length == 6 then local a, b, c, d, e, f = ... return tostring(a) .. " " .. tostring(b) .. " " .. tostring(c) .. " " .. tostring(d) .. " " .. tostring(e) .. " " .. tostring(f) end local array = table.create(length) for index = 1, length do array[index] = tostring(select(index, ...)) end return table.concat(array, " ") end local function Warn(...) warn(ORANGE(Concat(...))) end return Warn
387
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/FairComparison.bench/Duster.luau
--!native -- duster -- fast and lightweight maid impl ( thats also better than janitor ) type Types = "table" | "function" | "thread" | "Instance" | "RBXScriptConnection" type TableCleanupMethod = <V>(self: (V & {})) -> () export type Cleanable = | { Disconnect: TableCleanupMethod } | { disconnect: TableCleanupMethod } | { Cleanup: TableCleanupMethod } | { destroy: TableCleanupMethod } | { Destroy: TableCleanupMethod } | { cleanup: TableCleanupMethod } | { Cleanup: TableCleanupMethod } | { clear: TableCleanupMethod } | { Clear: TableCleanupMethod } | RBXScriptConnection | Instance | () -> () | thread local DISCONNECT = (function() local conn = script.Changed:Connect(function() end) local disconnect = conn.Disconnect disconnect(conn) return disconnect end)() local TYPEOF = typeof :: <V>(value: V) -> Types local DESTROY = game.Destroy local REMOVE = table.remove local INSERT = table.insert local CANCEL = task.cancel local CLEAR = table.clear local FIND = table.find local duster = {} -- have to keep the generic, as otherwise typechecker WILL kick and scream function duster.clearval<V>(duster: { Cleanable }, value: V & Cleanable) local index = FIND(duster, (value :: any)) if index then local type = TYPEOF(value) if type == "function" then (value :: any)() elseif type == "thread" then CANCEL((value :: any)) elseif type == "table" then local disconnect1 = (value :: any).Disconnect if disconnect1 then disconnect1(value) return end local disconnect = (value :: any).disconnect if disconnect then disconnect(value) return end local destroy = (value :: any).destroy if destroy then destroy(value) return end local clear = (value :: any).clear if clear then clear(value) return end local clean = (value :: any).cleanup if clean then clean(value) return end local destroy2 = (value :: any).Destroy if destroy2 then destroy2(value) return end local clear2 = (value :: any).Clear if clear2 then clear2(value) return end local clean2 = (value :: any).Cleanup if clean2 then clean2(value) end elseif type == "Instance" then DESTROY((value :: any)) elseif type == "RBXScriptConnection" then DISCONNECT((value :: any)) end REMOVE(duster, index) end end function duster.cleari(duster: { Cleanable }, index: number) local value = duster[index] if value then local type = TYPEOF(value) if type == "function" then (value :: any)() elseif type == "thread" then CANCEL((value :: any)) elseif type == "table" then local disconnect1 = (value :: any).Disconnect if disconnect1 then disconnect1(value) return end local disconnect = (value :: any).disconnect if disconnect then disconnect(value) return end local destroy = (value :: any).destroy if destroy then destroy(value) return end local clear = (value :: any).clear if clear then clear(value) return end local clean = (value :: any).cleanup if clean then clean(value) return end local destroy2 = (value :: any).Destroy if destroy2 then destroy2(value) return end local clear2 = (value :: any).Clear if clear2 then clear2(value) return end local clean2 = (value :: any).Cleanup if clean2 then clean2(value) end elseif type == "Instance" then DESTROY((value :: any)) elseif type == "RBXScriptConnection" then DISCONNECT((value :: any)) end REMOVE(duster, index) end end function duster.clear(duster: { Cleanable }) for _, value in duster do local type = TYPEOF(value) if type == "function" then (value :: any)() elseif type == "thread" then CANCEL((value :: any)) elseif type == "table" then local disconnect1 = (value :: any).Disconnect if disconnect1 then disconnect1(value) continue end local disconnect = (value :: any).disconnect if disconnect then disconnect(value) continue end local destroy = (value :: any).destroy if destroy then destroy(value) continue end local clear = (value :: any).clear if clear then clear(value) continue end local clean = (value :: any).cleanup if clean then clean(value) continue end local destroy2 = (value :: any).Destroy if destroy2 then destroy2(value) continue end local clear2 = (value :: any).Clear if clear2 then clear2(value) continue end local clean2 = (value :: any).Cleanup if clean2 then clean2(value) end elseif type == "Instance" then DESTROY((value :: any)) elseif type == "RBXScriptConnection" then DISCONNECT((value :: any)) end end CLEAR(duster) end function duster.insert<V>( duster: { Cleanable }, value: V & Cleanable, cleaner: (((self: V) -> ()) | () -> ())? ): V if cleaner then INSERT(duster, function() (cleaner :: any)(value) end) else INSERT(duster, value :: any) end return value end return table.freeze(duster)
1,432
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/FairComparison.bench/Janitor17/init.luau
--!optimize 2 --!strict local Promise = require(script.Promise) type Promise<T...> = Promise.TypedPromise<T...> local LinkToInstanceIndex = setmetatable({}, { __tostring = function() return "LinkToInstanceIndex" end; }) local INVALID_METHOD_NAME = "Object is a %* and as such expected `true?` for the method name and instead got %*. Traceback: %*" local METHOD_NOT_FOUND_ERROR = "Object %* doesn't have method %*, are you sure you want to add it? Traceback: %*" local NOT_A_PROMISE = "Invalid argument #1 to 'Janitor:AddPromise' (Promise expected, got %* (%*)) Traceback: %*" export type Janitor = typeof(setmetatable({} :: { CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, Add: <T>(self: Janitor, object: T, methodName: BooleanOrString?, index: any?) -> T, AddObject: <T, A...>( self: Janitor, constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, A... ) -> T, AddPromise: <T...>(self: Janitor, promiseObject: Promise<T...>) -> Promise<T...>, Remove: (self: Janitor, index: any) -> Janitor, RemoveNoClean: (self: Janitor, index: any) -> Janitor, RemoveList: (self: Janitor, ...any) -> Janitor, RemoveListNoClean: (self: Janitor, ...any) -> Janitor, Get: (self: Janitor, index: any) -> any?, GetAll: (self: Janitor) -> {[any]: any}, Cleanup: (self: Janitor) -> (), Destroy: (self: Janitor) -> (), LinkToInstance: (self: Janitor, Object: Instance, allowMultiple: boolean?) -> RBXScriptConnection, LinkToInstances: (self: Janitor, ...Instance) -> Janitor, }, {} :: {__call: (self: Janitor) -> ()})) type Private = typeof(setmetatable({} :: { CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, [any]: BooleanOrString, Add: <T>(self: Private, object: T, methodName: BooleanOrString?, index: any?) -> T, AddObject: <T, A...>( self: Private, constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, A... ) -> T, AddPromise: <T...>(self: Private, promiseObject: Promise<T...>) -> Promise<T...>, Remove: (self: Private, index: any) -> Private, RemoveNoClean: (self: Private, index: any) -> Private, RemoveList: (self: Private, ...any) -> Private, RemoveListNoClean: (self: Private, ...any) -> Private, Get: (self: Private, index: any) -> any?, GetAll: (self: Private) -> {[any]: any}, Cleanup: (self: Private) -> (), Destroy: (self: Private) -> (), LinkToInstance: (self: Private, object: Instance, allowMultiple: boolean?) -> RBXScriptConnection, LinkToInstances: (self: Private, ...Instance) -> Private, }, {} :: {__call: (self: Private) -> ()})) type Static = { ClassName: "Janitor", CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, new: () -> Janitor, Is: (object: any) -> boolean, instanceof: (object: any) -> boolean, } type PrivateStatic = Static & { __call: (self: Private) -> (), __tostring: (self: Private) -> string, } local Janitor = {} :: Janitor & Static local Private = Janitor :: Private & PrivateStatic Janitor.ClassName = "Janitor" Janitor.CurrentlyCleaning = true Janitor.SuppressInstanceReDestroy = false; (Janitor :: any).__index = Janitor local Janitors = setmetatable({} :: {[Private]: {[any]: any}}, {__mode = "k"}) local TYPE_DEFAULTS = { ["function"] = true; thread = true; RBXScriptConnection = "Disconnect"; } function Janitor.new(): Janitor return setmetatable({ CurrentlyCleaning = false; }, Janitor) :: never end function Janitor.Is(object: any): boolean return type(object) == "table" and getmetatable(object) == Janitor end Janitor.instanceof = Janitor.Is local function Remove(self: Private, index: any) local this = Janitors[self] if this then local object = this[index] if not object then return self end local methodName = self[object] if methodName then if methodName == true then if type(object) == "function" then object() else local wasCancelled: boolean = nil if coroutine.running() ~= object then wasCancelled = pcall(function() task.cancel(object) end) end if not wasCancelled then local toCleanup = object task.defer(function() task.cancel(toCleanup) end) end end else local objectMethod = object[methodName] if objectMethod then if self.SuppressInstanceReDestroy and methodName == "Destroy" and typeof(object) == "Instance" then pcall(objectMethod, object) else objectMethod(object) end end end self[object] = nil end this[index] = nil end return self end type BooleanOrString = boolean | string local function Add<T>(self: Private, object: T, methodName: BooleanOrString?, index: any?): T if index then Remove(self, index) local this = Janitors[self] if not this then this = {} Janitors[self] = this end this[index] = object end local typeOf = typeof(object) local newMethodName = methodName or TYPE_DEFAULTS[typeOf] or "Destroy" if typeOf == "function" or typeOf == "thread" then if newMethodName ~= true then warn(string.format(INVALID_METHOD_NAME, typeOf, tostring(newMethodName), debug.traceback(nil, 2))) end else if not (object :: never)[newMethodName] then warn( string.format( METHOD_NOT_FOUND_ERROR, tostring(object), tostring(newMethodName), debug.traceback(nil, 2) ) ) end end self[object] = newMethodName return object end Private.Add = Add function Janitor:AddObject<T, A...>(constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, ...: A...): T return Add(self, constructor.new(...), methodName, index) end function Janitor:AddPromise<T...>(promiseObject: Promise<T...>): Promise<T...> if not Promise then return promiseObject end if not Promise.is(promiseObject) then error(string.format(NOT_A_PROMISE, typeof(promiseObject), tostring(promiseObject), debug.traceback(nil, 2))) end if promiseObject:getStatus() == Promise.Status.Started then local uniqueId = newproxy(false) local newPromise = Add(self, Promise.new(function(resolve, _, onCancel) if onCancel(function() promiseObject:cancel() end) then return end resolve(promiseObject) end), "cancel", uniqueId) newPromise:finally(function() Remove(self, uniqueId) end) return newPromise :: never end return promiseObject end Private.Remove = Remove function Private:RemoveNoClean(index: any) local this = Janitors[self] if this then local object = this[index] if object then self[object] = nil this[index] = nil end end return self end function Janitor:RemoveList(...: any) local this = Janitors[self] if this then local length = select("#", ...) if length == 1 then return Remove(self, ...) end if length == 2 then local indexA, indexB = ... Remove(self, indexA) Remove(self, indexB) return self end if length == 3 then local indexA, indexB, indexC = ... Remove(self, indexA) Remove(self, indexB) Remove(self, indexC) return self end for selectIndex = 1, length do local removeObject = select(selectIndex, ...) Remove(self, removeObject) end end return self end function Janitor:RemoveListNoClean(...: any) local this = Janitors[self] if this then local length = select("#", ...) if length == 1 then local indexA = ... local object = this[indexA] if object then self[object] = nil this[indexA] = nil end return self end if length == 2 then local indexA, indexB = ... local objectA = this[indexA] if objectA then self[objectA] = nil this[indexA] = nil end local objectB = this[indexB] if objectB then self[objectB] = nil this[indexB] = nil end return self end if length == 3 then local indexA, indexB, indexC = ... local objectA = this[indexA] if objectA then self[objectA] = nil this[indexA] = nil end local objectB = this[indexB] if objectB then self[objectB] = nil this[indexB] = nil end local objectC = this[indexC] if objectC then self[objectC] = nil this[indexC] = nil end return self end for selectIndex = 1, length do local index = select(selectIndex, ...) local object = this[index] if object then self[object] = nil this[index] = nil end end end return self end function Janitor:Get(index: any): any? local this = Janitors[self] return if this then this[index] else nil end function Janitor:GetAll(): {[any]: any} local this = Janitors[self] return if this then table.freeze(table.clone(this)) else {} end local function GetFenv(self: Private): () -> (any, BooleanOrString) return function(): () for object, methodName in next, self do if object ~= "SuppressInstanceReDestroy" then return object, methodName end end end :: never end local function Cleanup(self: Private) if not self.CurrentlyCleaning then self.CurrentlyCleaning = nil :: never local get = GetFenv(self) local object, methodName = get() while object and methodName do if methodName == true then if type(object) == "function" then object() elseif type(object) == "thread" then local wasCancelled: boolean = nil if coroutine.running() ~= object then wasCancelled = pcall(function() task.cancel(object) end) end if not wasCancelled then local toCleanup = object task.defer(function() task.cancel(toCleanup) end) end end else local objectMethod = (object :: never)[methodName] :: (object: unknown) -> () if objectMethod then if self.SuppressInstanceReDestroy and methodName == "Destroy" and typeof(object) == "Instance" then pcall(objectMethod, object) else objectMethod(object) end end end self[object] = nil object, methodName = get() end local this = Janitors[self] if this then table.clear(this) Janitors[self] = nil end self.CurrentlyCleaning = false end end Private.Cleanup = Cleanup function Janitor:Destroy() Cleanup(self) table.clear(self :: never) setmetatable(self :: any, nil) end Private.__call = Cleanup local function LinkToInstance(self: Private, object: Instance, allowMultiple: boolean?): RBXScriptConnection local indexToUse = if allowMultiple then newproxy(false) else LinkToInstanceIndex return Add(self, object.Destroying:Connect(function() Cleanup(self) end), "Disconnect", indexToUse) end Private.LinkToInstance = LinkToInstance; (Janitor :: never).LegacyLinkToInstance = LinkToInstance function Janitor:LinkToInstances(...: Instance) local manualCleanup = Janitor.new() for index = 1, select("#", ...) do local object = select(index, ...) if typeof(object) ~= "Instance" then continue end manualCleanup:Add(LinkToInstance(self, object, true), "Disconnect") end return manualCleanup end function Private:__tostring() return "Janitor" end return Janitor :: Static
2,995
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/FairComparison.bench/Janitor18/FastDefer.luau
--!native --!optimize 2 --!strict local FreeThreads: {thread} = table.create(500) local function RunFunction<Arguments...>(callback: (Arguments...) -> (), thread: thread, ...: Arguments...) callback(...) table.insert(FreeThreads, thread) end local function Yield() while true do RunFunction(coroutine.yield()) end end local function FastDefer<Arguments...>(callback: (Arguments...) -> (), ...: Arguments...): thread local thread: thread local freeAmount = #FreeThreads if freeAmount > 0 then thread = FreeThreads[freeAmount] FreeThreads[freeAmount] = nil else thread = coroutine.create(Yield) coroutine.resume(thread) end -- TODO: This might be able to throw? return task.defer(thread, callback, thread, ...) end return FastDefer
193
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/FairComparison.bench/Trove.luau
--!optimize 2 --!strict local RunService = game:GetService("RunService") export type Trove = { Extend: (self: Trove) -> Trove, Clone: <T>(self: Trove, instance: T & Instance) -> T, Construct: <T, A...>(self: Trove, class: Constructable<T, A...>, A...) -> T, Connect: (self: Trove, signal: SignalLike | RBXScriptSignal, fn: (...any) -> ...any) -> ConnectionLike, BindToRenderStep: (self: Trove, name: string, priority: number, fn: (dt: number) -> ()) -> (), AddPromise: <T>(self: Trove, promise: T & PromiseLike) -> T, Add: <T>(self: Trove, object: T & Trackable, cleanupMethod: string?) -> T, Remove: <T>(self: Trove, object: T & Trackable) -> boolean, Clean: (self: Trove) -> (), WrapClean: (self: Trove) -> () -> (), AttachToInstance: (self: Trove, instance: Instance) -> RBXScriptConnection, Destroy: (self: Trove) -> (), } type TroveInternal = Trove & { _objects: {any}, _cleaning: boolean, _findAndRemoveFromObjects: (self: TroveInternal, object: any, cleanup: boolean) -> boolean, _cleanupObject: (self: TroveInternal, object: any, cleanupMethod: string?) -> (), } export type Trackable = Instance | RBXScriptConnection | ConnectionLike | PromiseLike | thread | ((...any) -> ...any) | Destroyable | DestroyableLowercase | Disconnectable | DisconnectableLowercase type ConnectionLike = { Connected: boolean, Disconnect: (self: ConnectionLike) -> (), } type SignalLike = { Connect: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike, Once: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike, } type PromiseLike = { getStatus: (self: PromiseLike) -> string, finally: (self: PromiseLike, callback: (...any) -> ...any) -> PromiseLike, cancel: (self: PromiseLike) -> (), } type Constructable<T, A...> = {new: (A...) -> T} | (A...) -> T type Destroyable = { Destroy: (self: Destroyable) -> (), } type DestroyableLowercase = { destroy: (self: DestroyableLowercase) -> (), } type Disconnectable = { Disconnect: (self: Disconnectable) -> (), } type DisconnectableLowercase = { disconnect: (self: DisconnectableLowercase) -> (), } local FN_MARKER = newproxy() local THREAD_MARKER = newproxy() local GENERIC_OBJECT_CLEANUP_METHODS = table.freeze({"Destroy", "Disconnect", "destroy", "disconnect"}) local function GetObjectCleanupFunction(object: any, cleanupMethod: string?) local t = typeof(object) if t == "function" then return FN_MARKER elseif t == "thread" then return THREAD_MARKER end if cleanupMethod then return cleanupMethod end if t == "Instance" then return "Destroy" elseif t == "RBXScriptConnection" then return "Disconnect" elseif t == "table" then for _, genericCleanupMethod in GENERIC_OBJECT_CLEANUP_METHODS do if typeof(object[genericCleanupMethod]) == "function" then return genericCleanupMethod end end end error(`failed to get cleanup function for object {t}: {object}`, 3) end local function AssertPromiseLike(object: any) if typeof(object) ~= "table" or typeof(object.getStatus) ~= "function" or typeof(object.finally) ~= "function" or typeof(object.cancel) ~= "function" then error("did not receive a promise as an argument", 3) end end local Trove = {} Trove.__index = Trove function Trove.new(): Trove local self = setmetatable({}, Trove) self._objects = {} self._cleaning = false return (self :: any) :: Trove end function Trove.Add(self: TroveInternal, object: Trackable, cleanupMethod: string?): any if self._cleaning then error("cannot call trove:Add() while cleaning", 2) end local cleanup = GetObjectCleanupFunction(object, cleanupMethod) table.insert(self._objects, {object, cleanup}) return object end function Trove.Clone(self: TroveInternal, instance: Instance): Instance if self._cleaning then error("cannot call trove:Clone() while cleaning", 2) end return self:Add(instance:Clone()) end function Trove.Construct<T, A...>(self: TroveInternal, class: Constructable<T, A...>, ...: A...) if self._cleaning then error("Cannot call trove:Construct() while cleaning", 2) end local object = nil local t = type(class) if t == "table" then object = (class :: any).new(...) elseif t == "function" then object = (class :: any)(...) end return self:Add(object) end function Trove.Connect(self: TroveInternal, signal: SignalLike, fn: (...any) -> ...any) if self._cleaning then error("Cannot call trove:Connect() while cleaning", 2) end return self:Add(signal:Connect(fn)) end function Trove.BindToRenderStep(self: TroveInternal, name: string, priority: number, fn: (dt: number) -> ()) if self._cleaning then error("cannot call trove:BindToRenderStep() while cleaning", 2) end RunService:BindToRenderStep(name, priority, fn) self:Add(function() RunService:UnbindFromRenderStep(name) end) end function Trove.AddPromise(self: TroveInternal, promise: PromiseLike) if self._cleaning then error("cannot call trove:AddPromise() while cleaning", 2) end AssertPromiseLike(promise) if promise:getStatus() == "Started" then promise:finally(function() if self._cleaning then return end self:_findAndRemoveFromObjects(promise, false) end) self:Add(promise, "cancel") end return promise end function Trove.Remove(self: TroveInternal, object: Trackable): boolean if self._cleaning then error("cannot call trove:Remove() while cleaning", 2) end return self:_findAndRemoveFromObjects(object, true) end function Trove.Extend(self: TroveInternal) if self._cleaning then error("cannot call trove:Extend() while cleaning", 2) end return self:Construct(Trove) end function Trove.Clean(self: TroveInternal) if self._cleaning then return end self._cleaning = true for _, obj in self._objects do self:_cleanupObject(obj[1], obj[2]) end table.clear(self._objects) self._cleaning = false end function Trove.WrapClean(self: TroveInternal) return function() self:Clean() end end function Trove._findAndRemoveFromObjects(self: TroveInternal, object: any, cleanup: boolean): boolean local objects = self._objects for i, obj in objects do if obj[1] == object then local n = #objects objects[i] = objects[n] objects[n] = nil if cleanup then self:_cleanupObject(obj[1], obj[2]) end return true end end return false end function Trove._cleanupObject(_self: TroveInternal, object: any, cleanupMethod: string?) if cleanupMethod == FN_MARKER then task.spawn(object) elseif cleanupMethod == THREAD_MARKER then pcall(task.cancel, object) else object[cleanupMethod](object) end end function Trove.AttachToInstance(self: TroveInternal, instance: Instance) if self._cleaning then error("cannot call trove:AttachToInstance() while cleaning", 2) elseif not instance:IsDescendantOf(game) then error("instance is not a descendant of the game hierarchy", 2) end return self:Connect(instance.Destroying, function() self:Destroy() end) end function Trove.Destroy(self: TroveInternal) self:Clean() end return { new = Trove.new; }
1,927
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/FairComparison.bench/init.luau
--!optimize 2 --!strict local Duster = require(script.Duster) local Janitor17 = require(script.Janitor17) local Janitor18 = require(script.Janitor18) local Maid = require(script.Maid) local Trove = require(script.Trove) local UltraJanitor18 = require(script.UltraJanitor18) type IProfiler = { Begin: (label: string) -> (), End: () -> (), Start: (label: string) -> (), Stop: () -> (), Open: (label: string) -> (), Close: () -> (), Enter: (label: string) -> (), Exit: () -> (), begin: (label: string) -> (), ["end"]: () -> (), -- what start: (label: string) -> (), stop: () -> (), open: (label: string) -> (), close: () -> (), enter: (label: string) -> (), exit: () -> (), } type IBenchmark<T... = ...nil> = { ParameterGenerator: () -> T...?, Functions: {[string]: (Profiler: IProfiler, T...) -> ()}, } local function CreateBenchmark<T...>( ParameterGenerator: () -> T...?, Functions: {[string]: (Profiler: IProfiler, T...) -> ()} ): IBenchmark<T...> return { ParameterGenerator = ParameterGenerator; Functions = Functions; } end type BasicClass = { CleanupFunction: nil | () -> (), AddCleanupFunction: (self: BasicClass, callback: nil | () -> ()) -> BasicClass, Destroy: (self: BasicClass) -> (), } type Static = { ClassName: "BasicClass", new: () -> BasicClass, } local BasicClass = {} :: BasicClass & Static BasicClass.ClassName = "BasicClass"; (BasicClass :: any).__index = BasicClass function BasicClass.new(): BasicClass return setmetatable({ CleanupFunction = nil; }, BasicClass) :: never end function BasicClass:AddCleanupFunction(callback: nil | () -> ()): BasicClass self.CleanupFunction = callback return self end function BasicClass:Destroy(): () local cleanupFunction = self.CleanupFunction if cleanupFunction then cleanupFunction() end table.clear(self) setmetatable(self, nil) end local function NoOperation(): () end local DIVIDE_BY = 550 local functionsToAdd = 1_000_000 // DIVIDE_BY local threadsToAdd = 200_000 // DIVIDE_BY local classesToAdd = 1_000_000 // DIVIDE_BY local instancesToAdd = 100_000 // DIVIDE_BY local Add = UltraJanitor18.new().Add local Cleanup = UltraJanitor18.new().Cleanup local Benchmark = CreateBenchmark(function() return end, { ["Janitor 1.17.0"] = function() local janitor = Janitor17.new() local functionsJanitor = janitor:Add(Janitor17.new(), "Cleanup") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true) end local threadsJanitor = janitor:Add(Janitor17.new(), "Cleanup") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true) end local classesJanitor = janitor:Add(Janitor17.new(), "Cleanup") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = janitor:Add(Janitor17.new(), "Cleanup") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end janitor:Destroy() end; ["Janitor 1.18.2"] = function() local janitor = Janitor18.new() local functionsJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true) end local threadsJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true) end local classesJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end janitor:Cleanup() end; ["Ultra Janitor 1.18.2"] = function() local janitor = UltraJanitor18.new() local functionsJanitor = Add(janitor, UltraJanitor18.new(), "Cleanup") for _ = 1, functionsToAdd do Add(functionsJanitor, NoOperation, true) end local threadsJanitor = Add(janitor, UltraJanitor18.new(), "Cleanup") for _ = 1, threadsToAdd do Add(threadsJanitor, task.delay(5, NoOperation), true) end local classesJanitor = Add(janitor, UltraJanitor18.new(), "Cleanup") for _ = 1, classesToAdd do Add(classesJanitor, BasicClass.new(), "Destroy") end local instancesJanitor = Add(janitor, UltraJanitor18.new(), "Cleanup") for _ = 1, instancesToAdd do Add(instancesJanitor, Instance.new("Folder"), "Destroy") end Cleanup(janitor) end; ["Janitor 1.18.2 Unsafe"] = function() local janitor = Janitor18.new() janitor.UnsafeThreadCleanup = true local functionsJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true) end local threadsJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true) end local classesJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = janitor:Add(Janitor18.new(), "Cleanup") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end janitor:Cleanup() end; -- Lesser beings ["Trove 1.5.0"] = function() local trove = Trove.new() local functionsJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation) end local threadsJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation)) end local classesJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end trove:Destroy() end; ["Maid"] = function() local maid = Maid.new() local functionsJanitor = maid:Add(Maid.new()) for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation) end local threadsJanitor = maid:Add(Maid.new()) for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation)) end local classesJanitor = maid:Add(Maid.new()) for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new()) end local instancesJanitor = maid:Add(Maid.new()) for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder")) end maid:Destroy() end; ["Duster"] = function() local duster: {Duster.Cleanable} = {} local functionsJanitor: {Duster.Cleanable} = {} Duster.insert(duster, function() Duster.clear(functionsJanitor) end) for _ = 1, functionsToAdd do Duster.insert(functionsJanitor, NoOperation) end local threadsJanitor: {Duster.Cleanable} = {} Duster.insert(duster, function() Duster.clear(threadsJanitor) end) for _ = 1, threadsToAdd do Duster.insert(threadsJanitor, task.delay(5, NoOperation)) end local classesJanitor: {Duster.Cleanable} = {} Duster.insert(duster, function() Duster.clear(classesJanitor) end) for _ = 1, classesToAdd do Duster.insert(classesJanitor, BasicClass.new() :: never) end local instancesJanitor: {Duster.Cleanable} = {} Duster.insert(duster, function() Duster.clear(instancesJanitor) end) for _ = 1, instancesToAdd do Duster.insert(instancesJanitor, Instance.new("Folder")) end Duster.clear(duster) end; }) return Benchmark
2,174
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/UnfairComparison.bench/Janitor18/init.luau
--!optimize 2 --!strict local FastDefer = require(script.FastDefer) local Promise = require(script.Promise) type Promise<T...> = Promise.TypedPromise<T...> local LinkToInstanceIndex = setmetatable({}, { __tostring = function() return "LinkToInstanceIndex" end; }) local INVALID_METHOD_NAME = "Object is a %* and as such expected `true?` for the method name and instead got %*. Traceback: %*" local METHOD_NOT_FOUND_ERROR = "Object %* doesn't have method %*, are you sure you want to add it? Traceback: %*" local NOT_A_PROMISE = "Invalid argument #1 to 'Janitor:AddPromise' (Promise expected, got %* (%*)) Traceback: %*" export type Janitor = typeof(setmetatable({} :: { CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, UnsafeThreadCleanup: boolean, Add: <T>(self: Janitor, object: T, methodName: BooleanOrString?, index: any?) -> T, AddObject: <T, A...>( self: Janitor, constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, A... ) -> T, AddPromise: <T...>(self: Janitor, promiseObject: Promise<T...>, index: unknown?) -> Promise<T...>, Remove: (self: Janitor, index: any) -> Janitor, RemoveNoClean: (self: Janitor, index: any) -> Janitor, RemoveList: (self: Janitor, ...any) -> Janitor, RemoveListNoClean: (self: Janitor, ...any) -> Janitor, Get: (self: Janitor, index: any) -> any?, GetAll: (self: Janitor) -> {[any]: any}, Cleanup: (self: Janitor) -> (), Destroy: (self: Janitor) -> (), LinkToInstance: (self: Janitor, Object: Instance, allowMultiple: boolean?) -> RBXScriptConnection, LinkToInstances: (self: Janitor, ...Instance) -> Janitor, }, {} :: {__call: (self: Janitor) -> ()})) type Private = typeof(setmetatable({} :: { CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, UnsafeThreadCleanup: boolean, [any]: BooleanOrString, Add: <T>(self: Private, object: T, methodName: BooleanOrString?, index: any?) -> T, AddObject: <T, A...>( self: Private, constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, A... ) -> T, AddPromise: <T...>(self: Private, promiseObject: Promise<T...>, index: unknown?) -> Promise<T...>, Remove: (self: Private, index: any) -> Private, RemoveNoClean: (self: Private, index: any) -> Private, RemoveList: (self: Private, ...any) -> Private, RemoveListNoClean: (self: Private, ...any) -> Private, Get: (self: Private, index: any) -> any?, GetAll: (self: Private) -> {[any]: any}, Cleanup: (self: Private) -> (), Destroy: (self: Private) -> (), LinkToInstance: (self: Private, object: Instance, allowMultiple: boolean?) -> RBXScriptConnection, LinkToInstances: (self: Private, ...Instance) -> Private, }, {} :: {__call: (self: Private) -> ()})) type Static = { ClassName: "Janitor", CurrentlyCleaning: boolean, SuppressInstanceReDestroy: boolean, UnsafeThreadCleanup: boolean, new: () -> Janitor, Is: (object: any) -> boolean, instanceof: (object: any) -> boolean, } type PrivateStatic = Static & { __call: (self: Private) -> (), __tostring: (self: Private) -> string, } local Janitor = {} :: Janitor & Static local Private = Janitor :: Private & PrivateStatic Janitor.ClassName = "Janitor" Janitor.CurrentlyCleaning = true Janitor.SuppressInstanceReDestroy = false Janitor.UnsafeThreadCleanup = false; (Janitor :: any).__index = Janitor local Janitors = setmetatable({} :: {[Private]: {[any]: any}}, {__mode = "ks"}) local TYPE_DEFAULTS = { ["function"] = true; thread = true; RBXScriptConnection = "Disconnect"; } function Janitor.new(): Janitor return setmetatable({ CurrentlyCleaning = false; }, Janitor) :: never end function Janitor.Is(object: any): boolean return type(object) == "table" and getmetatable(object) == Janitor end Janitor.instanceof = Janitor.Is local function Remove(self: Private, index: any): Janitor local this = Janitors[self] if this then local object = this[index] if not object then return self end local methodName = self[object] if methodName then if methodName == true then if type(object) == "function" then object() else local wasCancelled: boolean = nil if coroutine.running() ~= object then wasCancelled = pcall(function() task.cancel(object) end) end if not wasCancelled then if self.UnsafeThreadCleanup then FastDefer(function() task.cancel(object) end) else task.defer(function() task.cancel(object) end) end end end else local objectMethod = object[methodName] if objectMethod then if self.SuppressInstanceReDestroy and methodName == "Destroy" and typeof(object) == "Instance" then pcall(objectMethod, object) else objectMethod(object) end end end self[object] = nil end this[index] = nil end return self end type BooleanOrString = boolean | string local function Add<T>(self: Private, object: T, methodName: BooleanOrString?, index: any?): T if index then Remove(self, index) local this = Janitors[self] if not this then this = {} Janitors[self] = this end this[index] = object end local typeOf = typeof(object) local newMethodName = methodName or TYPE_DEFAULTS[typeOf] or "Destroy" if typeOf == "function" or typeOf == "thread" then if newMethodName ~= true then warn(string.format(INVALID_METHOD_NAME, typeOf, tostring(newMethodName), debug.traceback(nil, 2))) end else if not (object :: never)[newMethodName] then warn( string.format( METHOD_NOT_FOUND_ERROR, tostring(object), tostring(newMethodName), debug.traceback(nil, 2) ) ) end end self[object] = newMethodName return object end Private.Add = Add function Janitor:AddObject<T, A...>(constructor: {new: (A...) -> T}, methodName: BooleanOrString?, index: any?, ...: A...): T return Add(self, constructor.new(...), methodName, index) end local function Get(self: Private, index: unknown): any? local this = Janitors[self] return if this then this[index] else nil end Janitor.Get = Get function Janitor:AddPromise<T...>(promiseObject: Promise<T...>, index: unknown?): Promise<T...> if not Promise then return promiseObject end if not Promise.is(promiseObject) then error(string.format(NOT_A_PROMISE, typeof(promiseObject), tostring(promiseObject), debug.traceback(nil, 2))) end if promiseObject:getStatus() ~= Promise.Status.Started then return promiseObject end local uniqueId = index if uniqueId == nil then uniqueId = newproxy(false) end local newPromise = Add(self, Promise.new(function(resolve, _, onCancel) if onCancel(function() promiseObject:cancel() end) then return end resolve(promiseObject) end), "cancel", uniqueId) newPromise:finally(function() if Get(self, uniqueId) == newPromise then Remove(self, uniqueId) end end) return newPromise :: never end Private.Remove = Remove function Private:RemoveNoClean(index: any): Janitor local this = Janitors[self] if this then local object = this[index] if object then self[object] = nil this[index] = nil end end return self end function Janitor:RemoveList(...: any): Janitor local this = Janitors[self] if this then local length = select("#", ...) if length == 1 then return Remove(self, ...) end if length == 2 then local indexA, indexB = ... Remove(self, indexA) Remove(self, indexB) return self end if length == 3 then local indexA, indexB, indexC = ... Remove(self, indexA) Remove(self, indexB) Remove(self, indexC) return self end for selectIndex = 1, length do local removeObject = select(selectIndex, ...) Remove(self, removeObject) end end return self end function Janitor:RemoveListNoClean(...: any): Janitor local this = Janitors[self] if this then local length = select("#", ...) if length == 1 then local indexA = ... local object = this[indexA] if object then self[object] = nil this[indexA] = nil end return self end if length == 2 then local indexA, indexB = ... local objectA = this[indexA] if objectA then self[objectA] = nil this[indexA] = nil end local objectB = this[indexB] if objectB then self[objectB] = nil this[indexB] = nil end return self end if length == 3 then local indexA, indexB, indexC = ... local objectA = this[indexA] if objectA then self[objectA] = nil this[indexA] = nil end local objectB = this[indexB] if objectB then self[objectB] = nil this[indexB] = nil end local objectC = this[indexC] if objectC then self[objectC] = nil this[indexC] = nil end return self end for selectIndex = 1, length do local index = select(selectIndex, ...) local object = this[index] if object then self[object] = nil this[index] = nil end end end return self end function Janitor:GetAll(): {[any]: any} local this = Janitors[self] return if this then table.freeze(table.clone(this)) else {} end local function Cleanup(self: Private): () if not self.CurrentlyCleaning then local suppressInstanceReDestroy = self.SuppressInstanceReDestroy local unsafeThreadCleanup = self.UnsafeThreadCleanup self.CurrentlyCleaning = nil :: never self.SuppressInstanceReDestroy = nil :: never self.UnsafeThreadCleanup = nil :: never local object, methodName = next(self) while object and methodName do if methodName == true then if type(object) == "function" then object() elseif type(object) == "thread" then local wasCancelled: boolean? = nil if coroutine.running() ~= object then wasCancelled = pcall(function() task.cancel(object) end) end if not wasCancelled then local toCleanup = object if unsafeThreadCleanup then FastDefer(function() task.cancel(toCleanup) end) else task.defer(function() task.cancel(toCleanup) end) end end end else local objectMethod = (object :: never)[methodName] :: (object: unknown) -> () if objectMethod then if suppressInstanceReDestroy and methodName == "Destroy" and typeof(object) == "Instance" then pcall(objectMethod, object) else objectMethod(object) end end end self[object] = nil object, methodName = next(self, object) end local this = Janitors[self] if this then table.clear(this) Janitors[self] = nil end self.CurrentlyCleaning = false self.SuppressInstanceReDestroy = suppressInstanceReDestroy self.UnsafeThreadCleanup = unsafeThreadCleanup end end Private.Cleanup = Cleanup function Janitor:Destroy(): () Cleanup(self) table.clear(self :: never) setmetatable(self :: any, nil) end Private.__call = Cleanup local function LinkToInstance(self: Private, object: Instance, allowMultiple: boolean?): RBXScriptConnection local indexToUse = if allowMultiple then newproxy(false) else LinkToInstanceIndex return Add(self, object.Destroying:Connect(function() Cleanup(self) end), "Disconnect", indexToUse) end Private.LinkToInstance = LinkToInstance; (Janitor :: never).LegacyLinkToInstance = LinkToInstance function Janitor:LinkToInstances(...: Instance): Janitor local manualCleanup = Janitor.new() for index = 1, select("#", ...) do local object = select(index, ...) if typeof(object) ~= "Instance" then continue end manualCleanup:Add(LinkToInstance(self, object, true), "Disconnect") end return manualCleanup end function Private:__tostring() return "Janitor" end return Janitor :: Static
3,155
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/UnfairComparison.bench/Troveitor/init.luau
--!optimize 2 --!strict local RunService = game:GetService("RunService") local Janitor = require(script.Parent.Janitor18) local Promise = require(script.Promise) type ConnectionLike = { Connected: boolean, Disconnect: (self: ConnectionLike) -> (), } type SignalLike = { Connect: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike, Once: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike, } type PromiseLike = { getStatus: (self: PromiseLike) -> string, finally: (self: PromiseLike, callback: (...any) -> ...any) -> PromiseLike, cancel: (self: PromiseLike) -> (), } type Constructable<T, A...> = {new: (A...) -> T} | (A...) -> T type Destroyable = { Destroy: (self: Destroyable) -> (), } type DestroyableLowercase = { destroy: (self: DestroyableLowercase) -> (), } type Disconnectable = { Disconnect: (self: Disconnectable) -> (), } type DisconnectableLowercase = { disconnect: (self: DisconnectableLowercase) -> (), } export type Trackable = Instance | RBXScriptConnection | ConnectionLike | Promise.TypedPromise<...any> | thread | ((...any) -> ...any) | Destroyable | DestroyableLowercase | Disconnectable | DisconnectableLowercase export type Trove = { Add: <T>(self: Trove, object: T, cleanupMethod: string?) -> T, AddPromise: <T...>(self: Trove, promise: Promise.TypedPromise<T...>) -> Promise.TypedPromise<T...>, AttachToInstance: (self: Trove, instance: Instance) -> RBXScriptConnection, BindToRenderStep: (self: Trove, name: string, priority: number, fn: (dt: number) -> ()) -> (), Clean: (self: Trove) -> (), Clone: <T>(self: Trove, instance: T & Instance) -> T, Connect: (self: Trove, signal: SignalLike | RBXScriptSignal, fn: (...any) -> ...any) -> ConnectionLike, Construct: <T, A...>(self: Trove, class: Constructable<T, A...>, A...) -> T, Extend: (self: Trove) -> Trove, Remove: (self: Trove, object: Trackable) -> boolean, WrapClean: (self: Trove) -> () -> (), Destroy: (self: Trove) -> (), } type Private = { Janitor: Janitor.Janitor, Add: <T>(self: Private, object: T, cleanupMethod: string?) -> T, AddPromise: <T...>(self: Private, promise: Promise.TypedPromise<T...>) -> Promise.TypedPromise<T...>, AttachToInstance: (self: Private, instance: Instance) -> RBXScriptConnection, BindToRenderStep: (self: Private, name: string, priority: number, fn: (dt: number) -> ()) -> (), Clean: (self: Private) -> (), Clone: <T>(self: Private, instance: T & Instance) -> T, Connect: (self: Private, signal: SignalLike | RBXScriptSignal, fn: (...any) -> ...any) -> ConnectionLike, Construct: <T, A...>(self: Private, class: Constructable<T, A...>, A...) -> T, Extend: (self: Private) -> Private, Remove: (self: Private, object: Trackable) -> boolean, WrapClean: (self: Private) -> () -> (), Destroy: (self: Private) -> (), } type Static = { ClassName: "Trove", new: () -> Trove, } local Trove = {} :: Trove & Static local Private = Trove :: Private & Static Trove.ClassName = "Trove"; (Trove :: any).__index = Trove function Trove.new(): Trove return setmetatable({ Janitor = Janitor.new(); }, Trove) :: never end function Private:Add<T>(object: T, cleanupMethod): T return self.Janitor:Add(object, cleanupMethod, object) end function Private:AddPromise<T...>(object) return self.Janitor:AddPromise(object) end function Private:AttachToInstance(object) if not object:IsDescendantOf(game) then error("instance is not a descendant of the game hierarchy", 2) end return self.Janitor:LinkToInstance(object, false) end function Private:BindToRenderStep(name, priority, callback) RunService:BindToRenderStep(name, priority, callback) self:Add(function() RunService:UnbindFromRenderStep(name) end) end function Private:Clean() self.Janitor:Cleanup() end function Private:Clone<T>(instance) local object = instance:Clone() return self.Janitor:Add(object, "Destroy", object) end function Private:Connect(signal, callback) return self:Add((signal :: any):Connect(callback)) end function Private:Construct<T, A...>(class, ...) local object = nil local t = type(class) if t == "table" then object = (class :: any).new(...) elseif t == "function" then object = (class :: any)(...) end return self:Add(object) end function Private:Extend() return self:Add(Trove.new()) :: never end function Private:Remove(object) if self.Janitor:Get(object) == nil then return false end self.Janitor:Remove(object) return self.Janitor:Get(object) == nil end function Private:Destroy() self:Clean() end function Private:WrapClean() return function() self:Clean() end end return table.freeze(Trove :: Static)
1,296
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/benchmarks/UnfairComparison.bench/init.luau
--!optimize 2 --!strict -- for reference, unfair in this case means unfair to JANITOR. local Janitor17 = require(script.Janitor17) local Janitor18 = require(script.Janitor18) local Maid = require(script.Maid) local Trove = require(script.Trove) local Troveitor = require(script.Troveitor) type IProfiler = { Begin: (label: string) -> (), End: () -> (), Start: (label: string) -> (), Stop: () -> (), Open: (label: string) -> (), Close: () -> (), Enter: (label: string) -> (), Exit: () -> (), begin: (label: string) -> (), ["end"]: () -> (), -- what start: (label: string) -> (), stop: () -> (), open: (label: string) -> (), close: () -> (), enter: (label: string) -> (), exit: () -> (), } type IBenchmark<T... = ...nil> = { ParameterGenerator: () -> T...?, Functions: {[string]: (Profiler: IProfiler, T...) -> ()}, } local function CreateBenchmark<T...>( ParameterGenerator: () -> T...?, Functions: {[string]: (Profiler: IProfiler, T...) -> ()} ): IBenchmark<T...> return { ParameterGenerator = ParameterGenerator; Functions = Functions; } end type BasicClass = { CleanupFunction: nil | () -> (), AddCleanupFunction: (self: BasicClass, callback: nil | () -> ()) -> BasicClass, Destroy: (self: BasicClass) -> (), } type Static = { ClassName: "BasicClass", new: () -> BasicClass, } local BasicClass = {} :: BasicClass & Static BasicClass.ClassName = "BasicClass"; (BasicClass :: any).__index = BasicClass function BasicClass.new(): BasicClass return setmetatable({ CleanupFunction = nil; }, BasicClass) :: never end function BasicClass:AddCleanupFunction(callback: nil | () -> ()): BasicClass self.CleanupFunction = callback return self end function BasicClass:Destroy(): () local cleanupFunction = self.CleanupFunction if cleanupFunction then cleanupFunction() end table.clear(self) setmetatable(self, nil) end local function NoOperation(): () end local functionsToAdd = 1_000_000 // 500 local threadsToAdd = 200_000 // 500 local classesToAdd = 1_000_000 // 500 local instancesToAdd = 100_000 // 500 local Benchmark = CreateBenchmark(function() return end, { ["Janitor 1.17.0"] = function() local janitor = Janitor17.new() local functionsJanitor = janitor:Add(Janitor17.new(), "Cleanup", "Functions") for index = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true, index) end local threadsJanitor = janitor:Add(Janitor17.new(), "Cleanup", "Threads") for index = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true, index) end local classesJanitor = janitor:Add(Janitor17.new(), "Cleanup", "Classes") for index = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy", index) end local instancesJanitor = janitor:Add(Janitor17.new(), "Cleanup", "Instances") for index = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy", index) end janitor:Destroy() end; ["Janitor 1.18.0"] = function() local janitor = Janitor18.new() local functionsJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Functions") for index = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true, index) end local threadsJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Threads") for index = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true, index) end local classesJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Classes") for index = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy", index) end local instancesJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Instances") for index = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy", index) end janitor:Destroy() end; ["Janitor 1.18.0 Unsafe"] = function() local janitor = Janitor18.new() janitor.UnsafeThreadCleanup = true local functionsJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Functions") for index = 1, functionsToAdd do functionsJanitor:Add(NoOperation, true, index) end local threadsJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Threads") for index = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation), true, index) end local classesJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Classes") for index = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy", index) end local instancesJanitor = janitor:Add(Janitor18.new(), "Cleanup", "Instances") for index = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy", index) end janitor:Destroy() end; ["Troveitor"] = function() local trove = Troveitor.new() local functionsJanitor = trove:Add(Troveitor.new(), "Clean") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation) end local threadsJanitor = trove:Add(Troveitor.new(), "Clean") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation)) end local classesJanitor = trove:Add(Troveitor.new(), "Clean") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = trove:Add(Troveitor.new(), "Clean") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end trove:Destroy() end; -- Lesser beings ["Trove 1.5.0"] = function() local trove = Trove.new() local functionsJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation) end local threadsJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation)) end local classesJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new(), "Destroy") end local instancesJanitor = trove:Add(Trove.new(), "Clean") for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder"), "Destroy") end trove:Destroy() end; ["Maid"] = function() local maid = Maid.new() local functionsJanitor = maid:Add(Maid.new()) for _ = 1, functionsToAdd do functionsJanitor:Add(NoOperation) end local threadsJanitor = maid:Add(Maid.new()) for _ = 1, threadsToAdd do threadsJanitor:Add(task.delay(5, NoOperation)) end local classesJanitor = maid:Add(Maid.new()) for _ = 1, classesToAdd do classesJanitor:Add(BasicClass.new()) end local instancesJanitor = maid:Add(Maid.new()) for _ = 1, instancesToAdd do instancesJanitor:Add(Instance.new("Folder")) end maid:Destroy() end; }) return Benchmark
1,891
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/luau/run-package-tests.luau
--!optimize 2 --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") local Jest = require(ReplicatedStorage.DevPackages.Jest) local processServiceExists, ProcessService = pcall(function() local s = "ProcessService" return game:GetService(s) end) local status, result = Jest.runCLI(ReplicatedStorage.Janitor, { all = true; ci = false; verbose = true; }, {ReplicatedStorage.Janitor}):awaitStatus() if status == "Rejected" then print(result) end if status == "Resolved" and result.results.numFailedTestSuites == 0 and result.results.numFailedTests == 0 then if processServiceExists then ProcessService:ExitAsync(0) end end if processServiceExists then ProcessService:ExitAsync(1) end return nil
187
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/src/__tests__/Janitor.test.luau
--!optimize 2 --!strict _G.__IS_UNIT_TESTING__ = true local ReplicatedStorage = game:GetService("ReplicatedStorage") local Workspace = game:GetService("Workspace") local JestGlobals = require(script.Parent.Parent.Parent.DevPackages.JestGlobals) local Janitor = require(script.Parent.Parent) local Promise = require(script.Parent.Parent.Promise) local describe = JestGlobals.describe local expect = JestGlobals.expect local it = JestGlobals.it local IS_DEFERRED = (function() local bindableEvent = Instance.new("BindableEvent") local handlerRun = false bindableEvent.Event:Once(function() handlerRun = true end) bindableEvent:Fire() bindableEvent:Destroy() return not handlerRun end)() local function AwaitCondition(predicate: () -> boolean, timeout: number?): boolean local trueTimeout = timeout or 10 local startTime = os.clock() while true do if predicate() then return true end if os.clock() - startTime > trueTimeout then return false end task.wait() end end type BasicClass = { CleanupFunction: nil | () -> (), AddCleanupFunction: (self: BasicClass, callback: nil | () -> ()) -> BasicClass, Destroy: (self: BasicClass) -> (), } type Static = { ClassName: "BasicClass", new: () -> BasicClass, } local BasicClass = {} :: BasicClass & Static BasicClass.ClassName = "BasicClass"; (BasicClass :: any).__index = BasicClass function BasicClass.new(): BasicClass return setmetatable({ CleanupFunction = nil; }, BasicClass) :: never end function BasicClass:AddCleanupFunction(callback: nil | () -> ()): BasicClass self.CleanupFunction = callback return self end function BasicClass:Destroy(): () local cleanupFunction = self.CleanupFunction if cleanupFunction then cleanupFunction() end table.clear(self) setmetatable(self, nil) end local function NoOperation(): () end describe("Janitor.Is", function() it("should return true iff the passed value is a Janitor", function() local janitor = Janitor.new() expect(Janitor.Is(janitor)).toBe(true) janitor:Destroy() end) it("should return false iff the passed value is anything else", function() expect(Janitor.Is(NoOperation)).toBe(false) expect(Janitor.Is({})).toBe(false) expect(Janitor.Is(BasicClass.new())).toBe(false) end) end) describe("Janitor.new", function() it("should create a new Janitor", function() local janitor = Janitor.new() expect(janitor).toBeDefined() expect(Janitor.Is(janitor)).toBe(true) janitor:Destroy() end) end) describe("Janitor.Add", function() it("should add things", function() local janitor = Janitor.new() expect(function() janitor:Add(NoOperation, true) end).never.toThrow() janitor:Destroy() end) it("should add things with the given index", function() local janitor = Janitor.new() expect(function() janitor:Add(NoOperation, true, "Function") end).never.toThrow() expect(janitor:Get("Function")).toEqual(expect.any("function")) janitor:Destroy() end) it("should overwrite indexes", function() local janitor = Janitor.new() local wasRemoved = false janitor:Add(function() wasRemoved = true end, true, "Function") janitor:Add(NoOperation, true, "Function") expect(wasRemoved).toBe(true) janitor:Destroy() end) it("should return the passed object", function() local janitor = Janitor.new() local part = janitor:Add(Instance.new("Part"), "Destroy") expect(part).toBeDefined() expect(part).toEqual(expect.any("Instance")) expect(part.ClassName).toBe("Part") janitor:Destroy() end) it("should clean up instances, objects, functions, connections, and threads", function() local functionWasDestroyed = false local janitorWasDestroyed = false local basicClassWasDestroyed = false local threadWasRan = false local janitor = Janitor.new() local part = janitor:Add(Instance.new("Part"), "Destroy") part.Parent = ReplicatedStorage local connection = janitor:Add(part.ChildRemoved:Connect(NoOperation), "Disconnect") janitor:Add(function() functionWasDestroyed = true end, true) janitor:Add(Janitor.new(), "Destroy"):Add(function() janitorWasDestroyed = true end, true) janitor:Add(BasicClass.new(), "Destroy"):AddCleanupFunction(function() basicClassWasDestroyed = true end) janitor:Add(task.delay(1, function() threadWasRan = true end), true) janitor:Destroy() expect(part.Parent).toBeUndefined() expect(connection.Connected).toBe(false) expect(functionWasDestroyed).toBe(true) expect(janitorWasDestroyed).toBe(true) expect(basicClassWasDestroyed).toBe(true) expect(threadWasRan).toBe(false) end) it("should clean up everything correctly", function() local janitor = Janitor.new() local cleanedUp = 0 local totalToAdd = 5000 for index = 1, totalToAdd do janitor:Add(function() cleanedUp += 1 end, true, index) end for index = totalToAdd, 1, -1 do janitor:Remove(index) end janitor:Destroy() expect(cleanedUp).toBe(totalToAdd) end) it("should infer types if not given", function() local janitor = Janitor.new() local connection = janitor:Add(ReplicatedStorage.AncestryChanged:Connect(NoOperation)) janitor:Destroy() if IS_DEFERRED then task.wait() end expect(connection.Connected).toBe(false) end) end) describe("Janitor.AddPromise", function() if not Promise then return end it("should add a Promise", function() local janitor = Janitor.new() local addedPromise = janitor:AddPromise(Promise.delay(60)) expect(Promise.is(addedPromise)).toBe(true) janitor:Destroy() end) it("should cancel the Promise when destroyed", function() local janitor = Janitor.new() local wasCancelled = false janitor:AddPromise(Promise.new(function(resolve, _, onCancel) if onCancel(function() wasCancelled = true end) then return end return Promise.delay(60):andThen(resolve) end)) janitor:Destroy() expect(wasCancelled).toBe(true) end) it("should not remove any values from the return", function() local janitor = Janitor.new() local _, value = janitor :AddPromise(Promise.new(function(resolve) resolve(true) end)) :await() expect(value).toBe(true) janitor:Destroy() end) it("should throw if the passed value isn't a Promise", function() local janitor = Janitor.new() expect(function() janitor:AddPromise(BasicClass.new() :: never) end).toThrow() janitor:Destroy() end) end) describe("Janitor.Remove", function() it("should always return the Janitor", function() local janitor = Janitor.new() janitor:Add(NoOperation, true, "Function") expect(janitor:Remove("Function")).toBe(janitor) expect(janitor:Remove("Function")).toBe(janitor) janitor:Destroy() end) it("should always remove the value", function() local janitor = Janitor.new() local wasRemoved = false janitor:Add(function() wasRemoved = true end, true, "Function") janitor:Remove("Function") expect(AwaitCondition(function() return wasRemoved end, 1)).toBe(true) janitor:Destroy() end) it("should properly remove values that are already destroyed", function() -- credit to OverHash for pointing out this breaking. local janitor = Janitor.new() local value = 0 local subJanitor = Janitor.new() subJanitor:Add(function() value += 1 end, true) janitor:Add(subJanitor, "Destroy") subJanitor:Destroy() expect(function() janitor:Destroy() end).never.toThrow() expect(value).toBe(1) end) it("should clean up everything efficiently", function() local janitor = Janitor.new() local functionsToAdd = 1_000_000 local threadsToAdd = 200_000 local classesToAdd = 1_000_000 local instancesToAdd = 100_000 local amountAdded = 0 for _ = 1, functionsToAdd do amountAdded += 1 janitor:Add(NoOperation, true, amountAdded) end for _ = 1, threadsToAdd do amountAdded += 1 janitor:Add(task.delay(5, NoOperation), true, amountAdded) end for _ = 1, classesToAdd do amountAdded += 1 janitor:Add(BasicClass.new(), "Destroy", amountAdded) end for _ = 1, instancesToAdd do amountAdded += 1 janitor:Add(Instance.new("Part"), "Destroy", amountAdded) end for index = 1, amountAdded do janitor:Remove(index) end janitor:Destroy() end) end) describe("Janitor.RemoveList", function() it("should always return the Janitor", function() local janitor = Janitor.new() janitor:Add(NoOperation, true, "Function") expect(janitor:RemoveList("Function")).toBe(janitor) expect(janitor:RemoveList("Function")).toBe(janitor) janitor:Destroy() end) it("should always remove the value", function() local janitor = Janitor.new() local wasRemoved = false janitor:Add(function() wasRemoved = true end, true, "Function") janitor:RemoveList("Function") expect(wasRemoved).toBe(true) janitor:Destroy() end) it("should properly remove multiple values", function() local janitor = Janitor.new() local oneRan = false local twoRan = false local threeRan = false janitor:Add(function() oneRan = true end, true, 1) janitor:Add(function() twoRan = true end, true, 2) janitor:Add(function() threeRan = true end, true, 3) janitor:RemoveList(1, 2, 3) expect(oneRan).toBe(true) expect(twoRan).toBe(true) expect(threeRan).toBe(true) end) end) describe("Janitor.Get", function() it("should return the value iff it exists", function() local janitor = Janitor.new() janitor:Add(NoOperation, true, "Function") expect(janitor:Get("Function")).toBe(NoOperation) janitor:Destroy() end) it("should return void iff the value doesn't exist", function() local janitor = Janitor.new() expect(janitor:Get("Function")).toBeUndefined() janitor:Destroy() end) end) describe("Janitor.Cleanup", function() it("should cleanup everything", function() local janitor = Janitor.new() local totalRemoved = 0 local functionsToAdd = 500 for _ = 1, functionsToAdd do janitor:Add(function() totalRemoved += 1 end, true) end janitor:Cleanup() expect(totalRemoved).toBe(functionsToAdd) for _ = 1, functionsToAdd do janitor:Add(function() totalRemoved += 1 end, true) end janitor:Cleanup() expect(totalRemoved).toBe(functionsToAdd * 2) end) it("should be unique", function() local janitor = Janitor.new() local janitor2 = Janitor.new() local totalRemoved = 0 local functionsToAdd = 500 expect(janitor.CurrentlyCleaning).toBe(false) expect(janitor2.CurrentlyCleaning).toBe(false) local hasWaitCompleted = false for index = 1, functionsToAdd do if index == functionsToAdd then janitor:Add(function() totalRemoved += 1 task.wait(1) hasWaitCompleted = true end, true) else janitor:Add(function() totalRemoved += 1 end, true) end end task.spawn(function() janitor:Cleanup() end) task.wait() expect(janitor.CurrentlyCleaning).toBe(true) expect(janitor2.CurrentlyCleaning).toBe(false) expect(AwaitCondition(function() return hasWaitCompleted end, 5)).toBe(true) expect(totalRemoved).toBe(functionsToAdd) end) end) describe("Janitor.Destroy", function() it("should cleanup everything", function() local janitor = Janitor.new() local totalRemoved = 0 local functionsToAdd = 500 for _ = 1, functionsToAdd do janitor:Add(function() totalRemoved += 1 end, true) end janitor:Destroy() expect(totalRemoved).toBe(functionsToAdd) end) it("should render the Janitor unusable", function() local janitor = Janitor.new() janitor:Destroy() expect(function() janitor:Add(NoOperation, true) end).toBeTruthy() end) end) describe("Janitor.LinkToInstance", function() it("should link to an Instance", function() local janitor = Janitor.new() local part = janitor:Add(Instance.new("Part"), "Destroy") part.Parent = ReplicatedStorage expect(function() janitor:LinkToInstance(part) end).never.toThrow() janitor:Destroy() end) it("should cleanup once the Instance is destroyed", function() local janitor = Janitor.new() local wasCleaned = false local part = Instance.new("Part") part.Parent = Workspace janitor:Add(function() wasCleaned = true end, true) janitor:LinkToInstance(part) part:Destroy() task.wait(0.1) expect(wasCleaned).toBe(true) janitor:Destroy() end) it("should work if the Instance is parented to nil when started", function() local janitor = Janitor.new() local wasCleaned = false local part = Instance.new("Part") janitor:Add(function() wasCleaned = true end, true) janitor:LinkToInstance(part) part.Parent = Workspace part:Destroy() expect(AwaitCondition(function() return wasCleaned end, 1)).toBe(true) janitor:Destroy() end) it("should work if the Instance is parented to nil", function() local janitor = Janitor.new() local wsCleaned = false local part = Instance.new("Part") janitor:Add(function() wsCleaned = true end, true) janitor:LinkToInstance(part) part:Destroy() expect(AwaitCondition(function() return wsCleaned end, 1)).toBe(true) janitor:Destroy() end) it("shouldn't run if the Instance is removed or parented to nil", function() local janitor = Janitor.new() local part = Instance.new("Part") part.Parent = ReplicatedStorage janitor:Add(NoOperation, true, "Function") janitor:LinkToInstance(part) part.Parent = nil expect(janitor:Get("Function")).toBe(NoOperation) part.Parent = ReplicatedStorage expect(janitor:Get("Function")).toBe(NoOperation) part:Destroy() task.wait(0.1) expect(function() janitor:Destroy() end).never.toThrow() end) end) return false
3,712
howmanysmall/Janitor
howmanysmall-Janitor-47acf39/src/jest.config.luau
type Serialize = ( value: unknown, config: unknown, indentation: number, depth: number, refs: unknown, printer: Serialize ) -> string type Serializer = { serialize: Serialize, test: (value: unknown) -> boolean, } type JestConfiguration = { clearmocks: boolean?, displayName: nil | string | { name: string, color: string, }, projects: {Instance}?, rootDir: Instance?, setupFiles: {ModuleScript}?, setupFilesAfterEnv: {ModuleScript}?, slowTestThreshold: number?, snapshotFormat: { printInstanceDefaults: boolean?, callToJSON: boolean?, escapeRegex: boolean?, escapeString: boolean?, highlight: boolean?, indent: number?, maxDepth: number?, maxWidth: number?, min: boolean?, printBasicPrototype: boolean?, printFunctionName: boolean?, theme: {[string]: string}?, }?, snapshotSerializers: {Serializer}?, testFailureExitCode: number?, testMatch: {string}?, testPathIgnorePatterns: {string}?, testRegex: {{string} | string}?, testTimeout: number?, verbose: boolean?, } local JestConfiguration: JestConfiguration = { displayName = "Janitor"; testMatch = {"**/*.test"}; } return JestConfiguration
296
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/array.luau
local channel_state = require("../process/channel_state") local types = require("../types") --[[ Create a new array with the given dataTypeInterface ]] @native local function array<T>(value_ty: types.DataType<T>): types.DataType<{ T }> local val_write = value_ty.write local val_read = value_ty.read return { __T = nil :: T, read = @native function(buff: buffer, cursor: number) local array_length = buffer.readu16(buff, cursor) local array_cursor = cursor + 2 local array = table.create(array_length) for i = 1, array_length do local item, length = val_read(buff, array_cursor) array[i] = item array_cursor += length end return array, array_cursor - cursor end, write = @native function(value: any) local length = #value buffer.writeu16(channel_state.buff, channel_state.cursor, length) -- numeric iteration is about 2x faster than generic iteration for i = 1, length do val_write(value[i]) end end, } end return array
252
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/bool.luau
local types = require("../types") local bool_modifier = { [1] = true, [0] = false, } local bool_modifier2 = { [true] = 1, [false] = 0, } local bool_data_type = { __T = (nil :: any) :: boolean, --[[ 1 = true 0 = false Write and read based off a uint8 ]] read = @native function(b: buffer, cursor: number) return bool_modifier[buffer.readu8(b, cursor)], 1 end, length = 1, write = @native function(value) buffer.writeu8(bool_modifier2[value]) end, } @native local function bool(): types.DataType<boolean> return bool_data_type end return bool
172
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/buff.luau
local types = require("../types") local buff = { read = @native function(b: buffer, cursor: number) local length = buffer.readu16(b, cursor) local freshBuffer = buffer.create(length) -- copy the data from the main buffer to the new buffer with an offset of 2 because of length buffer.copy(freshBuffer, 0, b, cursor + 2, length) return freshBuffer, length + 2 end, write = @native function(data: buffer) local length = buffer.len(data) writeu16(length) dyn_alloc(length) -- write the length of the buffer, then the buffer itself writecopy(data) end, } return @native function(): types.DataType<buffer> return buff end
167
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/cframe.luau
local types = require("../types") local cframe: types.DataType<CFrame> = { __T = ... :: CFrame, read = @native function(b: buffer, cursor: number) local x = buffer.readf32(b, cursor) local y = buffer.readf32(b, cursor + 4) local z = buffer.readf32(b, cursor + 8) local rx = buffer.readf32(b, cursor + 12) local ry = buffer.readf32(b, cursor + 16) local rz = buffer.readf32(b, cursor + 20) return CFrame.new(x, y, z) * CFrame.Angles(rx, ry, rz), 24 end, write = @native function(value: CFrame) local x, y, z = value.X, value.Y, value.Z local rx, ry, rz = value:ToEulerAnglesXYZ() -- Math done, write it now alloc(24) writef32NoAlloc(x) writef32NoAlloc(y) writef32NoAlloc(z) writef32NoAlloc(rx) writef32NoAlloc(ry) writef32NoAlloc(rz) end, } return @native function(): types.DataType<CFrame> return cframe end
282
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/color3.luau
local types = require("../types") local color3 = { __T = ... :: Color3, write = @native function(input: Color3) alloc(3) uint8NoAlloc(input.R * 255) uint8NoAlloc(input.G * 255) uint8NoAlloc(input.B * 255) end, read = @native function(b: buffer, cursor: number) return Color3.fromRGB( buffer.readu8(b, cursor), buffer.readu8(b, cursor + 1), buffer.readu8(b, cursor + 2) ), 3 end, length = 3, } return @native function(): types.DataType<Color3> return color3 end
156
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/float32.luau
local types = require("../types") local float32: types.DataType<number> = { __T = ... :: number, write = f32, read = @native function(b: buffer, cursor: number) return buffer.readf32(b, cursor), 4 end, } return @native function(): types.DataType<number> return float32 end
74
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/float64.luau
local types = require("../types") local float64: types.DataType<number> = { __T = ... :: number, write = writef64, read = @native function(b: buffer, cursor: number) return buffer.readf64(b, cursor), 8 end, } return @native function(): types.DataType<number> return float64 end
75
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/inst.luau
local types = require("../types") return @native function(): types.DataType<Instance?> return { write = @native function(value) alloc(1) writeReference(value) end, read = @native function(b: buffer, cursor: number) local refs = readRefs.get() if not refs then return nil, 1 end local ref = refs[buffer.readu8(b, cursor)] if typeof(ref) == "Instance" then return ref, 1 else return nil, 1 end end, } end
131
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/int16.luau
local types = require("../types") local int16 = { write = writei16, read = @native function(b: buffer, cursor: number) return buffer.readi16(b, cursor), 2 end, } return @native function(): types.DataType<number> return int16 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/int32.luau
local types = require("../types") local int32 = { write = writei32, read = @native function(b: buffer, cursor: number) return buffer.readi32(b, cursor), 4 end, } return @native function(): types.DataType<number> return int32 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/int8.luau
local types = require("../types") local int8 = { write = writei8, read = @native function(b: buffer, cursor: number) return buffer.readi8(b, cursor), 1 end, } return @native function(): types.DataType<number> return int8 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/map.luau
local types = require("../types") @native local function map( keyType: types.DataType<any>, valueType: types.DataType<any> ): types.DataType<{ [any]: any }> -- Cache these functions to avoid the overhead of the index local key_write = keyType.write local value_write = valueType.write return { read = @native function(b: buffer, cursor: number) local map = {} local mapCursor = cursor -- Read map length local mapLength = buffer.readu16(b, mapCursor) mapCursor += 2 for _ = 1, mapLength do -- read key/value pairs and add them to the map local key, keyLength = keyType.read(b, mapCursor) mapCursor += keyLength local value, valueLength = valueType.read(b, mapCursor) mapCursor += valueLength map[key] = value end -- Return the map, alongside length, because mapCursor - cursor = size return map, mapCursor - cursor end, write = @native function(map: any) local count = 0 for _ in map do count += 1 end -- Write length writeu16(count) for k, v in map do -- Write key/value pairs key_write(k) value_write(v) end end, } end return map
314
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/nothing.luau
local types = require("../types") local nothing = { write = @native function() end, read = @native function() return nil, 0 end, } return @native function(): types.DataType<nil> return nothing end
50
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/optional.luau
local types = require("../types") @native local function optional<T>(value_type: types.DataType<T>): types.DataType<T?> local value_read = value_type.read local value_write = value_type.write return { --[[ first byte is a boolean, if it's true, the next bytes are the value of valueType if it's false, its length of 1 cuz only 1 boolean ]] read = @native function(b: buffer, cursor: number) if buffer.readu8(b, cursor) == 0 then -- doesn't exist return nil, 1 else -- exists, read the value local item, length = value_read(b, cursor + 1) return item, length + 1 end end, write = @native function(value: any) local exists = value ~= nil writebool(exists) if exists then value_write(value) end end, } end return optional
221
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/string.luau
local types = require("../types") local str = { -- 2 bytes for the length, then the string read = @native function(b: buffer, cursor: number) local length = buffer.readu16(b, cursor) return buffer.readstring(b, cursor + 2, length), length + 2 end, write = @native function(data: string) local length = string.len(data) writeu16(length) dyn_alloc(length) writestring(data) end, } return @native function(): types.DataType<string> return str end
122
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/struct.luau
local types = require("../types") type structData = { [string]: number, } return function<T, V>(input: T & { [string]: types.DataType<V>, }): types.DataType<T> local index_value_type_pairs: { [number]: types.DataType<any>, } = {} local index_key_pairs: { [number]: string } = {} local count = 0 for key in input :: any do count += 1 -- Store the index-value pairs and the index-key pairs as a shortcut for serializing n all that index_value_type_pairs[count] = input[key] index_key_pairs[count] = key end return { __T = nil :: T, read = @native function(b, cursor) local constructed = table.clone(input) local struct_cursor = cursor for index, value_type in index_value_type_pairs do local value, length = value_type.read(b, struct_cursor) constructed[index_key_pairs[index]] = value struct_cursor += length end return constructed, struct_cursor - cursor end, write = @native function(struct_value) for index, value_type in index_value_type_pairs do value_type.write(struct_value[index_key_pairs[index]]) end end, } end
276
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/uint16.luau
local types = require("../types") local uint16 = { write = writeu16, read = @native function(b: buffer, cursor: number) return buffer.readu16(b, cursor), 2 end, } return @native function(): types.DataType<number> return uint16 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/uint32.luau
local types = require("../types") local uint32 = { write = writeu32, read = @native function(b: buffer, cursor: number) return buffer.readu32(b, cursor), 4 end, } return @native function(): types.DataType<number> return uint32 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/uint8.luau
local types = require("../types") local uint8 = { write = writeu8, read = @native function(b: buffer, cursor: number) return buffer.readu8(b, cursor), 1 end, } return @native function(): types.DataType<number> return uint8 end
62
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/unknown.luau
local read_refs = require("../process/readRefs") local types = require("../types") @native local function unknown(): types.DataType<unknown> return { write = @native function(value: unknown) alloc(1) writeReference(value) end, read = @native function(b: buffer, cursor: number) local refs = read_refs.get() if not refs then return nil, 1 end return refs[buffer.readu8(b, cursor)], 1 end, } end return unknown
118
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/vec2.luau
local types = require("../types") local vec2 = { --[[ 2 float32s, one for X, one for Y ]] read = @native function(b: buffer, cursor: number) return Vector2.new(buffer.readf32(b, cursor), buffer.readf32(b, cursor + 4)), 8 end, write = @native function(value: Vector2) buffer.writef32(0, 0, value.X) buffer.writef32(0, 0, value.Y) end, } return @native function(): types.DataType<Vector2> return vec2 end
131
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/data_types/vec3.luau
local types = require("../types") local vec3 = { __T = ... :: vector, read = @native function(b: buffer, cursor: number) return vector.create( buffer.readf32(b, cursor), buffer.readf32(b, cursor + 4), buffer.readf32(b, cursor + 8) ), 12 end, write = @native function(value: vector) buffer.writef32(value.x) buffer.writef32(value.y) buffer.writef32(value.z) end, length = 12, } return @native function(): types.DataType<vector> return vec3 end
136
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/init.luau
local RunService = game:GetService("RunService") local array = require("@self/data_types/array") local bool = require("@self/data_types/bool") local buff = require("@self/data_types/buff") local cframe = require("@self/data_types/cframe") local client = require("@self/process/client") local define_packet = require("@self/packets/define_packet") local float32 = require("@self/data_types/float32") local float64 = require("@self/data_types/float64") local inst = require("@self/data_types/inst") local int16 = require("@self/data_types/int16") local int32 = require("@self/data_types/int32") local int8 = require("@self/data_types/int8") local map = require("@self/data_types/map") local nothing = require("@self/data_types/nothing") local optional = require("@self/data_types/optional") local server = require("@self/process/server") local string = require("@self/data_types/string") local struct = require("@self/data_types/struct") local uint16 = require("@self/data_types/uint16") local uint32 = require("@self/data_types/uint32") local uint8 = require("@self/data_types/uint8") local unknown = require("@self/data_types/unknown") local vec2 = require("@self/data_types/vec2") local vec3 = require("@self/data_types/vec3") if RunService:IsServer() then server.start() else client.init() end return table.freeze({ define_packet = define_packet, t = { array = array, bool = bool(), optional = optional, uint8 = uint8(), uint16 = uint16(), uint32 = uint32(), int8 = int8(), int16 = int16(), int32 = int32(), float32 = float32(), float64 = float64(), cframe = cframe(), string = string(), vec2 = vec2(), vec3 = vec3(), buff = buff(), struct = struct, map = map, inst = inst(), unknown = unknown(), nothing = nothing(), }, })
452
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/packets/packet.luau
--!native --!optimize 2 local Players = game:GetService("Players") local RunService = game:GetService("RunService") local types = require("../types") local client = require("../process/client") local server = require("../process/server") local run_context: "server" | "client" = if RunService:IsServer() then "server" else "client" --[[ We use closures here instead of metatables for performance It's just faster to use closures than metatables ]] return@native function(props: types.PacketProps<types.DataType<any>>, id: number) -- Basic properties: reliability type, "unique" which is used to get the packet ID, and set up listeners local reliabilityType = props.reliability or "reliable" local listeners = {} local serverSendFunction: (player: Player, id: number, writer: (value: any) -> (), data: any) -> () = if reliabilityType == "reliable" then server.sendPlayerReliable else server.sendPlayerUnreliable local serverSendAllFunction: (id: number, writer: (value: any) -> (), data: any) -> () = if reliabilityType == "reliable" then server.sendAllReliable else server.sendAllUnreliable local clientSendFunction: (id: number, writer: (value: any) -> (), data: any) -> () = if reliabilityType == "reliable" then client.send_reliable else client.send_unreliable -- shorcut to avoid indexxing local writer = props.value.write local exported = {} -- RunContext error checking that doesn't have performance drawbacks setmetatable(exported, { __index =@native function(index) if (index == "sendTo" or index == "sendToAllExcept" or index == "sendToAll") and run_context == "client" then error("You cannot use sendTo, sendToAllExcept, or sendToAll on the client") elseif index == "send" and run_context == "server" then error("You cannot use send on the server") end end, }) -- exposed for the reader file exported.reader = props.value.read if run_context == "server" then function exported.sendToList(data, players: { Player }) for _, player in players do serverSendFunction(player, id, writer, data) end end function exported.sendTo(data, player: Player) serverSendFunction(player, id, writer, data) end function exported.sendToAllExcept(data, except: Player) for _, player: Player in Players:GetPlayers() do if player ~= except then serverSendFunction(player, id, writer, data) end end end function exported.sendToAll(data) serverSendAllFunction(id, writer, data) end elseif run_context == "client" then function exported.send(data) clientSendFunction(id, writer, data) end end function exported.wait() -- define it up here so we can use it to disconnect local index: number local runningThread = coroutine.running() table.insert(listeners,@native function(data, player) task.spawn(runningThread, data, player) -- Disconnects the listener table.remove(listeners, index) end) -- we connected, time to set the index for when we need to disconnect. index = #listeners -- the listener will resume the thread return coroutine.yield() end function exported.listen(callback) table.insert(listeners, callback) end function exported.getListeners() return listeners end return exported end
820
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/process/channel_state.luau
local types = require("../types") local channel_state: types.ChannelState = { buff = buffer.create(0), ref_map = {}, cursor = 0, } return channel_state
37
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/process/client.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local read = require("./read") local types = require("../types") @native local function onClientEvent(receivedBuffer, ref) read(receivedBuffer, ref) end -- Shared with: src/process/server.luau (Infeasible to split this into another file) @native local function create(): types.ChannelState return { cursor = 0, size = 256, references = {}, buff = buffer.create(256), } end @native local function dump(channel: types.ChannelState): (buffer, { unknown }?) local cursor = channel.cursor local dump_buffer = buffer.create(cursor) buffer.copy(dump_buffer, 0, channel.buff, 0, cursor) return dump_buffer, if #channel.references > 0 then channel.references else nil end -- No longer shared local reliable: types.ChannelState = create() local unreliable: types.ChannelState = create() local client = {} function client.send_reliable<T>(id: number, data: T) reliable = writePacket(reliable, id, writer, data) end function client.send_unreliable(id: number, writer: (value: any) -> (), data: { [string]: any }) unreliable = writePacket(unreliable, id, writer, data) end function client.init() local reliableRemote = ReplicatedStorage:WaitForChild("ByteNetReliable") reliableRemote.OnClientEvent:Connect(onClientEvent) local unreliableRemote = ReplicatedStorage:WaitForChild("ByteNetUnreliable") unreliableRemote.OnClientEvent:Connect(onClientEvent) RunService.Heartbeat:Connect(function() -- Again, checking if there's anything in the channel before we send it. if reliable.cursor > 0 then local b, r = dump(reliable) reliableRemote:FireServer(b, r) -- effectively clears the channel reliable.cursor = 0 table.clear(reliable.references) end if unreliable.cursor > 0 then local b, r = dump(unreliable) unreliableRemote:FireServer(b, r) unreliable.cursor = 0 table.clear(unreliable.references) end end) end return client
502
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/process/read.luau
--!optimize 2 --!native local packetIDs = require("../a") local readRefs = require("./readRefs") local ref = packetIDs.ref() local free_thread: thread? @native local function function_passer(fn, ...) local aquiredThread = free_thread free_thread = nil fn(...) free_thread = aquiredThread end @native local function yielder() while true do function_passer(coroutine.yield()) end end @native local function run_listener(fn, ...) free_thread = task.spawn(free_thread or task.spawn(coroutine.create(yielder)), fn, ...) end @native local function read(incoming_buff: buffer, references: { [number]: unknown }?, player: Player?) local length = buffer.len(incoming_buff) local read_cursor = 0 readRefs.set(references) while read_cursor < length do local packet = ref[buffer.readu8(incoming_buff, read_cursor)] read_cursor += 1 local value, value_len = packet.reader(incoming_buff, read_cursor) read_cursor += value_len for _, listener in packet.getListeners() do run_listener(listener, value, player) end end end return read
264
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/process/server.luau
--!native local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local buffer_writer = require("./buffer_writer") local read = require("./read") local types = require("../types") local write_packet = buffer_writer.write_packet -- All ChannelState is set to nil upon being sent which is why these are all optionals local per_player_reliable: { [Player]: types.ChannelState } = {} local per_player_unreliable: { [Player]: types.ChannelState } = {} -- Shared with: src/process/client.luau (Infeasible to split this into another file) @native local function create(): types.ChannelState return { cursor = 0, size = 256, references = {}, buff = buffer.create(256), } end @native local function dump(channel: types.ChannelState): (buffer, { unknown }?) local cursor = channel.cursor local dump_buff = buffer.create(cursor) buffer.copy(dump_buff, 0, channel.buff, 0, cursor) return dump_buff, if #channel.references > 0 then channel.references else nil end -- No longer shared local globalReliable: types.ChannelState = create() local globalUnreliable: types.ChannelState = create() -- TODO handle invalid data better @native local function on_server_event(player: Player, data, references) -- Only accept buffer data if not (typeof(data) == "buffer") then return end read(data, references, player) end @native local function player_added(player) if not per_player_reliable[player] then per_player_reliable[player] = create() end if not per_player_unreliable[player] then per_player_unreliable[player] = create() end end local server = {} function server.sendAllReliable(id: number, writer: (value: any) -> (), data: { [string]: any }) globalReliable = write_packet(globalReliable, id, writer, data) end function server.sendAllUnreliable(id: number, writer: (value: any) -> (), data: { [string]: any }) globalUnreliable = write_packet(globalUnreliable, id, writer, data) end function server.sendPlayerReliable( player: Player, id: number, writer: (value: any) -> (), data: { [string]: any } ) per_player_reliable[player] = write_packet(per_player_reliable[player], id, writer, data) end function server.sendPlayerUnreliable( player: Player, id: number, writer: (value: any) -> (), data: { [string]: any } ) per_player_unreliable[player] = write_packet(per_player_unreliable[player], id, writer, data) end function server.start() local reliableRemote = Instance.new("RemoteEvent") reliableRemote.Name = "ByteNetReliable" reliableRemote.OnServerEvent:Connect(on_server_event) reliableRemote.Parent = ReplicatedStorage local unreliableRemote = Instance.new("UnreliableRemoteEvent") unreliableRemote.Name = "ByteNetUnreliable" unreliableRemote.OnServerEvent:Connect(on_server_event) unreliableRemote.Parent = ReplicatedStorage for _, player in Players:GetPlayers() do player_added(player) end Players.PlayerAdded:Connect(player_added) RunService.Heartbeat:Connect(function() -- Check if the channel has anything before trying to send it if globalReliable.cursor > 0 then local b, r = dump(globalReliable) reliableRemote:FireAllClients(b, r) globalReliable.cursor = 0 table.clear(globalReliable.references) end if globalUnreliable.cursor > 0 then local b, r = dump(globalUnreliable) unreliableRemote:FireAllClients(b, r) globalUnreliable.cursor = 0 table.clear(globalUnreliable.references) end for _, player in Players:GetPlayers() do if per_player_reliable[player].cursor > 0 then local b, r = dump(per_player_reliable[player]) reliableRemote:FireClient(player, b, r) per_player_reliable[player].cursor = 0 table.clear(per_player_reliable[player].references) end if per_player_unreliable[player].cursor > 0 then local b, r = dump(per_player_unreliable[player]) unreliableRemote:FireClient(player, b, r) per_player_unreliable[player].cursor = 0 table.clear(per_player_unreliable[player].references) end end end) end return server
1,029
ffrostfall/ByteNet
ffrostfall-ByteNet-fbdb156/src/types.luau
export type ChannelState = { buff: buffer, cursor: number, ref_map: { [number]: unknown }, } export type PacketProps<T> = { value: T, reliability: ("Reliable" | "Unreliable")?, max_per_frame: number?, } export type DataType<T> = { read __T: T, write: (value: T) -> (), read: (b: buffer, cursor: number) -> (T, number), read length: number?, } type Packet<T> = { send_to_all: (data: T) -> (), send_to: (data: T, target: Player) -> (), send_to_list: (data: T, targets: { Player }) -> (), send_to_all_except: (data: T, exception: Player) -> (), wait: () -> T, send: (data: T, target: Player?) -> (), listen: (callback: (data: T, player: Player?) -> ()) -> (), } export type function ValueFromDataType(data_type: type) return data_type:readproperty(types.singleton("__T")) end return nil
234
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/Constants.luau
--[=[ @class Constants @private Module containing constant values used throughout the Lyra library. ]=] -- Estimated bytes reserved within the DataStore value for Lyra's internal metadata -- (like appliedMigrations, orphanedFiles list, and File object overhead when sharded). -- This ensures that the actual user data shards stay safely within the DataStore limits. local INTERNAL_SPACE_RESERVE_BYTES = 10_000 --[=[ @interface Constants @within Constants .RECORD_SCOPE "lyra/records" -- Scope prefix used for keys storing the main DataStoreRecord objects. .TX_SCOPE "lyra/tx" -- Scope prefix used for keys storing transaction status markers in a DataStore. .SHARD_SCOPE "lyra/shards" -- Scope prefix used for keys storing data shards in a DataStore. .LOCK_SCOPE "lyra/locks" -- Scope prefix used for keys storing lock information in a MemoryStore HashMap. .MAX_CHUNK_SIZE number -- Maximum size (in bytes) for a single data shard stored in DataStore. Derived from the Roblox DataStore value limit (4MB) minus a reserved amount (INTERNAL_SPACE_RESERVE_BYTES) for Lyra's internal metadata within the main record. .LOCK_REFRESH_INTERVAL_SECONDS number -- How often (in seconds) a held lock should be refreshed in MemoryStore to prevent it from expiring while still actively being used. Should be significantly shorter than LOCK_DURATION_SECONDS. .LOCK_DURATION_SECONDS number -- The initial time-to-live (TTL) duration (in seconds) for a lock acquired in MemoryStore. If the lock isn't refreshed within this time, it will automatically expire. Must be longer than LOCK_REFRESH_INTERVAL_SECONDS to allow time for refreshes. .AUTOSAVE_INTERVAL_SECONDS number -- How often (in seconds) the automatic saving mechanism should attempt to save dirty session data. ]=] local Constants = { RECORD_SCOPE = "lyra/records", TX_SCOPE = "lyra/tx", SHARD_SCOPE = "lyra/shards", LOCK_SCOPE = "lyra/locks", MAX_CHUNK_SIZE = 4_000_000 - INTERNAL_SPACE_RESERVE_BYTES, LOCK_REFRESH_INTERVAL_SECONDS = 60, LOCK_DURATION_SECONDS = 90, AUTOSAVE_INTERVAL_SECONDS = 5 * 60, -- 5 minutes } return Constants
489
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/Log.luau
--[=[ @class Log @private Provides a structured logging implementation for the Lyra library. **Design:** - **Callback-based:** Instead of directly printing or sending logs, this module uses a callback function (`logCallback`) provided during logger creation. This allows the consuming application to decide how and where log messages are routed (e.g., print to console, send to an external service, store in memory). - **Structured Context:** Log messages include a `context` table. Loggers can be `extend`ed with additional context fields, which are automatically merged into every subsequent log message created by that logger instance or its descendants. This helps provide detailed, structured information for debugging and monitoring. - **Log Levels:** Supports standard log levels (`fatal`, `error`, `warn`, `info`, `debug`, `trace`). A global log level can be set using `Log.setLevel` to filter out messages below the desired severity. **Usage:** ```lua local Log = require(script.Parent.Log) -- Set the global minimum log level (optional, defaults to "info") Log.setLevel("debug") -- Create a logger instance with a callback local myLogger = Log.createLogger(function(logMessage) print(`[{logMessage.level}] {logMessage.message}`, logMessage.context) end, { initialContext = "value" }) -- Log messages myLogger:log("info", "User logged in", { userId = 123 }) -- Create a logger with extended context local sessionLogger = myLogger:extend({ sessionId = "abc" }) sessionLogger:log("debug", "Session data loaded") -- Output will include { initialContext = "value", sessionId = "abc", userId = 123 } -- if logged via myLogger, or { initialContext = "value", sessionId = "abc" } -- if logged via sessionLogger. ``` ]=] --[=[ Represents the different log levels available for logging messages. @type LogLevel "fatal" | "error" | "warn" | "info" | "debug" | "trace" @tag enum @within Log ]=] export type LogLevel = "fatal" | "error" | "warn" | "info" | "debug" | "trace" --[=[ Represents a log message sent to the logger's callback function. @interface LogMessage @within Log .message string -- The main content of the log message. .level LogLevel -- The severity level of the message. .context { [string]: any }? -- Optional table containing additional structured context. ]=] export type LogMessage = { message: string, level: LogLevel, context: { [string]: any }?, } export type LoggerImpl = { __index: LoggerImpl, log: (self: Logger, level: LogLevel, message: string, context: { [string]: any }?) -> (), extend: (self: Logger, context: { [string]: any }) -> Logger, } export type LoggerProps = { _logCallback: (logMessage: LogMessage) -> (), _context: { [string]: any }, } export type Logger = typeof(setmetatable({} :: LoggerProps, {} :: LoggerImpl)) -- Ordered list of log levels from most severe to least severe. local levels = { "fatal", "error", "warn", "info", "debug", "trace", } -- The main Log module table, holds global settings like the current log level. local Log = { level = "info", -- Default global log level. } --[=[ Sets the global minimum log level. Messages with a severity lower than this level will be ignored by all loggers. @within Log @param level LogLevel -- The minimum log level to allow. @error string -- Throws an error if the provided level is invalid. ]=] function Log.setLevel(level: LogLevel) if table.find(levels, level) == nil then error(`Invalid log level: '{level}'`) end Log.level = level end -- Metatable implementing the Logger methods. (Internal) local Logger: LoggerImpl = {} :: LoggerImpl Logger.__index = Logger --[=[ Logs a message if its level is at or above the globally set log level. Merges the provided `context` table with the logger's persistent context before calling the configured `_logCallback`. @within Log @param level LogLevel -- The severity level of the message. @param message string -- The log message content. @param context { [string]: any }? -- Optional additional context specific to this log call. ]=] function Logger:log(level: LogLevel, message: string, context: { [string]: any }?) -- Filter messages based on the global log level. if table.find(levels, level) > table.find(levels, Log.level) then return end -- Merge instance context with call-specific context. local finalContext = table.clone(self._context) if context then for key, value in context do finalContext[key] = value end end -- Call the configured log callback within a protected call to catch errors. local ok, result = pcall(function() self._logCallback({ level = level, message = message, context = finalContext, }) end) if not ok then -- If the logging callback itself errors, print a warning. warn(`Error in log callback: {result}`) end end --[=[ Creates a new Logger instance that inherits the parent's callback but has an extended context. The new logger's context is a merged table containing the parent's context and the additional `context` provided here. @within Log @param context { [string]: any } -- The additional context fields to add. @return Logger -- A new Logger instance with the extended context. ]=] function Logger:extend(context: { [string]: any }): Logger -- Merge existing context with the new context. local finalContext = table.clone(self._context) for key, value in context do finalContext[key] = value end -- Create and return a new logger instance sharing the callback but with the new context. return setmetatable({ _logCallback = self._logCallback, _context = finalContext, }, Logger) end --[=[ Factory function to create a new root Logger instance. @within Log @param logCallback (logMessage: LogMessage) -> () -- The function that will be called for each log message that passes the level filter. This function receives the complete `LogMessage` object including merged context. @param context { [string]: any }? -- Optional initial context for this logger. @return Logger -- A new Logger instance. ]=] function Log.createLogger(logCallback: (logMessage: LogMessage) -> (), context: { [string]: any }?): Logger return setmetatable({ _logCallback = logCallback, _context = context or {}, }, Logger) end return Log
1,495
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/Migrations.luau
--[=[ @class Migrations @private Provides functionality for managing and applying data migrations. **Concept:** As data schemas evolve over time, older data stored in DataStores needs to be updated to match the new structure. This module allows defining a series of migration steps (`Types.MigrationStep`) that transform data from one version of the schema to the next. **Workflow:** 1. Define migration steps using helpers like `makeAddFieldsStep` or `makeTransformStep`. Each step must have a unique `name`. 2. Provide the list of steps to the `Store` via `StoreContext`. 3. When data is loaded (`Session:load`), the `apply` function in this module is called. 4. `apply` compares the list of all defined steps against the `appliedMigrations` list stored within the `DataStoreRecord`. 5. It executes the `apply` function of any step that hasn't been applied yet, in the order they are defined. 6. The `apply` function of each step receives the current data and returns the transformed data. 7. The names of successfully applied steps are added to the `appliedMigrations` list, which is then saved back to the `DataStoreRecord`. **Idempotency:** The system ensures migrations are idempotent (applying them multiple times has the same effect as applying them once) by checking the `appliedMigrations` list before running a step. **Error Handling:** Each step's `apply` function is executed within a `pcall` to catch errors. If a step fails, the migration process stops, and the error is propagated. ]=] local Log = require(script.Parent.Log) local Promise = require(script.Parent.Promise) local Tables = require(script.Parent.Tables) local Types = require(script.Parent.Types) --[=[ Alias for a generic data table type used in migrations. @type Data { [string]: any } @within Migrations @private ]=] type Data = { [string]: any } --[=[ Validates that the provided migration steps adhere to the expected structure. @within Migrations @param steps {Types.MigrationStep} -- The list of migration steps to validate. @error string -- Throws an error if any step is malformed. ]=] local function validate(steps: { Types.MigrationStep }) assert(typeof(steps) == "table", "steps must be a table") for _, step in steps do assert(typeof(step) == "table", "step must be a table") assert(typeof(step.name) == "string", "step.name must be a string") assert(typeof(step.apply) == "function", "step.apply must be a function") end end --[=[ Helper function to create a common type of migration step: adding new fields with default values to existing data. Uses a deep merge strategy. @within Migrations @param name string -- The unique name for this migration step. @param fields Data -- A table containing the new fields and their default values. @return Types.MigrationStep -- A migration step object. ]=] local function makeAddFieldsStep(name: string, fields: Data): Types.MigrationStep return { name = name, apply = function(data) -- Merges the default `fields` into the existing `data`. -- Existing keys in `data` are preserved unless they are tables themselves, -- in which case they are recursively merged. return Tables.mergeDeep(fields, data) end, } end --[=[ Helper function to create a migration step that applies a custom transformation function to the data. @within Migrations @param name string -- The unique name for this migration step. @param transformFunc (currentValue: Data) -> Data -- The function that takes the current data and returns the transformed data. @return Types.MigrationStep -- A migration step object. ]=] local function makeTransformStep(name: string, transformFunc: (currentValue: Data) -> Data): Types.MigrationStep return { name = name, apply = transformFunc, } end --[=[ Parameters for the `apply` function. @interface ApplyParams @within Migrations .logger Log.Logger -- Logger instance for logging migration progress and errors. .data Data -- The current data loaded from the DataStore record's File. .steps {Types.MigrationStep} -- The list of all defined migration steps for the store. .appliedMigrations {string} -- The list of names of migration steps already applied to this specific data record, loaded from the DataStoreRecord. ]=] export type ApplyParams = { logger: Log.Logger, data: Data, steps: { Types.MigrationStep }, appliedMigrations: { string }, } --[=[ Result returned by the `apply` function upon successful completion. @interface ApplyResult @within Migrations .data Data -- The potentially modified data after applying necessary migration steps. .appliedMigrations {string} -- The updated list of applied migration names, including any newly applied steps. This should be saved back to the DataStoreRecord. ]=] export type ApplyResult = { data: Data, appliedMigrations: { string }, } --[=[ Applies pending migration steps to the data. Iterates through the defined `steps` and applies any step whose name is not present in the `appliedMigrations` list. Ensures idempotency and uses `pcall` for safe execution of each step's `apply` function. @within Migrations @param params ApplyParams -- The parameters for applying migrations. @return Promise<ApplyResult> -- A Promise that resolves with the updated data and the new list of applied migration names. @error string -- Rejects if any migration step fails during `pcall`. ]=] local function apply(params: ApplyParams): Promise.TPromise<ApplyResult> local logger = params.logger local currentData = params.data -- Clone the list to avoid modifying the original list passed in params directly within this function scope. local appliedMigrations = table.clone(params.appliedMigrations) -- Create a set for quick lookup of already applied migrations. local appliedSet = {} for _, name in appliedMigrations do appliedSet[name] = true end return Promise.new(function(resolve, reject) for _, step in params.steps do -- Idempotency Check: Only apply if the step name is not in the applied set. if not appliedSet[step.name] then logger:log("trace", "applying migration step", { stepName = step.name }) -- Deep copy the data before applying the step to avoid modifying the original -- `currentData` reference in case of an error within `step.apply`. -- TODO: Do we actually care about atomicity here? This might be a performance hit. local staged = Tables.copyDeep(currentData) -- Safely execute the migration step's apply function. local ok, result = pcall(step.apply, staged) if not ok then -- If pcall failed, log the error and reject the promise. logger:log("error", "failed to apply migration step", { stepName = step.name, error = result }) return reject(`Failed migration step '{step.name}': {result}`) end -- If pcall succeeded, update currentData with the result. -- Deep copy again to ensure `currentData` holds a distinct copy for the next step. -- TODO: We should probably just warn about not modifying the data after returning - this is expensive. currentData = Tables.copyDeep(result) -- Add the step name to the list of applied migrations for this record. table.insert(appliedMigrations, step.name) -- Also update the lookup set for the next iteration. appliedSet[step.name] = true end end -- All applicable steps applied successfully. Resolve with the final data and updated list. return resolve({ data = currentData, appliedMigrations = appliedMigrations, }) end) end --[=[ Utility function to extract just the names from a list of migration steps. @within Migrations @param migrations {Types.MigrationStep} -- The list of migration steps. @return {string} -- A list containing only the names of the migration steps. ]=] local function getStepNames(migrations: { Types.MigrationStep }): { string } local names = {} for _, step in migrations do table.insert(names, step.name) end return names end return { makeAddFieldsStep = makeAddFieldsStep, makeTransformStep = makeTransformStep, validate = validate, apply = apply, getStepNames = getStepNames, }
1,880
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/PlayerStore.luau
--[=[ A PlayerStore wraps a regular Store to provide a more convenient API for working with Player data. It automatically converts Players to UserId keys and handles player kicks on data errors. ```lua local playerStore = PlayerStore.create({ name = "PlayerData", template = { coins = 0, items = {}, }, schema = function(data) return typeof(data.coins) == "number" and typeof(data.items) == "table", "Invalid data format" end, }) -- Load data when player joins Players.PlayerAdded:Connect(function(player) playerStore:loadAsync(player) end) -- Unload data when player leaves Players.PlayerRemoving:Connect(function(player) playerStore:unloadAsync(player) end) ``` @class PlayerStore ]=] local Players = game:GetService("Players") local Log = require(script.Parent.Log) local Promise = require(script.Parent.Promise) local Store = require(script.Parent.Store) local Types = require(script.Parent.Types) type PlayerStoreImpl<T> = { __index: PlayerStoreImpl<T>, _kickPlayer: (self: PlayerStore<T>, keyOrPlayer: string | Player, message: string) -> (), get: (self: PlayerStore<T>, player: Player) -> Promise.TPromise<T>, load: (self: PlayerStore<T>, player: Player) -> Promise.Promise, unload: (self: PlayerStore<T>, player: Player) -> Promise.Promise, update: ( self: PlayerStore<T>, player: Player, transformFunction: (data: T) -> boolean ) -> Promise.TPromise<boolean>, updateImmutable: ( self: PlayerStore<T>, player: Player, transformFunction: (data: T) -> T | false ) -> Promise.TPromise<boolean>, tx: ( self: PlayerStore<T>, players: { Player }, transformFunction: (state: { [Player]: T }) -> boolean ) -> Promise.TPromise<boolean>, txImmutable: ( self: PlayerStore<T>, players: { Player }, transformFunction: (state: { [Player]: T }) -> { [Player]: T } | false ) -> Promise.TPromise<boolean>, save: (self: PlayerStore<T>, player: Player) -> Promise.Promise, close: (self: PlayerStore<T>) -> Promise.Promise, peek: (self: PlayerStore<T>, userId: number) -> T, getAsync: (self: PlayerStore<T>, player: Player) -> T, loadAsync: (self: PlayerStore<T>, player: Player) -> (), unloadAsync: (self: PlayerStore<T>, player: Player) -> (), updateAsync: (self: PlayerStore<T>, player: Player, transformFunction: (data: T) -> boolean) -> boolean, updateImmutableAsync: ( self: PlayerStore<T>, player: Player, transformFunction: (data: T) -> T | false ) -> boolean, txAsync: ( self: PlayerStore<T>, players: { Player }, transformFunction: (state: { [Player]: T }) -> boolean ) -> (), txImmutableAsync: ( self: PlayerStore<T>, players: { Player }, transformFunction: (state: { [Player]: T }) -> { [Player]: T } | false ) -> boolean, saveAsync: (self: PlayerStore<T>, player: Player) -> (), closeAsync: (self: PlayerStore<T>) -> (), peekAsync: (self: PlayerStore<T>, userId: number) -> T, } type PlayerStoreProps<T> = { _store: Store.Store<T>, } --[=[ Configuration for creating a new Store. @interface PlayerStoreConfig .name string -- The name of the store .template T -- The template data for new keys .schema (value: any) -> (boolean, string?) -- A function to validate data .migrationSteps { MigrationStep }? -- Optional migration steps .importLegacyData ((key: string) -> any?)? -- Optional function to import legacy data .changedCallbacks { (key: string, newData: T, oldData: T?) -> () }? -- Optional callbacks for data changes .logCallback ((logMessage: LogMessage) -> ())? -- Optional callback for log messages .memoryStoreService MemoryStoreService? -- Optional MemoryStoreService instance for mocking .dataStoreService DataStoreService? -- Optional DataStoreService instance for mocking @within PlayerStore ]=] type PlayerStoreConfig<T> = { name: string, template: T, useDSSLocking: boolean?, schema: (value: any) -> (boolean, string?), migrationSteps: { Types.MigrationStep }?, importLegacyData: ((key: string) -> any?)?, changedCallbacks: { (key: string, newData: T, oldData: T?) -> () }?, logCallback: ((logMessage: Log.LogMessage) -> ())?, memoryStoreService: MemoryStoreService?, dataStoreService: DataStoreService?, } type PlayerStore<T> = typeof(setmetatable({} :: PlayerStoreProps<T>, {} :: PlayerStoreImpl<T>)) local function getUserIdKey(player: Player): string return tostring(player.UserId) end local PlayerStore: PlayerStoreImpl<any> = {} :: PlayerStoreImpl<any> PlayerStore.__index = PlayerStore --[=[ Creates a new PlayerStore with the given configuration. Configuration is similar to Store.createStore, but automatically adds player kick handling. ```lua local playerStore = PlayerStore.create({ name = "PlayerData", template = { coins = 0 }, schema = function(data) return typeof(data.coins) == "number", "coins must be a number" end, -- Optional: Runs whenever data changes changedCallbacks = { function(key, newData, oldData) print(key, "changed from", oldData.coins, "to", newData.coins) end, }, }) ``` Players will be automatically kicked with an error message if: - Their data fails to load - The DataStore lock is lost during their session @param config PlayerStoreConfig<T> -- Configuration for the store @return PlayerStore<T> @within PlayerStore ]=] local function createPlayerStore<T>(config: PlayerStoreConfig<T>): PlayerStore<T> local self: PlayerStore<T> local storeConfig: Store.StoreConfig<T> = { name = config.name, template = config.template, schema = config.schema, useDSSLocking = config.useDSSLocking, migrationSteps = config.migrationSteps, importLegacyData = config.importLegacyData, changedCallbacks = config.changedCallbacks, logCallback = config.logCallback, onLockLost = function(key: string) self:_kickPlayer(key, "DataStore lock lost, please rejoin the game.") end, memoryStoreService = config.memoryStoreService, dataStoreService = config.dataStoreService, } local store = Store.createStore(storeConfig) self = setmetatable({ _store = store }, PlayerStore) return self end --[=[ Internal helper to kick players when data errors occur. @within PlayerStore @private ]=] function PlayerStore:_kickPlayer(keyOrPlayer: string | Player, message: string): () if typeof(keyOrPlayer) ~= "string" then keyOrPlayer:Kick(message) else local player = Players:GetPlayerByUserId(tonumber(keyOrPlayer)) if player ~= nil then player:Kick(message) end end end --[=[ Gets the current data for the given player. ```lua playerStore:get(player):andThen(function(data) print(player.Name, "has", data.coins, "coins") end) ``` @error "Key not loaded" -- The player's data hasn't been loaded @error "Store is closed" -- The store has been closed @return Promise<T> -- Resolves with the player's data @within PlayerStore ]=] function PlayerStore:get(player: Player) local userIdKey = getUserIdKey(player) return self._store:get(userIdKey) end --[=[ Syntactic sugar for `playerStore:get(player):expect()`. See [PlayerStore:get] @yields ]=] function PlayerStore:getAsync(player: Player) return self:get(player):expect() end --[=[ Loads data for the given player. Must be called before using other methods. ```lua playerStore:load(player):andThen(function() print("Data loaded for", player.Name) end) ``` :::caution If loading fails, the player will be kicked from the game. ::: @error "Load already in progress" -- Another load is in progress for this player @error "Store is closed" -- The store has been closed @return Promise -- Resolves when data is loaded @within PlayerStore ]=] function PlayerStore:load(player: Player) local userIdKey = getUserIdKey(player) return self._store:load(userIdKey, { player.UserId }):catch(function(e) self:_kickPlayer(player, "DataStore load failed, please rejoin the game.") return Promise.reject(e) end) end --[=[ Syntactic sugar for `playerStore:load(player):expect()`. See [PlayerStore:load] @yields ]=] function PlayerStore:loadAsync(player: Player) return self:load(player):expect() end --[=[ Unloads data for the given player. ```lua playerStore:unload(player):andThen(function() print("Data unloaded for", player.Name) end) ``` @error "Store is closed" -- The store has been closed @return Promise<boolean> -- Resolves when the update is complete, with a boolean indicating success @within PlayerStore ]=] function PlayerStore:unload(player: Player) local userIdKey = getUserIdKey(player) return self._store:unload(userIdKey) end --[=[ Syntactic sugar for `playerStore:unload(player):expect()`. See [PlayerStore:unload] @yields ]=] function PlayerStore:unloadAsync(player: Player) return self:unload(player):expect() end --[=[ Updates data for the given player using a transform function. The transform function must return true to commit changes, or false to abort. ```lua playerStore:update(player, function(data) if data.coins < 100 then data.coins += 50 return true -- Commit changes end return false -- Don't commit changes end) ``` @error "Key not loaded" -- The player's data hasn't been loaded @error "Store is closed" -- The store has been closed @error "Schema validation failed" -- The transformed data failed schema validation @return Promise -- Resolves when the update is complete @within PlayerStore ]=] function PlayerStore:update<T>(player: Player, transformFunction: (data: T) -> boolean) local userIdKey = getUserIdKey(player) return self._store:update(userIdKey, transformFunction) end --[=[ Syntactic sugar for `playerStore:update(player, transformFunction):expect()`. See [PlayerStore:update] @yields ]=] function PlayerStore:updateAsync<T>(player: Player, transformFunction: (data: T) -> boolean) return self:update(player, transformFunction):expect() end --[=[ Updates data for the given player using a transform function that does not mutate the original data. The transform function must return the new data or false to abort. ```lua playerStore:updateImmutable(player, function(data) if data.coins < 100 then return { coins = data.coins + 50 } -- Return new data to commit changes end return false -- Don't commit changes end) ``` @error "Key not loaded" -- The player's data hasn't been loaded @error "Store is closed" -- The store has been closed @error "Schema validation failed" -- The transformed data failed schema validation @return Promise -- Resolves when the update is complete @within PlayerStore ]=] function PlayerStore:updateImmutable<T>( player: Player, transformFunction: (data: T) -> T | false ): Promise.TPromise<boolean> local userIdKey = getUserIdKey(player) return self._store:updateImmutable(userIdKey, transformFunction) end --[=[ Syntactic sugar for `playerStore:updateImmutable(player, transformFunction):expect()`. See [PlayerStore:updateImmutable] @yields ]=] function PlayerStore:updateImmutableAsync<T>(player: Player, transformFunction: (data: T) -> T | false) return self:updateImmutable(player, transformFunction):expect() end --[=[ Performs a transaction across multiple players' data atomically. All players' data must be loaded first. Either all changes apply or none do. ```lua playerStore:tx({player1, player2}, function(state) -- Transfer coins between players if state[player1].coins >= 100 then state[player1].coins -= 100 state[player2].coins += 100 return true -- Commit transaction end return false -- Abort transaction end) ``` @error "Key not loaded" -- One or more players' data hasn't been loaded @error "Store is closed" -- The store has been closed @error "Schema validation failed" -- The transformed data failed schema validation @return Promise -- Resolves with `true` if the transaction was successful, or `false` if it was aborted. Rejects on error. @within PlayerStore ]=] function PlayerStore:tx<T>( players: { Player }, transformFunction: (state: { [Player]: T }) -> boolean ): Promise.TPromise<boolean> local userIdKeys = table.create(#players) local userIdKeyToPlayer = {} for i, player in players do local key = getUserIdKey(player) userIdKeys[i] = key userIdKeyToPlayer[key] = player end local function wrapped(state: { [string]: any }): boolean local userIdState = {} for key, value in state do local player = userIdKeyToPlayer[key] userIdState[player] = value end local success = transformFunction(userIdState) if success == false then return false end for key in state do state[key] = nil end for playerVariant, value in userIdState do local stringKey = getUserIdKey(playerVariant) state[stringKey] = value end return success end return self._store:tx(userIdKeys, wrapped) end --[=[ Syntactic sugar for `playerStore:tx(players, transformFunction):expect()`. See [PlayerStore:tx] @yields ]=] function PlayerStore:txAsync<T>(players: { Player }, transformFunction: (state: { [Player]: T }) -> boolean) return self:tx(players, transformFunction):expect() end --[=[ Performs a transaction across multiple players' data atomically using immutable updates. All players' data must be loaded first. Either all changes apply or none do. ```lua playerStore:txImmutable({player1, player2}, function(state) -- Transfer coins between players if state[player1].coins >= 100 then return { [player1] = { coins = state[player1].coins - 100 }, [player2] = { coins = state[player2].coins + 100 }, } -- Commit transaction with new data end return false -- Abort transaction end) ``` @error "Key not loaded" -- One or more players' data hasn't been loaded @error "Store is closed" -- The store has been closed @error "Schema validation failed" -- The transformed data failed schema validation @return Promise -- Resolves with `true` if the transaction was successful, or `false` if it was aborted. Rejects on error. @within PlayerStore ]=] function PlayerStore:txImmutable<T>( players: { Player }, transformFunction: (state: { [Player]: T }) -> { [Player]: T } | false ): Promise.TPromise<boolean> local userIdKeys = table.create(#players) local userIdKeyToPlayer = {} for i, player in players do local key = getUserIdKey(player) userIdKeys[i] = key userIdKeyToPlayer[key] = player end local function wrapped(state: { [string]: any }): { [string]: any } | false local userIdState = {} for key, value in state do local player = userIdKeyToPlayer[key] userIdState[player] = value end local newData = transformFunction(userIdState) if newData == false then return false end for key in state do state[key] = nil end for playerVariant, value in newData :: { [Player]: T } do local stringKey = getUserIdKey(playerVariant) state[stringKey] = value end return state end return self._store:txImmutable(userIdKeys, wrapped) end --[=[ Syntactic sugar for `playerStore:txImmutable(players, transformFunction):expect()`. See [PlayerStore:txImmutable] @yields ]=] function PlayerStore:txImmutableAsync<T>( players: { Player }, transformFunction: (state: { [Player]: T }) -> { [Player]: T } | false ) return self:txImmutable(players, transformFunction):expect() end --[=[ Forces an immediate save of the given player's data. :::info Data is automatically saved periodically, so manual saves are usually unnecessary. ::: @error "Key not loaded" -- The player's data hasn't been loaded @error "Store is closed" -- The store has been closed @return Promise -- Resolves when the save is complete @within PlayerStore ]=] function PlayerStore:save(player: Player) local userIdKey = getUserIdKey(player) return self._store:save(userIdKey) end --[=[ Syntactic sugar for `playerStore:save(player):expect()`. See [PlayerStore:save] @yields ]=] function PlayerStore:saveAsync(player: Player) return self:save(player):expect() end --[=[ Closes the store and unloads all active sessions. The store cannot be used after closing. @return Promise -- Resolves when the store is closed @within PlayerStore ]=] function PlayerStore:close() return self._store:close() end --[=[ Syntactic sugar for `playerStore:close():expect()`. See [PlayerStore:close] @yields ]=] function PlayerStore:closeAsync() return self:close():expect() end --[=[ Returns the current data for the given key without loading it into the store. ```lua playerStore:peek(userId):andThen(function(data) print("Current coins:", data.coins) end) ``` @return Promise<T> -- Resolves with the current data @within PlayerStore ]=] function PlayerStore:peek(userId: number) local userIdKey = tostring(userId) return self._store:peek(userIdKey) end --[=[ Syntactic sugar for `playerStore:peek(userId):expect()`. See [PlayerStore:peek] @yields ]=] function PlayerStore:peekAsync(userId: number) return self:peek(userId):expect() end return { createPlayerStore = createPlayerStore, }
4,287
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/PromiseQueue.luau
--[=[ @class PromiseQueue @private Implements a queue that processes asynchronous operations (represented by functions returning Promises or synchronous functions) one at a time, ensuring serial execution. **Purpose:** Useful for scenarios where operations on a shared resource must not run concurrently to prevent race conditions or ensure logical order. For example, processing updates to a specific player's data session. **Core Logic:** - Operations are added to the queue via the `add` method. - Each operation is wrapped in a `Promise`. - A single processing loop ([PromiseQueue:_processQueue]) runs as long as the queue is not empty. - The loop takes the next item, executes its associated function, and waits for its Promise to resolve or reject before moving to the next item. - Includes timeout and deadlock detection for individual items. - Supports adding an operation atomically across multiple queues ([PromiseQueue:multiQueueAdd]). ]=] local Log = require(script.Parent.Log) local Promise = require(script.Parent.Promise) local Tables = require(script.Parent.Tables) --[=[ Internal implementation details and methods for the PromiseQueue class. @interface PromiseQueueImpl @within PromiseQueue @private .__index PromiseQueueImpl .new (params: CreatePromiseQueueParams) -> PromiseQueue ._processQueue (self: PromiseQueue) -> () ._addResumableBlock (queue: PromiseQueue) -> Promise<() -> ()> ._getLogContext (self: PromiseQueue, item: QueueItem?) -> { [string]: any } .add (self: PromiseQueue, callback: () -> ()) -> Promise .multiQueueAdd (queues: { PromiseQueue }, callback: () -> ()) -> Promise -- Public static method ]=] type PromiseQueueImpl = { __index: PromiseQueueImpl, new: (params: CreatePromiseQueueParams) -> PromiseQueue, _processQueue: (self: PromiseQueue) -> (), _addResumableBlock: (queue: PromiseQueue) -> Promise.TPromise<() -> ()>, _getLogContext: (self: PromiseQueue, item: QueueItem?) -> { [string]: any }, multiQueueAdd: (queues: { PromiseQueue }, callback: () -> ()) -> Promise.Promise, add: (self: PromiseQueue, callback: () -> ()) -> Promise.Promise, } --[=[ Internal properties stored within a PromiseQueue instance. @interface PromiseQueueProps @within PromiseQueue @private ._queue { QueueItem } -- The actual queue holding items to be processed. ._logger Log.Logger -- Logger instance for internal logging. ._totalItemCount number -- Counter for assigning unique IDs to queue items. ]=] type PromiseQueueProps = { _queue: { QueueItem }, _logger: Log.Logger, _totalItemCount: number, } --[=[ Represents a single item within the queue. @interface QueueItem @within PromiseQueue @private .id number -- Unique identifier for the item within this queue instance. .fn () -> () -- The function to execute for this item. Can be sync or return a Promise. .resolve (value: any) -> () -- The resolve function of the Promise returned by `add`. .reject (error: any) -> () -- The reject function of the Promise returned by `add`. .trace string -- Debug traceback captured when the item was added. ]=] type QueueItem = { id: number, fn: () -> (), resolve: (value: any) -> (), reject: (error: any) -> (), trace: string, } export type PromiseQueue = typeof(setmetatable({} :: PromiseQueueProps, {} :: PromiseQueueImpl)) local PromiseQueue = {} :: PromiseQueueImpl PromiseQueue.__index = PromiseQueue --[=[ Parameters for creating a new PromiseQueue instance. @interface CreatePromiseQueueParams @within PromiseQueue .logger Log.Logger ]=] type CreatePromiseQueueParams = { logger: Log.Logger, } --[=[ Creates a new PromiseQueue instance. @param params -- Configuration parameters. @return PromiseQueue -- A new PromiseQueue object. @within PromiseQueue ]=] function PromiseQueue.new(params: CreatePromiseQueueParams): PromiseQueue return setmetatable({ _queue = {}, _logger = params.logger, _totalItemCount = 0, }, PromiseQueue) :: PromiseQueue end --[=[ Adds a new operation (callback function) to the end of the queue. The callback will be executed only after all preceding items in the queue have completed. @param callback () -> T -- The function to execute. This function can be synchronous or return a Promise. Its result or error will resolve/reject the Promise returned by this `add` call. @return Promise<T> -- A Promise that resolves or rejects with the result or error of the provided `callback` function once it's processed by the queue. @within PromiseQueue ]=] function PromiseQueue:add(callback: () -> ()): Promise.Promise local trace = debug.traceback(nil, 2) -- Capture stack trace for debugging slow/failed items. return Promise.new(function(resolve, reject, onCancel) self._totalItemCount += 1 -- Create the queue item record. local record = { id = self._totalItemCount, fn = callback, resolve = resolve, reject = reject, trace = trace, } table.insert(self._queue, record) self._logger:log("trace", "added item to queue", self:_getLogContext()) -- Handle cancellation: if the returned promise is cancelled before processing, -- remove the item from the queue. onCancel(function() local idx = table.find(self._queue, record) if idx then table.remove(self._queue, idx) self._logger:log("trace", "removed cancelled item from queue", self:_getLogContext(record)) end end) -- If this is the first item added to an empty queue, start the processing loop. if #self._queue == 1 then task.spawn(function() self:_processQueue() end) end end) end --[=[ Internal function that processes items from the queue sequentially. It runs as long as there are items in the queue. @within PromiseQueue @private ]=] function PromiseQueue:_processQueue() self._logger:log("trace", "processing queue", self:_getLogContext()) -- Loop continues as long as items exist in the queue. while #self._queue > 0 do local item = self._queue[1] -- Get the next item from the front. -- Set up a warning timer for potential deadlocks or long-running items. -- If an item takes longer than 60 seconds, a warning is logged. local deadlockWarn = task.delay(60, function() local ctx = self:_getLogContext(item) ctx.trace = item.trace -- Include original call stack in warning. self._logger:log("warn", "queue item taking > 60s", ctx) end) self._logger:log("trace", "processing queue item", self:_getLogContext(item)) -- Execute the item's function within a Promise context. Promise .try(item.fn) :timeout(60) -- Apply a 60-second timeout to the item's execution. :andThen( item.resolve, -- If successful, resolve the original promise returned by `add`. function(e) -- If failed (error or timeout)... -- Log the failure details. local ctx = self:_getLogContext(item) ctx.error = e ctx.trace = item.trace local msg if Promise.Error.isKind(e, Promise.Error.Kind.TimedOut) then msg = "queue item timed out" else msg = "queue item failed" end self._logger:log("debug", msg, ctx) -- Reject the original promise with the error and traceback. item.reject(`Queue item failed: {e}\nCreated at:\n{item.trace}`) end ) :finally(function() -- This runs regardless of success or failure. self._logger:log("trace", "finished processing queue item", self:_getLogContext(item)) -- Remove the item *only if* it's still the first item. -- This prevents issues if an item was cancelled and removed while processing. if self._queue[1] == item then table.remove(self._queue, 1) end -- Cancel the deadlock warning timer as the item has finished. task.cancel(deadlockWarn) end) :await() -- Wait for the item's promise (including timeout/finally) to complete before the loop continues. end self._logger:log("trace", "finished processing queue", self:_getLogContext()) end --[=[ Internal helper function used by `multiQueueAdd`. Adds a special "blocking" item to a single queue. This item's function returns a Promise that only resolves when an external `resume` function is called. `resume` is just a Promise resolver function - calling it unblocks the queue item. @param queue -- The PromiseQueue instance to add the block to. @return Promise<() -> ()> -- A Promise that resolves with the `resume` function once the block becomes the active item in the queue. @within PromiseQueue @private ]=] local function addResumableBlock(queue: PromiseQueue): Promise.TPromise<() -> ()> return Promise.new(function(outerResolve) -- Add an item whose function returns a promise... queue:add(function() return Promise.new(function(resume) -- ...that resolves the outer promise (`addResumableBlock`'s promise) -- with the `resume` function needed to unblock this item. outerResolve(resume :: any) end) end) end) end PromiseQueue._addResumableBlock = addResumableBlock -- Assign to the metatable for internal use. --[=[ Atomically adds a callback function to be executed across multiple queues. Ensures that the callback only runs when it has effectively acquired the "lock" (become the currently processing item) on *all* specified queues simultaneously. This is useful for operations that need to coordinate across multiple resources managed by separate queues. **Mechanism:** 1. Uses `_addResumableBlock` to add a blocking item to each queue. 2. Waits for all these blocking items to become active (i.e., all `_addResumableBlock` promises resolve, returning their `resume` functions). 3. Once all queues are blocked, executes the provided `callback`. 4. After the `callback` finishes (successfully or with an error), calls all the `resume` functions to unblock all the queues. @param queues -- A table array of PromiseQueue instances to coordinate. @param callback -- The function to execute once all queues are ready. @return Promise -- A Promise that resolves/rejects with the result/error of the `callback`. @within PromiseQueue ]=] function PromiseQueue.multiQueueAdd(queues: { PromiseQueue }, callback: () -> ()): Promise.Promise local trace = debug.traceback(nil, 2) return Promise.new(function(resolve, reject) -- Add a resumable block to each queue. local promises = Tables.map(queues, addResumableBlock) -- Wait for all blocks to be added and become active. Promise.all(promises):andThen(function(resumes) -- All queues are now blocked at our added item. Execute the callback. Promise.try(callback) :andThen(resolve, function(e) -- Handle callback success/failure reject(`multiQueueAdd callback failed: {e}\nCreated at:\n{trace}`) end) :finally(function() -- Unblock all queues regardless of callback outcome. for _, resume in resumes do resume() end end) end) end) end --[=[ Internal helper to generate a context table for logging. @param item -- (Optional) The QueueItem currently being processed. @return { [string]: any } -- A table containing common context fields like queue length and item ID. @within PromiseQueue @private ]=] function PromiseQueue:_getLogContext(item: QueueItem?): { [string]: any } return { queueLength = #self._queue, totalItems = self._totalItemCount, itemId = item and item.id, } end return PromiseQueue
2,710
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/Types.luau
--[=[ @class Types @private Common types shared among different modules. ]=] local Log = require(script.Parent.Log) local t = require(script.Parent.Parent.t) --[=[ Represents a single operation within a JSON Patch array. Used for describing changes between data states. @interface PatchOperation @within Types .op "add" | "replace" | "remove" -- The operation type. .path string -- A JSON Pointer string indicating the target location. .value any? -- The value to add or replace (used for "add" and "replace"). Optional for "remove". ]=] export type PatchOperation = { op: "add", path: string, value: any } | { op: "replace", path: string, value: any } | { op: "remove", path: string } --[=[ An array of PatchOperation objects representing the changes made during a transaction. @type TxPatch { PatchOperation } @within Types ]=] export type TxPatch = { PatchOperation } --[=[ Holds information about the state of data potentially involved in a transaction. Used by the `Transactions` module to determine the correct data to return during reads. @interface TxInfo @within Types .committedData any -- The last known data state that was successfully saved to the primary DataStore record *before* the transaction identified by `txId` began. .txId string? -- The unique identifier of the transaction currently attempting to modify this data. If `nil`, no transaction is active or the last one completed and was cleaned up. .txPatch TxPatch? -- The set of changes (JSON Patch) applied by the transaction identified by `txId`. This is used to reconstruct the final state if the transaction is confirmed as committed. ]=] export type TxInfo = { committedData: any, txId: string?, txPatch: TxPatch?, } --[=[ Represents the stored data, abstracting away the sharding mechanism. If the data was small enough, it's stored directly in the `data` field. If the data was large and sharded, `shard` and `count` are present instead, pointing to the location and number of data shards stored separately. @interface File @within Types .data any? -- The actual data, if it was stored directly (not sharded). Mutually exclusive with `shard` and `count`. .shard string? -- The unique identifier for the set of shards, if the data was sharded. Mutually exclusive with `data`. .count number? -- The total number of shards, if the data was sharded. Mutually exclusive with `data`. ]=] export type File = { data: any, } & { shard: string, count: number, } --[=[ The structure of the primary record stored in the main DataStore for each key. This record contains metadata and a reference (`File`) to the actual user data. @interface DataStoreRecord @within Types .appliedMigrations {string} -- A list of names of migration steps that have already been successfully applied to the data associated with this record. Initialized as empty. .file File -- A `File` object representing the actual user data. This might contain the data directly or point to shards. .orphanedFiles {File} -- A list of sharded `File` objects that are no longer referenced by any active record. This is used for cleanup and garbage collection of unused data. Initialized as empty. ]=] export type DataStoreRecord = { appliedMigrations: { string }, file: File, orphanedFiles: { File }, } --[=[ Represents a migration step that can be applied to data when loading it. Each step has a name and an `apply` function that takes the data as input and returns a modified version of the data. @interface MigrationStep @within Types .name string -- The unique name of the migration step. .apply (data: { [string]: any }) -> { [string]: any } -- The function that transforms the data for this step. ]=] export type MigrationStep = { name: string, apply: (data: { [string]: any }) -> { [string]: any }, } --[=[ Contains all the contextual information and dependencies required for a `Store` or `PlayerStore` instance to operate. This includes configuration, service instances, callbacks, and underlying storage objects. @interface StoreContext<T> @within Types .name string -- The name of the store, used for logging and potentially identifying DataStore keys. .template T -- A default template object representing the initial state for new data entries. .schema (value: any) -> (boolean, string?) -- A validation function (like one created by `t`) used to check if loaded or modified data conforms to the expected structure. Returns `true` if valid, or `false` and an error message string if invalid. .migrationSteps {MigrationStep} -- A list of migration steps to apply to data when it's loaded, based on the `appliedMigrations` field in the `DataStoreRecord`. Initialized as empty. .importLegacyData ((key: string) -> any?)? -- An optional function to load data from a legacy storage system when a key is accessed for the first time in this store. .dataStoreService DataStoreService -- The Roblox DataStoreService instance. .memoryStoreService MemoryStoreService -- The Roblox MemoryStoreService instance. .changedCallbacks { (key: string, newData: T, oldData: T?) -> () } -- A list of functions to call whenever data for a key is successfully changed. Provides the key, the new data state, and the previous data state (if available). Initialized as empty. .logger Logger -- A `Logger` instance used for internal logging within the store and its components. .onLockLost ((key: string) -> ())? -- An optional callback function triggered if the distributed lock for a key is lost unexpectedly (e.g., due to expiration or external interference). .useDSSLocking boolean -- Whether to use DataStoreService for distributed locking instead of MemoryStoreService. .recordStore DataStore -- The DataStore used to store `DataStoreRecord` objects. .shardStore DataStore -- The DataStore used to store the actual data shards for large files. .txStore DataStore -- The DataStore used to store transaction status markers (`txId` keys). .lockHashMap MemoryStoreHashMap -- The MemoryStore HashMap used for managing distributed locks. ]=] export type StoreContext<T> = { name: string, template: T, schema: (value: any) -> (boolean, string?), migrationSteps: { MigrationStep }, importLegacyData: ((key: string) -> any?)?, dataStoreService: DataStoreService, memoryStoreService: MemoryStoreService, changedCallbacks: { (key: string, newData: T, oldData: T?) -> () }, logger: Log.Logger, onLockLost: ((key: string) -> ())?, useDSSLocking: boolean, recordStore: DataStore, shardStore: DataStore, txStore: DataStore, lockHashMap: DataStore | MemoryStoreHashMap, } -- Validation check for TxInfo structure using 't' library. local txInfoCheck = t.some( t.strictInterface({ committedData = t.any }), t.strictInterface({ committedData = t.any, txId = t.string, txPatch = t.any }) ) -- Validation check for File structure using 't' library. local fileCheck = t.some(t.strictInterface({ data = t.any }), t.strictInterface({ shard = t.string, count = t.number })) --[=[ A handle returned by retry utility functions like `hashMapRetry`. It bundles the core Promise with a way to cancel the retry operation. When the `cancel` function is called, instead of cancelling the Promise itself, the retry mechanism is stopped, and the Promise is rejected with a cancellation error when the next retry attempt is made. @interface RetryHandle<T> @within Types .promise T -- The Promise representing the asynchronous operation being retried. This promise resolves or rejects based on the outcome of the operation after retries. .cancel () -> () -- A function that can be called to signal cancellation. If called, the retry mechanism will stop further attempts and reject the `promise`. ]=] export type RetryHandle<T> = { promise: T, cancel: () -> (), } return { txInfoCheck = txInfoCheck, fileCheck = fileCheck, }
1,799
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/hashMapRetry.luau
--[=[ @class hashMapRetry @private Provides a utility function to wrap Roblox MemoryStoreService HashMap API calls (like `GetAsync`, `SetAsync`, `UpdateAsync`) with automatic retries for specific, commonly transient error conditions identified by error message strings. **Purpose:** Similar to [dataStoreRetry], MemoryStore operations can fail due to temporary service issues, throttling, or internal errors. This module implements a retry mechanism with exponential backoff to handle these transient failures. It differs from [dataStoreRetry] by matching against error *strings* rather than numeric codes, as MemoryStore errors often manifest this way. It also includes a cancellation mechanism. **Usage:** ```lua local MemoryStoreService = game:GetService("MemoryStoreService") local hashMapRetry = require(script.Parent.hashMapRetry) local myMap = MemoryStoreService:GetHashMap("MyMap") local handle = hashMapRetry(function() -- This function will be retried automatically on specific errors return myMap:GetAsync("MyKey") end) handle.promise:andThen(function(data) print("Successfully retrieved data:", data) end):catch(function(err) warn("Failed to get data after retries or cancelled:", err) end) -- To cancel the operation: -- handle.cancel() ``` ]=] local Promise = require(script.Parent.Promise) local Types = require(script.Parent.Types) -- Maximum number of times to attempt the operation before giving up. local MAX_RETRIES = 5 --[[ List of error message substrings that indicate potentially transient MemoryStore errors worth retrying. These are based on observed errors and common failure modes like throttling and internal issues. Unlike DataStores, MemoryStore often reports errors via strings rather than distinct numeric codes. Refer to Roblox Creator Documentation for MemoryStore limits and potential issues: https://create.roblox.com/docs/cloud-services/memory-stores#observability (Note: Specific error message strings may not be exhaustively documented.) ]] local RETRY_ERROR_CODES = { "TotalRequestsOverLimit", -- Exceeds universe-level request unit limit. "InternalError", -- Generic internal server error. "RequestThrottled", -- Recent MemoryStores requests hit one or more limits. "PartitionRequestsOverLimit", -- Exceeds partition request unit limit. "Throttled", -- Undocumented, included for completeness. "Timeout", -- Undocumented, included for completeness. } --[=[ Wraps a function that performs a MemoryStore HashMap operation, automatically retrying it if it fails with specific transient error message substrings. Implements an exponential backoff strategy: waits 1s, 2s, 4s, 8s between retries. Includes a cancellation mechanism via the returned [RetryHandle]. @within hashMapRetry @param func () -> any -- The function to execute and potentially retry. This function should perform the desired MemoryStore HashMap operation (e.g., `GetAsync`, `SetAsync`, `UpdateAsync`). It should return the result on success or throw an error on failure. @return RetryHandle<Promise<any>> -- A handle containing: `promise` (A Promise that resolves with the return value of `func` if it succeeds within `MAX_RETRIES` attempts) and `cancel` (A function that, when called, attempts to stop further retries and rejects the promise). @error string -- Rejects if `func` fails with a non-retriable error, if it fails with a retriable error `MAX_RETRIES` times, or if `cancel()` is called. ]=] local function hashMapRetry(func: () -> any): Types.RetryHandle<Promise.TPromise<any>> local cancel = false local handle: Types.RetryHandle<Promise.TPromise<any>> = { promise = Promise.new(function(resolve, reject) local lastError for i = 1, MAX_RETRIES do -- Apply exponential backoff delay before retrying (starting from the second attempt) -- Only wait if the operation hasn't been cancelled. if i > 1 and not cancel then -- Wait times: 2^0=1s, 2^1=2s, 2^2=4s, 2^3=8s local retryAfter = 2 ^ (i - 1) task.wait(retryAfter) end if cancel then return reject(`HashMap error: operation cancelled`) end local result = table.pack(pcall(func)) -- { success: boolean, ...results | error: string } if result[1] == true then -- Success! Resolve the promise with the function's return values. return resolve(table.unpack(result, 2)) end -- Failure. Store the error message. lastError = result[2] -- Check if the error message contains any of the retriable substrings. local retry = false for _, errorCodeSubstring in RETRY_ERROR_CODES do if lastError:find(errorCodeSubstring, 1, true) then retry = true break end end -- If the error is retriable, continue to the next iteration (if not cancelled). if retry then continue end -- Non-retriable error. Reject immediately. return reject(`HashMap error: {lastError}`) end -- If the loop completes, it means MAX_RETRIES were reached without success. -- Check for cancellation one last time before rejecting due to retries. if cancel then return reject(`HashMap error: operation cancelled`) else return reject(`HashMap error: too many retries ({MAX_RETRIES}). Last error: {lastError}`) end end), cancel = function() cancel = true end, } return handle end return hashMapRetry
1,255
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/init.luau
--[=[ @class Lyra The main entry point and public facade for the Lyra library. This module re-exports the primary functions and constructors needed to interact with Lyra, simplifying the public API and hiding internal module structure. Users of the library should typically only need to require this top-level module. ]=] local Log = require(script.Log) local Migrations = require(script.Migrations) local PlayerStore = require(script.PlayerStore) --[=[ Provides helper functions for creating common migration steps. @interface MigrationStep .field addFields (name: string, fields: { [string]: any }) -> MigrationStep -- Creates a step to add new fields with default values. .field transform (name: string, transformFunc: (currentValue: { [string]: any }) -> { [string]: any }) -> MigrationStep -- Creates a step with a custom data transformation function. @within Lyra ]=] local MigrationStep = { addFields = Migrations.makeAddFieldsStep, transform = Migrations.makeTransformStep, } --[=[ Factory function to create a new PlayerStore instance. @function createPlayerStore<T> @param context PlayerStoreConfig<T> -- The configuration for the PlayerStore. @return PlayerStore<T> -- A new PlayerStore instance. @within Lyra ]=] local createPlayerStore = PlayerStore.createPlayerStore --[=[ Sets the global minimum log level for all Lyra loggers. @function setLogLevel @param level LogLevel -- The minimum log level ("fatal", "error", "warn", "info", "debug", "trace"). @within Lyra ]=] local setLogLevel = Log.setLevel -- The public interface of the Lyra library. return { MigrationStep = MigrationStep, createPlayerStore = createPlayerStore, setLogLevel = setLogLevel, }
383
paradoxum-games/lyra
paradoxum-games-lyra-954e68c/src/noYield.luau
--[[ Calls a function and throws an error if it attempts to yield. Pass any number of arguments to the function after the callback. This function supports multiple return; all results returned from the given function will be returned. ]] local function resultHandler(co: thread, ok: boolean, ...) if not ok then local message = (...) error(debug.traceback(co, message), 2) end if coroutine.status(co) ~= "dead" then error(debug.traceback(co, "attempt to yield"), 2) end return ... end local function noYield<Input..., Output...>(callback: (Input...) -> Output..., ...: Input...): Output... local co = coroutine.create(callback) return resultHandler(co, coroutine.resume(co, ...)) end return noYield
169
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Action/Flags.lua
--!strict return { STATIONARY = bit32.lshift(1, 9), MOVING = bit32.lshift(1, 10), AIR = bit32.lshift(1, 11), INTANGIBLE = bit32.lshift(1, 12), SWIMMING = bit32.lshift(1, 13), METAL_WATER = bit32.lshift(1, 14), SHORT_HITBOX = bit32.lshift(1, 15), RIDING_SHELL = bit32.lshift(1, 16), INVULNERABLE = bit32.lshift(1, 17), BUTT_OR_STOMACH_SLIDE = bit32.lshift(1, 18), DIVING = bit32.lshift(1, 19), ON_POLE = bit32.lshift(1, 20), HANGING = bit32.lshift(1, 21), IDLE = bit32.lshift(1, 22), ATTACKING = bit32.lshift(1, 23), ALLOW_VERTICAL_WIND_ACTION = bit32.lshift(1, 24), CONTROL_JUMP_HEIGHT = bit32.lshift(1, 25), ALLOW_FIRST_PERSON = bit32.lshift(1, 26), PAUSE_EXIT = bit32.lshift(1, 27), SWIMMING_OR_FLYING = bit32.lshift(1, 28), WATER_OR_TEXT = bit32.lshift(1, 29), THROWING = bit32.lshift(1, 31), }
339
MaximumADHD/sm64-roblox
MaximumADHD-sm64-roblox-79d5372/client/Enums/Action/Groups.lua
--!strict return { -- Group Flags STATIONARY = bit32.lshift(0, 6), MOVING = bit32.lshift(1, 6), AIRBORNE = bit32.lshift(2, 6), SUBMERGED = bit32.lshift(3, 6), CUTSCENE = bit32.lshift(4, 6), AUTOMATIC = bit32.lshift(5, 6), OBJECT = bit32.lshift(6, 6), -- Mask for capturing these Flags GROUP_MASK = 0b_000000111000000, }
134