ModeMetricsMode 0 then call.unset = table.clone(state.personUnset) end if identity(state, call) then state.identified = true state.personSet, state.personOnce, state.personUnset = {}, {}, {} end end local function release(state: any) if state.loading or state.pendingConsent or state.out or state.consent.analytics_storage ~= "granted" then return end identify(state) for _, item in state.pending do if item.route == Wire.paths.events then item.data.consent = table.clone(state.consent) end queue:push(item.route, item.data, state.id) end state.pending = {} end local function newState(player: any): any local id = if player then Wire.id(player.UserId) else "server" if not id then return nil end local grants, pending = consent(options.consent) local context: any = { locale = "", timezone = "", screen_width = 0, screen_height = 0, viewport_width = 0, viewport_height = 0, library = Wire.LIB, library_version = Wire.LIB_VERSION, platform = "roblox", app_version = options.app_version, } -- No context.user_agent, so a secret key keeps the server surface and a -- Roblox datacenter address is never scored as a bot. local state: any = { id = id, player = player, session = Session.new(), joined = os.clock(), screen = options.place_name, context = context, device = {}, groups = {}, groupProperties = {}, supers = {}, pending = {}, relayTimes = {}, consent = grants, pendingConsent = pending, out = remembered[id], identified = false, person = {}, personSet = {}, personOnce = {}, personUnset = {}, levels = {}, levelOrder = {}, loading = false, } if state.out == nil then state.out = options.default_opt_out == true end states[player or "server"] = state return state end function Mode.capture(player: any, event: any, props: any?) if not running or not queue:accepting() or type(event) ~= "string" or #event == 0 or #event > 200 then return end local state = stateFor(player) if not state and player == nil then state = newState(nil) end if not state or not enabled(player) then return end local passive = event == Wire.events.performance or event == Wire.events.quit if not Session.touch(state, passive) then return end identify(state) local p: any = {} merge(p, supers) merge(p, state.supers) merge(p, state.session.supers) merge(p, properties(props)) p[Wire.props.engine] = "roblox" p[Wire.props.engine_version] = options.engine_version p[Wire.props.screen_name] = state.screen local attach = options.autocapture.device and (not state.session.deviceSent or event == Wire.events.opened) and next(state.device) ~= nil if attach then p[Wire.props.device] = table.clone(state.device) end if event == Wire.events.exception then p[Wire.props.release] = options.app_version p[Wire.props.breadcrumbs] = table.clone(state.session.breadcrumbs) end local item: any = { event_id = Uuid.new(), event = Wire.clean(event), distinct_id = state.id, timestamp = Wire.timestamp(), session_id = state.session.id, properties = p, context = table.clone(state.context), consent = table.clone(state.consent), } if next(state.groups) then item.groups = table.clone(state.groups) end local eventId, timestamp = item.event_id, item.timestamp if options.before_send then local ok, result = pcall(options.before_send, item) if not ok or type(result) ~= "table" then return end if type(result.event) ~= "string" or #result.event == 0 or #result.event > 200 then return end item = { event = Wire.clean(result.event), properties = properties(result.properties), context = table.clone(state.context), consent = table.clone(state.consent), distinct_id = state.id, session_id = state.session.id, event_id = eventId, timestamp = timestamp, groups = if next(state.groups) then table.clone(state.groups) else nil, } item.properties[Wire.props.engine] = "roblox" item.properties[Wire.props.engine_version] = options.engine_version item.properties[Wire.props.screen_name] = state.screen end local ok, encoded = pcall(Wire.encode, item) if not ok or #encoded > 65536 then return end if state.pendingConsent or state.loading then hold(state, Wire.paths.events, item) else queue:push(Wire.paths.events, item, state.id) end if attach then state.session.deviceSent = true end local breadcrumb: string = Wire.clean(item.event) table.insert(state.session.breadcrumbs, breadcrumb) if #state.session.breadcrumbs > 20 then table.remove(state.session.breadcrumbs, 1) end end local function personUpdate(player: any, set: any, once: any, unset: any) local state = stateFor(player) if not state or state.out then return end local cleanSet, cleanOnce = properties(set), properties(once) merge(state.person, cleanOnce, true) merge(state.person, cleanSet) local names = {} if type(unset) == "table" then for _, name in unset do if type(name) == "string" and #name > 0 and #name <= 200 then name = Wire.clean(name) table.insert(names, name) state.person[name] = nil state.personSet[name], state.personOnce[name] = nil, nil if #names == 100 then break end end end end state.flags = nil if not state.identified then merge(state.personSet, cleanSet) merge(state.personOnce, cleanOnce, true) for _, name in names do table.insert(state.personUnset, name) end identify(state) else local call: any = {type = "identify", user_id = state.id} if next(cleanSet) then call.set = cleanSet end if next(cleanOnce) then call.set_once = cleanOnce end if #names > 0 then call.unset = names end if call.set or call.set_once or call.unset then identity(state, call) end end end function Mode.set_person_properties(player: any, set: any, setOnce: any?) personUpdate(player, set, setOnce, nil) end function Mode.unset_person_properties(player: any, names: any) personUpdate(player, nil, nil, names) end function Mode.group(player: any, kind: any, key: any, set: any?) local state, groupType, groupKey = stateFor(player), Wire.id(kind), Wire.id(key) if not state or not enabled(player) or not groupType or not groupKey then return end state.groups[groupType] = groupKey local cleanSet = properties(set) if next(cleanSet) then state.groupProperties[groupType] = cleanSet end state.flags = nil identify(state) local call: any = {type = "group", group_type = groupType, group_key = groupKey, distinct_id = state.id} if next(cleanSet) then call.set = cleanSet end identity(state, call) end function Mode.alias(player: any, previous: any) local state, previousId = stateFor(player), Wire.id(previous) if not state or not enabled(player) or not previousId then return end identify(state) identity(state, {type = "alias", user_id = state.id, previous_id = previousId}) end function Mode.register(props: any) merge(supers, properties(props)) end function Mode.register_once(props: any) merge(supers, properties(props), true) end function Mode.unregister(name: string) supers[name] = nil end function Mode.register_for_player(player: any, props: any) local state = stateFor(player) if state and not state.out then merge(state.supers, properties(props)) end end function Mode.register_for_session(player: any, props: any) local state = stateFor(player) if state and not state.out then Session.touch(state, false) merge(state.session.supers, properties(props)) end end function Mode.get_distinct_id(player: any): string? local state = stateFor(player) return if state then state.id else nil end function Mode.get_session_id(player: any): string? local state = stateFor(player) return if state then state.session.id else nil end local function persistOpt(state: any) remembered[state.id] = state.out if options.opt_out_store and not optWriters[state.id] then optWriters[state.id] = true local store = options.opt_out_store task.spawn(function() local failures = 0 repeat local value = remembered[state.id] local ok = pcall(function() store:UpdateAsync("mode_opt_" .. state.id, function() return remembered[state.id] end) end) if ok then failures = 0 if value == remembered[state.id] then break end else failures += 1 task.wait(math.min(300, 2 ^ math.min(failures, 8))) end until not running optWriters[state.id] = nil end) end end function Mode.opt_out(player: any) local state = stateFor(player) if not state then return end state.out = true state.optRevision = (state.optRevision or 0) + 1 queue:removePlayer(state.id) state.pending, state.personSet, state.personOnce, state.personUnset = {}, {}, {}, {} state.person, state.supers, state.groups, state.groupProperties = {}, {}, {}, {} state.flags = nil state.identified = false state.session = Session.new() errors.remove(player) persistOpt(state) end function Mode.opt_in(player: any) local state = stateFor(player) if not state then return end state.out = false state.optRevision = (state.optRevision or 0) + 1 persistOpt(state) release(state) end function Mode.set_consent(player: any, value: any) local state = stateFor(player) if not state then return end state.consent, state.pendingConsent = consent(value) if state.pendingConsent or state.consent.analytics_storage == "denied" then queue:removePlayer(state.id) state.identified = false state.flags = nil if not state.pendingConsent then state.pending = {} end else release(state) end end local function levelState(player: any, level: any): (any, string?) local state = stateFor(player) if not state or not enabled(player) or (type(level) ~= "string" and type(level) ~= "number") then return nil, nil end local name = Wire.truncate(Wire.clean(tostring(level)), 200) if name == "" then return nil, nil end if not state.levels[name] then state.levels[name] = {attempt = 0} table.insert(state.levelOrder, name) if #state.levelOrder > 1000 then state.levels[table.remove(state.levelOrder, 1)] = nil end end return state.levels[name], name end function Mode.level_start(player: any, level: any, props: any?) local track, name = levelState(player, level) if not track then return end track.attempt += 1 track.started = os.clock() local p = properties(props) p[Wire.props.level], p[Wire.props.attempt] = name, track.attempt Mode.capture(player, Wire.events.level_start, p) end local function levelEnd(player: any, level: any, event: string, reason: any, props: any) local track, name = levelState(player, level) if not track then return end local p = properties(props) p[Wire.props.level], p[Wire.props.attempt] = name, track.attempt if track.started then p[Wire.props.duration_ms] = math.floor((os.clock() - track.started) * 1000) end if type(reason) == "string" then p[Wire.props.reason] = Wire.truncate(Wire.clean(reason), 200) end track.started = nil Mode.capture(player, event, p) end function Mode.level_complete(player: any, level: any, props: any?) levelEnd(player, level, Wire.events.level_complete, nil, props) end function Mode.level_fail(player: any, level: any, reason: any, props: any?) levelEnd(player, level, Wire.events.level_fail, reason, props) end function Mode.score(player: any, value: number, props: any?) if type(value) ~= "number" or value ~= value or math.abs(value) == math.huge then return end local p = properties(props) p[Wire.props.score] = value Mode.capture(player, Wire.events.score, p) end function Mode.progression(player: any, milestone: any, props: any?) if type(milestone) ~= "string" then return end local p = properties(props) p[Wire.props.milestone] = Wire.truncate(Wire.clean(milestone), 200) Mode.capture(player, Wire.events.progression, p) end -- The contract's $purchase. With a source (the store) and its transaction id -- the event carries dedupe_key, so the store's own report counts once. function Mode.purchase(player: any, product: any, value: any, currency: any, props: any?) local productId = Wire.id(product) if not productId or type(currency) ~= "string" then return end if value ~= nil and (type(value) ~= "number" or value ~= value or math.abs(value) == math.huge) then return end local p = properties(props) local quantity = p[Wire.props.quantity] if type(quantity) ~= "number" or quantity < 1 or quantity % 1 ~= 0 then quantity = 1 end p[Wire.props.quantity] = nil p[Wire.props.items] = {{[Wire.props.product_id] = productId, [Wire.props.quantity] = quantity}} p[Wire.props.value] = value p[Wire.props.currency] = Wire.truncate(Wire.clean(currency), 16) if p[Wire.props.dedupe_key] == nil then p[Wire.props.dedupe_key] = Wire.dedupeKey(p[Wire.props.source], p[Wire.props.transaction_id]) end Mode.capture(player, Wire.events.purchase, p) end function Mode.wrapProcessReceipt(handler: any): any assert(purchases, "Initialize Mode before wrapping receipts") return purchases.wrap(handler) end function Mode.get_flag(player: any, key: string): any local state = stateFor(player) if not running or not state or not enabled(player) then return false end Session.touch(state, false) return flags.get(state, key) end function Mode.is_feature_enabled(player: any, key: string): boolean local value = Mode.get_flag(player, key) return value ~= false and value ~= nil end function Mode.flush() if queue then queue:flush() end end local function quit(player: any) local state = stateFor(player) if not state then return end if options.autocapture.app then Mode.capture(player, Wire.events.quit, { [Wire.props.session_ms] = math.floor((os.clock() - state.session.started) * 1000), [Wire.props.foreground_ms] = math.floor((os.clock() - state.joined) * 1000), }) end Mode.flush() errors.remove(player) state.closed = true state.flags = nil states[player] = nil end function Mode.shutdown() if not running or closing then return end closing = true local deadline = os.clock() + 24 for player in states do if player ~= "server" then quit(player) end end for _, connection in connections do connection:Disconnect() end connections = {} if relay then relay.stop() end errors.stop() purchases.stop() queue:flush() while os.clock() < deadline and (#queue.items > 0 or queue.busy) do task.wait(0.05) end queue:stop() states = {} running = false end function Mode.init(config: any): any if running then return Mode end assert(type(config) == "table" and type(config.host) == "string", "Mode host must be an HTTPS origin") local host: string = config.host assert(host:match("^https://[^/%s?#]+/?$"), "Mode host must be an HTTPS origin") options = table.clone(config) options.host = host:gsub("/+$", "") options.app_version = if type(config.app_version) == "string" then Wire.truncate(Wire.clean(config.app_version), 200) else "" options.build = Wire.truncate(Wire.clean(tostring(config.build or game.PlaceVersion)), 200) options.app_name = Wire.truncate(Wire.clean(if type(config.app_name) == "string" then config.app_name else game.Name), 200) options.engine_version = Wire.truncate(Wire.clean(version()), 200) options.flush_interval = if type(config.flush_interval) == "number" and config.flush_interval == config.flush_interval then math.clamp(config.flush_interval, 0.1, 300) else 10 options.autocapture = {} for _, key in {"app", "screen", "errors", "purchases", "device", "performance"} do options.autocapture[key] = config.autocapture ~= false and (type(config.autocapture) ~= "table" or config.autocapture[key] ~= false) end if type(config.before_send) ~= "function" then options.before_send = nil end local key = config.key if key == nil then local ok, secret = pcall(function() return HttpService:GetSecret(config.secret_name or "mode_key") end) assert(ok and secret ~= nil, "Mode secret is unavailable") key = secret else assert(type(key) == "string" and #key > 0, "Mode test key must be nonempty text") end queue = Queue.new(options, key) running, closing = true, false errors = Errors.new(Mode.capture, function(player: any): boolean if player == nil and not stateFor(nil) then newState(nil) end return options.autocapture.errors and enabled(player) end) purchases = Purchases.new(Mode.purchase, function(player: any): boolean return options.autocapture.purchases and enabled(player) end, connect) flags = Flags.new(queue, Mode.capture) if config.relay ~= false then relay = Relay.new(stateFor, Mode.capture, errors, options.autocapture, connect) end local function join(player: any) if not running or stateFor(player) then return end local state = newState(player) if not state then return end state.personOnce = { [Wire.props.account_age_days] = math.max(0, player.AccountAge), [Wire.props.membership_type] = player.MembershipType.Name, } merge(state.person, state.personOnce) if options.opt_out_store then state.loading = true local revision = state.optRevision local ok, value = pcall(function() return options.opt_out_store:GetAsync("mode_opt_" .. state.id) end) if not running or stateFor(player) ~= state then return end if revision == state.optRevision then -- A failed read cannot silently override a player's stored refusal. if ok and type(value) == "boolean" then state.out = value elseif not ok then state.out = true end end state.loading = false end identify(state) local facts: any = {} local ok, joinData = pcall(function() return player:GetJoinData() end) if ok and type(joinData) == "table" then facts = joinData end if options.autocapture.app then local source = tonumber(facts.SourcePlaceId) Mode.capture(player, Wire.events.opened, { [Wire.props.version] = options.app_version, [Wire.props.build] = options.build, [Wire.props.from_background] = false, [Wire.props.place_id] = tostring(game.PlaceId), [Wire.props.source_place_id] = if source and source > 0 then tostring(source) else nil, [Wire.props.teleported] = source ~= nil and source > 0, [Wire.props.launch_data] = type(facts.LaunchData) == "string" and #facts.LaunchData > 0, }) end if options.autocapture.screen then if state.screen then Mode.capture(player, Wire.events.screen) else state.screenWaiting = true end end release(state) end connect(Players.PlayerAdded, join) connect(Players.PlayerRemoving, quit) if options.autocapture.errors then connect(ScriptContext.Error, function(message: any, stack: any, sourceScript: any) local involved = nil if sourceScript then for _, player in Players:GetPlayers() do local ok, belongs = pcall(function() return sourceScript:IsDescendantOf(player) or (player.Character ~= nil and sourceScript:IsDescendantOf(player.Character)) end) if ok and belongs then involved = player break end end end errors.report(involved, message, stack, false) end) end game:BindToClose(Mode.shutdown) local currentQueue = queue local resolved = false local function resolvePlace(name: any) if resolved or not running or currentQueue ~= queue then return end resolved = true options.place_name = if type(name) == "string" and #name > 0 then Wire.truncate(Wire.clean(name), 200) else tostring(game.PlaceId) for _, state in states do state.screen = options.place_name if state.screenWaiting then state.screenWaiting = false local p: any = {} if state.loadMs then p[Wire.props.load_ms] = state.loadMs state.loadSent = true end Mode.capture(state.player, Wire.events.screen, p) end end end -- Place metadata is fetched once without holding up the game's initialization. task.spawn(function() local ok, info = pcall(function() return MarketplaceService:GetProductInfo(game.PlaceId, Enum.InfoType.Asset) end) resolvePlace(if ok and type(info) == "table" then info.Name else nil) end) task.delay(5, function() resolvePlace(nil) end) for _, player in Players:GetPlayers() do task.spawn(join, player) end return Mode end return Mode ]]>Errors= 100 then return end table.insert(emitted, now) local props = table.clone(entry.props) props[Wire.props.repeat_count] = repeats emit(entry.player, Wire.events.exception, props) end function api.report(player: any, message: any, stack: any, fromClient: boolean?) if not alive or not enabled(player) or type(message) ~= "string" or type(stack) ~= "string" then return end local cleanMessage = Wire.truncate(Wire.clean(message), 4096) local cleanStack = Wire.truncate(Wire.clean(stack), 16384) if player then for _, field in {"Name", "DisplayName"} do local ok, name = pcall(function() return player[field] end) if ok and type(name) == "string" and #name > 0 then local pattern = name:gsub("([^%w])", "%%%1") cleanMessage = cleanMessage:gsub(pattern, "[player]") cleanStack = cleanStack:gsub(pattern, "[player]") end end end local kind = "Error" local firstLine = cleanStack:match("^[^\n]*") or "" local owner = if player then tostring(player.UserId) else "server" local fingerprint = owner .. "\n" .. kind .. "\n" .. cleanMessage .. "\n" .. firstLine local entry = entries[fingerprint] if entry then entry.repeats += 1 if not entry.scheduled then entry.scheduled = true task.delay(math.max(0, entry.last + 60 - os.clock()), function() if not alive or entries[fingerprint] ~= entry then return end local repeats = entry.repeats entry.repeats = 0 entry.scheduled = false entry.last = os.clock() send(entry, repeats) end) end return end if count >= 1000 then for key, old in entries do if not old.scheduled and old.last <= os.clock() - 60 then entries[key] = nil count -= 1 end end if count >= 1000 then return end end entry = {player = player, repeats = 0, last = os.clock(), scheduled = false, props = { [Wire.props.type] = kind, [Wire.props.message] = cleanMessage, [Wire.props.stack] = cleanStack, [Wire.props.handled] = false, [Wire.props.fatal] = false, [Wire.props.mechanism] = "roblox_script_context", }} if fromClient then entry.props[Wire.props.from_client] = true end entries[fingerprint] = entry count += 1 send(entry, 1) end function api.remove(player: any) for key, entry in entries do if entry.player == player then entries[key] = nil count -= 1 end end end function api.stop() alive = false table.clear(entries) end return api end return Errors ]]>Flags 200 then return false end if queue.stopped or state.closed or state.out or state.loading or state.consent.analytics_storage ~= "granted" or state.pendingConsent then return false end local cache = state.flags if not cache then cache = {values = {}, expires = 0, retry = 0, attempts = 0, loading = false} state.flags = cache end local now = os.clock() if now >= cache.expires and now >= cache.retry and not cache.loading and queue:waitUntil() <= now then cache.loading = true local bodyToSend: any = {distinct_id = state.id} if next(state.groups) then bodyToSend.groups = state.groups end if next(state.person) then bodyToSend.person_properties = state.person end if next(state.groupProperties) then bodyToSend.group_properties = state.groupProperties end local status, body = queue:request(Wire.paths.flags, bodyToSend) cache.loading = false if state.flags ~= cache then return false end if state.out or state.pendingConsent or state.consent.analytics_storage ~= "granted" then return false end if status >= 200 and status < 300 and type(body) == "string" then local ok, data = pcall(function() return HttpService:JSONDecode(body) end) if ok and type(data) == "table" and type(data.flags) == "table" then cache.values = {} for name, value in data.flags do if type(name) == "string" and #name <= 200 and (type(value) == "boolean" or type(value) == "string") then cache.values[name] = if type(value) == "string" then Wire.truncate(Wire.clean(value), 200) else value end end cache.expires = os.clock() + 60 cache.retry = 0 cache.retryable = false cache.attempts = 0 else cache.retry = os.clock() + 10 cache.retryable = true end elseif status < 200 or status == 408 or status == 429 or status >= 500 then cache.attempts += 1 cache.retryable = true cache.retry = math.max(queue:waitUntil(), os.clock() + math.min(300, 2 ^ math.min(20, cache.attempts - 1)) * (0.5 + Random.new():NextNumber() / 2)) else cache.retry = math.max(queue:waitUntil(), os.clock() + 60) cache.retryable = false end end if cache.expires <= os.clock() and not cache.loading and not cache.scheduled and (cache.retryable or queue:waitUntil() > os.clock()) then cache.scheduled = true task.delay(math.max(0.01, math.max(cache.retry, queue:waitUntil()) - os.clock()), function() cache.scheduled = false if state.flags == cache then api.get(state, key, true) end end) end local value = cache.values[key] if value == nil then value = false end -- Only evaluated values count as exposure, a failed request is not a flag decision. if not background and cache.expires > 0 and not state.session.exposed[key] then state.session.exposed[key] = true capture(state.player, Wire.events.flag, {[Wire.props.flag] = key, [Wire.props.value] = value}) end return value end return api end return Flags ]]>Purchases 256 then cache[table.remove(cacheOrder, 1)] = nil end end if alive and enabled(player) and not (developerProduct and receiptMode) then purchase(player, productId, entry.price, "ROBUX", {[Wire.props.source] = "roblox", [Wire.props.quantity] = 1}) end end) end connect(MarketplaceService.PromptGamePassPurchaseFinished, function(player: any, id: any, purchased: any) prompt(player, id, purchased, Enum.InfoType.GamePass, false) end) connect(MarketplaceService.PromptProductPurchaseFinished, function(userId: any, id: any, purchased: any) if type(userId) ~= "number" then return end prompt(Players:GetPlayerByUserId(userId), id, purchased, Enum.InfoType.Product, true) end) function api.wrap(handler: any): any assert(type(handler) == "function", "Mode receipt handler must be a function") local callback = handler :: (any) -> any receiptMode = true return function(receipt: any): any local result = callback(receipt) if result == Enum.ProductPurchaseDecision.PurchaseGranted and type(receipt) == "table" then local transaction = Wire.id(receipt.PurchaseId) local player = Players:GetPlayerByUserId(receipt.PlayerId) if alive and transaction and not receipts[transaction] and player and enabled(player) then receipts[transaction] = true table.insert(receiptOrder, transaction) if #receiptOrder > 1000 then receipts[table.remove(receiptOrder, 1)] = nil end purchase(player, receipt.ProductId, receipt.CurrencySpent, "ROBUX", { [Wire.props.transaction_id] = transaction, [Wire.props.source] = "roblox", [Wire.props.quantity] = 1, }) end end return result end end function api.stop() alive = false end return api end return Purchases ]]>Queue= self.pause end function Queue.schedule(self: any, delay: number) if self.stopped or #self.items == 0 then return end local due = os.clock() + math.max(0.01, delay) if self.due <= due then return end self.timer += 1 local token = self.timer self.due = due task.delay(math.max(0.01, due - os.clock()), function() if self.stopped or token ~= self.timer then return end self.due = math.huge self:flush() end) end function Queue.push(self: any, route: string, data: any, owner: string): boolean if not self:accepting() then return false end local ok, encoded = pcall(Wire.encode, data) if not ok or #encoded > 65536 then return false end local decodedOk, snapshot = pcall(function() return HttpService:JSONDecode(encoded) end) if not decodedOk then return false end table.insert(self.items, {route = route, data = snapshot, owner = owner, attempt = 0, at = 0}) if #self.items > 1000 then table.remove(self.items, 1) end self:schedule(if #self.items >= 50 then 0 else self.options.flush_interval) return true end function Queue.removePlayer(self: any, owner: string) local keep = {} for _, item in self.items do if item.owner ~= owner then table.insert(keep, item) end end self.items = keep end function Queue.waitUntil(self: any): number local now = os.clock() while self.requests[1] and self.requests[1] <= now - 60 do table.remove(self.requests, 1) end local rate = if #self.requests >= 60 then self.requests[1] + 60 else now return math.max(now, self.hold, self.pause, rate) end -- The key as a bearer token, the one way of sending it every route of the -- edge reads through Mode's proxy, which drops X-Mode-Key. A Roblox Secret -- only ever leaves as a header, so its prefix is added by the Secret itself. local function bearer(key: any): any if type(key) == "string" then return "Bearer " .. key end return key:AddPrefix("Bearer ") end function Queue.request(self: any, path: string, body: any): (number, any) if self.stopped or self:waitUntil() > os.clock() then return 0, nil end local encodedOk, encoded = pcall(Wire.encode, body) if not encodedOk or #encoded > 400000 then return 400, nil end table.insert(self.requests, os.clock()) local ok, response = pcall(function() return HttpService:RequestAsync({ Url = self.options.host .. path, Method = "POST", Headers = {["Content-Type"] = Wire.CONTENT_TYPE, Authorization = bearer(self.key)}, Body = encoded, }) end) if not ok or type(response) ~= "table" then return 0, nil end local status = tonumber(response.StatusCode) or 0 for name, value in response.Headers or {} do if string.lower(name) == "retry-after" and type(value) == "string" and value:match("^%d+$") then self.hold = math.max(self.hold, os.clock() + (tonumber(value) or 0)) end end if status == 402 then self.pause = os.clock() + 300 end return status, response.Body end function Queue.flush(self: any) if self.busy or self.stopped or #self.items == 0 then return end self.busy = true task.spawn(function() while not self.stopped and #self.items > 0 do local now = os.clock() local nextSend = self:waitUntil() if nextSend > now then self:schedule(nextSend - now) break end local route = Wire.paths.events for _, item in self.items do if item.route == Wire.paths.identity then route = Wire.paths.identity break end end local take: {any} = {} local batch: {any} = {} local ready = math.huge for _, item in self.items do if item.route ~= route then continue end ready = math.min(ready, item.at) if item.at > now then continue end table.insert(batch, item.data) if #Wire.encode({sent_at = Wire.timestamp(), batch = batch}) > 400000 then table.remove(batch) break end table.insert(take, item) if #take == 50 then break end end if #take == 0 then self:schedule(math.max(0.01, ready - now)) break end local status = self:request(route, {sent_at = Wire.timestamp(), batch = batch}) if self.options.debug and (status < 200 or status >= 400) then warn("Mode Metrics delivery status " .. tostring(status)) end local retry = status < 200 or status == 408 or status == 429 or status >= 500 local selected = {} for _, item in take do selected[item] = true end if retry then local earliest = math.huge for _, item in take do item.attempt += 1 local delay = math.min(300, 2 ^ math.min(20, item.attempt - 1)) * (0.5 + self.random:NextNumber() / 2) item.at = math.max(self.hold, os.clock() + delay) earliest = math.min(earliest, item.at) end self:schedule(math.max(0.01, earliest - os.clock())) break else local keep = {} for _, item in self.items do if not selected[item] then table.insert(keep, item) end end self.items = keep end end self.busy = false end) end function Queue.stop(self: any) self.stopped = true self.timer += 1 self.items = {} end return Queue ]]>Relay= 10 then return end table.insert(times, now) if type(payload) ~= "table" or type(payload.kind) ~= "string" then return end if payload.kind == Wire.relay.device and options.device then local changed = false if type(payload.device_type) == "string" and allowed[payload.device_type] then state.device.device_type = payload.device_type changed = true end if type(payload.locale) == "string" then local locale = Wire.truncate(Wire.clean(payload.locale), 35) if locale:match("^[%a%d%-_]+$") then state.context.locale = locale state.device.languages = {locale} changed = true end end for _, axis in {"width", "height"} do local n = Relay.number(payload["screen_" .. axis], 65535, true) if n then state.context["screen_" .. axis] = n state.context["viewport_" .. axis] = n changed = true end end if changed then state.session.deviceSent = false end local load = Relay.number(payload.load_ms, 3600000, true) if load and not state.loadSent and options.screen then state.loadMs = load if state.screen then state.loadSent = true emit(player, Wire.events.screen, {[Wire.props.load_ms] = load}) end end elseif payload.kind == Wire.relay.load and options.screen then local load = Relay.number(payload.load_ms, 3600000, true) if load and not state.loadSent then state.loadMs = load if state.screen then state.loadSent = true emit(player, Wire.events.screen, {[Wire.props.load_ms] = load}) end end elseif payload.kind == Wire.relay.performance and options.performance then local props = {} for key, max in performance do local value = Relay.number(payload[key], max, key == "frames" or key == "slow_frames" or key == "frozen_frames" or key == "interval_ms") if value then props[Wire.props[key]] = value end end if props[Wire.props.frames] and props[Wire.props.frames] > 0 and props[Wire.props.interval_ms] and props[Wire.props.interval_ms] > 0 then emit(player, Wire.events.performance, props) end elseif payload.kind == Wire.relay.error and options.errors then if type(payload.message) == "string" and type(payload.stack) == "string" then errors.report(player, Wire.truncate(payload.message, 4096), Wire.truncate(payload.stack, 16384), true) end end end) return {stop = function() if owned then endpoint:Destroy() end end} end return Relay ]]>Session= 1800 or now - state.session.started >= 86400 if expired and not passive then state.session = Session.new() end if not passive then state.session.active = now end return true end return Session ]]>Uuid 4095 then now += 1 sequence = 0 end else sequence = random:NextInteger(0, 4095) end lastMillis = now return string.format("%08x-%04x-7%03x-%04x-%04x%04x%04x", math.floor(now / 65536), now % 65536, sequence, random:NextInteger(32768, 49151), random:NextInteger(0, 65535), random:NextInteger(0, 65535), random:NextInteger(0, 65535)) end return Uuid ]]>Wire:: by the contract's rule, nil when either part is unknown. function Wire.dedupeKey(source: any, id: any): string? if type(source) ~= "string" or type(id) ~= "string" then return nil end local system = string.lower(source) local trimmed = string.match(id, "^%s*(.-)%s*$") or "" if system == "" or trimmed == "" or #trimmed > 128 or string.find(system, "[^a-z0-9_]") then return nil end local kind = if system == "google_play" then "order" elseif system == "roblox" then "receipt" else "txn" return system .. ":" .. kind .. ":" .. trimmed end Wire.personProperties = { account_age_days = "account_age_days", membership_type = "membership_type" } Wire.deviceProperties = { "device_type", "languages" } local refused = { ["0"] = true, ["null"] = true, ["nil"] = true, ["none"] = true, ["undefined"] = true, ["nan"] = true, ["true"] = true, ["false"] = true, ["anonymous"] = true, ["anon"] = true, ["guest"] = true, ["unknown"] = true, ["distinct_id"] = true, ["distinctid"] = true, ["id"] = true, ["[object object]"] = true, ["email"] = true, ["not_authenticated"] = true, } function Wire.id(value: any): string? if type(value) ~= "string" and type(value) ~= "number" then return nil end local id = string.match(tostring(value), "^%s*(.-)%s*$") or "" if #id == 0 or #id > 200 or string.find(id, "[%z\1-\31\127]") or refused[string.lower(id)] then return nil end if string.find(id, "[%w%._%%%+%-]+@[%w%.%-]+%.[%a]+") then return nil end local valid = pcall(function() for _, point in utf8.codes(id) do if point >= 127 and point <= 159 then error("control character") end end end) if not valid then return nil end return id end local function normal(name: string): string local stripped = (string.match(name, "^%s*(.-)%s*$") or ""):gsub("^%$+", ""):gsub("%-", "_") return string.lower(stripped) end local secretNames = { jwt = true, otp = true, one_time_code = true, magic = true, magic_link = true, magiclink = true, passwd = true, pwd = true } local secretParams = { code = true, auth = true, key = true, api_key = true, apikey = true, session = true, sig = true } local function secretKey(name: string): boolean local n = normal(name) return string.sub(n, -5) == "token" or string.find(n, "password", 1, true) ~= nil or string.sub(n, -6) == "secret" or string.sub(n, -9) == "signature" or secretNames[n] == true end local function stripParams(text: string): (string, boolean) local parts: {string} = {} local delimiter = "" local pending: string? = nil local changed = false local start = 1 local function append(body: string) local name = string.match(body, "^%s*([%w_%.%[%]%$%%%-]+)=") if name and (secretKey(name) or secretParams[normal(name)]) then changed = true if delimiter == "" or delimiter == "?" or delimiter == "#" then pending = delimiter end else local sep = delimiter if pending ~= nil and delimiter == "&" then sep = pending end pending = nil table.insert(parts, sep .. body) end end for i = 1, #text do local char = string.sub(text, i, i) if char == "?" or char == "&" or char == "#" or char == ";" then append(string.sub(text, start, i - 1)) delimiter = char start = i + 1 end end append(string.sub(text, start)) return table.concat(parts), changed end function Wire.truncate(text: string, bytes: number): string local last = math.min(#text, math.max(0, math.floor(bytes))) while last > 0 and last < #text do local nextByte = string.byte(text, last + 1) if nextByte < 128 or nextByte >= 192 then break end last -= 1 end return string.sub(text, 1, last) end local function cleanText(value: string, digits: boolean): string value = Wire.truncate(value, 65536) local lower = string.lower(string.match(value, "^%s*(.*)$") or value) for _, scheme in { "mailto:", "tel:", "sms:", "callto:" } do if string.sub(lower, 1, #scheme) == scheme then return scheme end end local text = stripParams(value) local decoded = text for _ = 1, 5 do local previous = decoded decoded = string.gsub(decoded, "%%(%x%x)", function(hex) return string.char(tonumber(hex, 16) or 0) end) local stripped, changed = stripParams(decoded) if changed then text = stripped decoded = stripped end if decoded == previous then break end end text = string.gsub(text, "%%25(40)", "%%%1") text = string.gsub(text, "%%40", "@") text = string.gsub(text, "[%w%._%%%+%-]+@[%w%.%-]+", function(address) local trailing = string.match(address, "[%.%-]+$") or "" local bare = string.sub(address, 1, #address - #trailing) local tld = string.match(bare, "%.([%a]+)$") if tld and #tld >= 2 then return "[email]" .. trailing end return address end) text = string.gsub(text, "/Users/[^/%s]+/", "~/") text = string.gsub(text, "/home/[^/%s]+/", "~/") text = string.gsub(text, "[A-Za-z]:\\[Uu]sers\\[^\\%s]+\\", "~/") text = string.gsub(text, "Players%.[^%.%s]+%.", "Players.[player].") text = string.gsub(text, "Players/[^/%s]+/", "Players/[player]/") if digits then text = string.gsub(text, "%d%d%d%d%d%d%d%d%d+", "[number]") end return text end function Wire.clean(value: string): string return cleanText(value, true) end local privateKeys = { device_name = true, hardware_id = true, advertising_id = true, ip = true, ip_address = true, player_name = true, display_name = true } local identifierKeys = { product_id = true, transaction_id = true, place_id = true, source_place_id = true } function Wire.cleanValue(value: any): any local seen: {[any]: boolean} = {} local budget = 1000 local function visit(item: any, depth: number, keepDigits: boolean): any budget -= 1 if budget < 0 or depth > 8 then return nil end local kind = type(item) if kind == "string" then local text = cleanText(item, not keepDigits) return Wire.truncate(text, 8192) elseif kind == "boolean" then return item elseif kind == "number" then return if item == item and math.abs(item) < math.huge then item else nil elseif kind ~= "table" or seen[item] then return nil end seen[item] = true local out: {[any]: any} = {} local count = 0 for key, child in item do count += 1 if count > 100 or budget < 0 then break end if type(key) == "string" and #key <= 200 and not secretKey(key) and not privateKeys[normal(key)] then out[cleanText(key, false)] = visit(child, depth + 1, identifierKeys[key] == true) elseif type(key) == "number" and key >= 1 and key % 1 == 0 and key <= 100 then out[key] = visit(child, depth + 1, false) end end seen[item] = nil return out end return visit(value, 0, false) end function Wire.timestamp(): string local millis = DateTime.now().UnixTimestampMillis return os.date("!%Y-%m-%dT%H:%M:%S", math.floor(millis / 1000)) .. string.format(".%03dZ", millis % 1000) end function Wire.encode(value: any): string return HttpService:JSONEncode(value) end return Wire ]]>ModeClient\"']*", function(link: string) local scheme = string.lower(link:match("^[^:]+:") or "") if scheme == "mailto:" or scheme == "tel:" or scheme == "sms:" or scheme == "callto:" then return scheme end if link:find("://", 1, true) then return link:match("^[^?#]*") or "" end return link end) text = string.gsub(text, "[?&#;]?[%w_%-]+=[^%s&#;]*", function(segment: string) local name = segment:match("^[?&#;]?([%w_%-]+)=") or "" local key = string.lower(name):gsub("%-", "_") if key:sub(-5) == "token" or key:find("password", 1, true) or key:sub(-6) == "secret" or key:sub(-9) == "signature" or key == "code" or key == "auth" or key == "key" or key == "api_key" or key == "apikey" or key == "session" or key == "sig" or key == "jwt" or key == "otp" or key == "one_time_code" or key == "magic" or key == "magic_link" or key == "magiclink" or key == "passwd" or key == "pwd" then return "" end return segment end) text = text:gsub("[%w%._%%%+%-]+@[%w%.%-]+", "[email]") text = text:gsub("/Users/[^/%s]+/", "~/"):gsub("/home/[^/%s]+/", "~/") text = text:gsub("[A-Za-z]:\\[Uu]sers\\[^\\%s]+\\", "~/") text = text:gsub("Players%.[^%.%s]+%.", "Players.[player].") text = text:gsub("%d%d%d%d%d%d%d%d%d+", "[number]") local player = Players.LocalPlayer if player then text = replaceLiteral(text, player.Name) text = replaceLiteral(text, player.DisplayName) end local last = math.min(#text, maximumBytes) while last > 0 and last < #text do local nextByte = string.byte(text, last + 1) if nextByte < 128 or nextByte >= 192 then break end last -= 1 end return string.sub(text, 1, last) end local function send(payload: any): boolean if not alive then return false end local now = os.clock() while recent[1] and recent[1] <= now - 60 do table.remove(recent, 1) end -- Leave space for the next performance and device reports during an error loop. local maximum = if payload.kind == "error" then 6 else 10 if #recent >= maximum then return false end table.insert(recent, now) pcall(function() remote:FireServer(payload) end) return true end local function device() if remote:GetAttribute("ModeDevice") == false then return end local kind = "desktop" if VRService.VREnabled then kind = "vr" elseif GuiService:IsTenFootInterface() or (UserInputService.GamepadEnabled and not UserInputService.KeyboardEnabled and not UserInputService.TouchEnabled) then kind = "console" elseif UserInputService.TouchEnabled and not UserInputService.KeyboardEnabled then kind = "mobile" end local camera = workspace.CurrentCamera local size = if camera then camera.ViewportSize else Vector2.new(0, 0) send({kind = "device", device_type = kind, screen_width = size.X, screen_height = size.Y, locale = LocalizationService.RobloxLocaleId, load_ms = ReplicatedFirst:GetAttribute("ModeLoadMs")}) end device() watch(ReplicatedFirst:GetAttributeChangedSignal("ModeLoadMs"), function() send({kind = "load", load_ms = ReplicatedFirst:GetAttribute("ModeLoadMs")}) end) local samples: {number} = {} local started = os.clock() local frames, slow, frozen, maximum = 0, 0, 0, 0 local rng = Random.new() watch(RunService.RenderStepped, function(delta: number) if not alive or remote:GetAttribute("ModePerformance") == false or delta <= 0 or delta ~= delta then return end local ms = math.min(delta * 1000, 60000) frames += 1 maximum = math.max(maximum, ms) if ms > 33.3 then slow += 1 end if ms > 700 then frozen += 1 end -- A bounded reservoir keeps percentiles useful even at very high frame rates. if #samples < 4096 then table.insert(samples, ms) else local index = rng:NextInteger(1, frames) if index <= #samples then samples[index] = ms end end local elapsed = os.clock() - started if elapsed >= 60 then table.sort(samples) local function percentile(p: number): number return samples[math.max(1, math.ceil(#samples * p))] end send({kind = "performance", fps = frames / elapsed, fps_min = 1000 / maximum, frame_ms_p50 = percentile(0.5), frame_ms_p95 = percentile(0.95), frame_ms_p99 = percentile(0.99), frame_ms_max = maximum, frames = frames, interval_ms = math.floor(elapsed * 1000), slow_frames = slow, frozen_frames = frozen}) samples = {} started = os.clock() frames, slow, frozen, maximum = 0, 0, 0, 0 device() end end) if remote:GetAttribute("ModeErrors") ~= false then watch(ScriptContext.Error, function(message: string, stack: string) send({kind = "error", message = cleanError(message, 4096), stack = cleanError(stack, 16384)}) end) end watch(script.Destroying, function() alive = false for _, connection in connections do connection:Disconnect() end end) ]]>ModeLoad