@rbxts/scribe 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
@@ -0,0 +1,68 @@
1
+ --!strict
2
+ -- Actions add-ons offer to the Studio plugin, by add-on name.
3
+
4
+ local Addons = {}
5
+
6
+ export type Action = { Run: (args: any) -> any, Writes: boolean? }
7
+ export type Actions = { [string]: Action }
8
+
9
+ local registered: { [string]: { Actions: Actions, Token: {} } } = {}
10
+
11
+ -- Set as the server bundle is built; read through Scribe.GetProfileKeyPrefix, which must
12
+ -- not require the Server module.
13
+ local profileKeyPrefix = "PLAYER_"
14
+
15
+ function Addons.SetProfileKeyPrefix(prefix: string)
16
+ profileKeyPrefix = prefix
17
+ end
18
+
19
+ function Addons.ProfileKeyPrefix(): string
20
+ return profileKeyPrefix
21
+ end
22
+
23
+ --- Registers under `name`, replacing an earlier one; the returned remover ignores a later one.
24
+ function Addons.Register(name: string, actions: Actions): () -> ()
25
+ local token = {}
26
+ registered[name] = { Actions = actions, Token = token }
27
+ return function()
28
+ local current = registered[name]
29
+ if current ~= nil and current.Token == token then
30
+ registered[name] = nil
31
+ end
32
+ end
33
+ end
34
+
35
+ --- Every add-on's actions and whether each needs writes.
36
+ function Addons.List(): { [string]: { [string]: { Writes: boolean } } }
37
+ local out = {}
38
+ for name, registration in registered do
39
+ local summary = {}
40
+ for action, entry in registration.Actions do
41
+ summary[action] = { Writes = entry.Writes == true }
42
+ end
43
+ out[name] = summary
44
+ end
45
+ return out
46
+ end
47
+
48
+ --- Whether the action needs writes; nil when unregistered.
49
+ function Addons.Writes(name: string, action: string): boolean?
50
+ local registration = registered[name]
51
+ local entry = if registration then registration.Actions[action] else nil
52
+ return if entry then entry.Writes == true else nil
53
+ end
54
+
55
+ --- Runs one action; false with a reason when it is not registered.
56
+ function Addons.Invoke(name: string, action: string, args: any): (boolean, any)
57
+ local registration = registered[name]
58
+ if registration == nil then
59
+ return false, `no add-on named "{name}" is registered`
60
+ end
61
+ local entry = registration.Actions[action]
62
+ if entry == nil then
63
+ return false, `add-on "{name}" has no action "{action}"`
64
+ end
65
+ return true, entry.Run(args)
66
+ end
67
+
68
+ return Addons
@@ -0,0 +1,582 @@
1
+ --!strict
2
+ -- Mantissa/exponent numbers for values past 2^53. Trades precision for range: a value
3
+ -- carries exactly 15 significant digits at any magnitude, so `1e20 + 1 == 1e20`, and
4
+ -- anything that must be exact belongs in Scribe.Int. Stored as the two-element array
5
+ -- { mantissa, exponent }, normalized to either { 0, 0 } or 1 <= |mantissa| < 10, so
6
+ -- there is one stored form per value.
7
+
8
+ local Big = {}
9
+
10
+ export type Big = {
11
+ M: number, -- mantissa, 0 or 1 <= |M| < 10
12
+ E: number, -- exponent, an integer
13
+ }
14
+
15
+ -- Past this magnitude gap the smaller term cannot affect the sum at all.
16
+ local PRECISION_GAP = 18
17
+ -- Exponent ceiling set by the wire, not the double: the exponent rides a zigzag
18
+ -- varint, which doubles it, and the varint writer stops at 2^53. Saturating here
19
+ -- beats storing an infinity that fails the whole profile save.
20
+ local MAX_EXPONENT = 2 ^ 52
21
+ local MAX_INPUT_BYTES = 256
22
+
23
+ local SUFFIXES = {
24
+ "",
25
+ "K",
26
+ "M",
27
+ "B",
28
+ "T",
29
+ "Qa",
30
+ "Qi",
31
+ "Sx",
32
+ "Sp",
33
+ "Oc",
34
+ "No",
35
+ "Dc",
36
+ "UDc",
37
+ "DDc",
38
+ "TDc",
39
+ "QaDc",
40
+ "QiDc",
41
+ "SxDc",
42
+ "SpDc",
43
+ "OcDc",
44
+ "NoDc",
45
+ "Vg",
46
+ "UVg",
47
+ "DVg",
48
+ "TVg",
49
+ "QaVg",
50
+ "QiVg",
51
+ "SxVg",
52
+ "SpVg",
53
+ "OcVg",
54
+ "NoVg",
55
+ "Tg",
56
+ }
57
+
58
+ local BIG_MT = {}
59
+ BIG_MT.__index = BIG_MT
60
+
61
+ local function raw(m: number, e: number): Big
62
+ return (setmetatable({ M = m, E = e }, BIG_MT) :: any) :: Big
63
+ end
64
+
65
+ -- Pull a value back into the canonical 1 <= |M| < 10 window. log10 rather than a
66
+ -- divide loop, so a mantissa arriving as 1e300 costs the same as one arriving as 12.
67
+ local function normalize(m: number, e: number): Big
68
+ if m == 0 or m ~= m then
69
+ return raw(0, 0)
70
+ end
71
+ if m == math.huge or m == -math.huge then
72
+ -- Saturate rather than let an infinity into stored data; no JSON round trip
73
+ -- survives one.
74
+ return raw(if m > 0 then 1 else -1, 308)
75
+ end
76
+ local shift = math.floor(math.log10(math.abs(m)))
77
+ if shift ~= 0 then
78
+ if shift < -323 then
79
+ -- 10^shift is exactly 0 at shift <= -324, and m/0 is inf. Scale in two steps
80
+ -- so the divisor stays representable, but only here: splitting compounds two
81
+ -- roundings and drifts the mantissa off canonical form.
82
+ m = m * 1e300 / 10 ^ (shift + 300)
83
+ else
84
+ m /= 10 ^ shift
85
+ end
86
+ e += shift
87
+ end
88
+ -- Snap to 15 digits, or 100 - 30 and the literal 70 store different mantissas and
89
+ -- everything comparing mantissas exactly splits on it. Must run before the window
90
+ -- fixup below, which catches the 9.99...8 -> 10 promotion this can produce.
91
+ m = tonumber(string.format("%.15g", m)) :: number
92
+ -- log10 rounding can leave the mantissa a hair outside the window.
93
+ if math.abs(m) >= 10 then
94
+ m /= 10
95
+ e += 1
96
+ elseif math.abs(m) < 1 then
97
+ m *= 10
98
+ e -= 1
99
+ end
100
+ -- The exponent needs the same domain guard the mantissa gets above: a non-finite
101
+ -- exponent makes every save for the session fail, and the wire encoder's varint
102
+ -- loop over inf never terminates.
103
+ if e ~= e then
104
+ return raw(0, 0)
105
+ end
106
+ return raw(m, math.clamp(math.floor(e), -MAX_EXPONENT, MAX_EXPONENT))
107
+ end
108
+
109
+ Big.normalize = normalize
110
+
111
+ -- Distinguish literal zero from tonumber underflow in one pass.
112
+ local function isPlainZero(text: string): boolean
113
+ local first = string.byte(text, 1)
114
+ local start = if first == 43 or first == 45 then 2 else 1
115
+ local dot, digit = false, false
116
+ for i = start, #text do
117
+ local byte = string.byte(text, i)
118
+ if byte == 48 then
119
+ digit = true
120
+ elseif byte == 46 and not dot then
121
+ dot = true
122
+ else
123
+ return false
124
+ end
125
+ end
126
+ return digit
127
+ end
128
+
129
+ -- Accepts a Big, the stored { m, e } array, a plain number, or a string like
130
+ -- "1.5e100" or "1500". Returns nil for anything else, so callers can produce their
131
+ -- own error with the path in it.
132
+ function Big.from(value: any): Big?
133
+ local t = type(value)
134
+ if t == "number" then
135
+ if value ~= value or value == math.huge or value == -math.huge then
136
+ return nil
137
+ end
138
+ return normalize(value, 0)
139
+ end
140
+ if t == "table" then
141
+ -- Refuse a non-finite half rather than saturating, so the caller gets the normal
142
+ -- path-named write error.
143
+ local function finite(n: number): boolean
144
+ return n == n and n ~= math.huge and n ~= -math.huge
145
+ end
146
+ local asBig = value :: any
147
+ if type(asBig.M) == "number" and type(asBig.E) == "number" then
148
+ return if finite(asBig.M) and finite(asBig.E) then normalize(asBig.M, asBig.E) else nil
149
+ end
150
+ if type(asBig[1]) == "number" and type(asBig[2]) == "number" then
151
+ return if finite(asBig[1]) and finite(asBig[2]) then normalize(asBig[1], asBig[2]) else nil
152
+ end
153
+ return nil
154
+ end
155
+ if t ~= "string" or #(value :: string) > MAX_INPUT_BYTES then
156
+ return nil
157
+ end
158
+ local text = (value :: string):gsub("%s", "")
159
+ -- A zero result only counts when the text really is zero: tonumber underflows
160
+ -- "1e-400" to 0 exactly as it overflows "1e400" to inf. Both ends fall through to
161
+ -- the manual split below.
162
+ local plain = tonumber(text)
163
+ if
164
+ plain ~= nil
165
+ and plain == plain
166
+ and plain ~= math.huge
167
+ and plain ~= -math.huge
168
+ and (plain ~= 0 or isPlainZero(text))
169
+ then
170
+ return normalize(plain, 0)
171
+ end
172
+ -- Past either end, split the exponent off by hand.
173
+ local mantissaText, exponentText = string.match(text, "^([%+%-]?[%d%.]+)[eE]([%+%-]?%d+)$")
174
+ if mantissaText == nil then
175
+ return nil
176
+ end
177
+ local m = tonumber(mantissaText)
178
+ local e = tonumber(exponentText)
179
+ if m == nil or e == nil or m ~= m or e % 1 ~= 0 then
180
+ return nil
181
+ end
182
+ return normalize(m, e)
183
+ end
184
+
185
+ -- The persisted shape: a two-element array, not the metatable-carrying object.
186
+ function Big.toStored(a: Big): { number }
187
+ return { a.M, a.E }
188
+ end
189
+
190
+ function Big.isBig(value: any): boolean
191
+ return type(value) == "table" and getmetatable(value :: any) == BIG_MT
192
+ end
193
+
194
+ function Big.add(a: Big, b: Big): Big
195
+ if a.M == 0 then
196
+ return b
197
+ end
198
+ if b.M == 0 then
199
+ return a
200
+ end
201
+ local high, low = a, b
202
+ if b.E > a.E then
203
+ high, low = b, a
204
+ end
205
+ local gap = high.E - low.E
206
+ if gap > PRECISION_GAP then
207
+ return high -- the smaller term cannot move a digit we can represent
208
+ end
209
+ return normalize(high.M + low.M / 10 ^ gap, high.E)
210
+ end
211
+
212
+ function Big.negate(a: Big): Big
213
+ return raw(-a.M, a.E)
214
+ end
215
+
216
+ function Big.sub(a: Big, b: Big): Big
217
+ return Big.add(a, Big.negate(b))
218
+ end
219
+
220
+ function Big.mul(a: Big, b: Big): Big
221
+ if a.M == 0 or b.M == 0 then
222
+ return raw(0, 0)
223
+ end
224
+ return normalize(a.M * b.M, a.E + b.E)
225
+ end
226
+
227
+ function Big.div(a: Big, b: Big): Big?
228
+ if b.M == 0 then
229
+ return nil -- the caller decides whether that is an error or a clamp
230
+ end
231
+ if a.M == 0 then
232
+ return raw(0, 0)
233
+ end
234
+ return normalize(a.M / b.M, a.E - b.E)
235
+ end
236
+
237
+ -- -1, 0, or 1. Sign first, then magnitude, so a comparison never has to subtract.
238
+ function Big.compare(a: Big, b: Big): number
239
+ if a.M == 0 and b.M == 0 then
240
+ return 0
241
+ end
242
+ local aNeg = a.M < 0
243
+ local bNeg = b.M < 0
244
+ if aNeg ~= bNeg then
245
+ return if aNeg then -1 else 1
246
+ end
247
+ if a.M == 0 then
248
+ return if bNeg then 1 else -1
249
+ end
250
+ if b.M == 0 then
251
+ return if aNeg then -1 else 1
252
+ end
253
+ local flip = if aNeg then -1 else 1
254
+ if a.E ~= b.E then
255
+ return if a.E > b.E then flip else -flip
256
+ end
257
+ if a.M == b.M then
258
+ return 0
259
+ end
260
+ return if a.M > b.M then 1 else -1
261
+ end
262
+
263
+ -- Lossy on purpose: everything past the double range saturates to inf, which is
264
+ -- what a caller asking for a plain number has to accept.
265
+ function Big.toNumber(a: Big): number
266
+ if a.M == 0 then
267
+ return 0
268
+ end
269
+ return a.M * 10 ^ a.E
270
+ end
271
+
272
+ -- The mantissa's 15 significant digits as text, with the decimal point's position
273
+ -- returned rather than applied, so the renders below move the point by counting
274
+ -- characters and never round a second time through a double. `%.14f` is exact because
275
+ -- normalize already snapped the mantissa to 15 digits. Returns the sign, the digits, and
276
+ -- how many of them belong left of the point: sign .. "0." .. digits .. "e" .. point.
277
+ local function significand(a: Big): (string, string, number)
278
+ local body = string.format("%.14f", math.abs(a.M))
279
+ local whole = string.match(body, "^%d+") :: string
280
+ return (if a.M < 0 then "-" else ""), whole .. string.sub(body, #whole + 2), a.E + #whole
281
+ end
282
+
283
+ -- Under this exponent a plain decimal is more leading zeros than digits. Matches where
284
+ -- Luau's own tostring switches to exponent form, which the branch below delegates to.
285
+ local MIN_DECIMAL_EXPONENT = -6
286
+
287
+ -- Place the decimal point inside (or outside) a digit string, padding with the zeros
288
+ -- the point ran past. Returns the halves separately because only the fractional one
289
+ -- may have its trailing zeros trimmed.
290
+ local function split(digits: string, point: number): (string, string)
291
+ if point <= 0 then
292
+ return "0", string.rep("0", -point) .. digits
293
+ elseif point >= #digits then
294
+ return digits .. string.rep("0", point - #digits), ""
295
+ end
296
+ return string.sub(digits, 1, point), string.sub(digits, point + 1)
297
+ end
298
+
299
+ function Big.toString(a: Big): string
300
+ if a.M == 0 then
301
+ return "0"
302
+ end
303
+ -- Below the precision limit a plain decimal is exact and far more readable.
304
+ if a.E < 15 and a.E >= MIN_DECIMAL_EXPONENT then
305
+ local sign, digits, point = significand(a)
306
+ local whole, fraction = split(digits, point)
307
+ -- Only the fraction is trimmed: a whole number's trailing zeros are the value.
308
+ fraction = (fraction:gsub("0+$", ""))
309
+ return if fraction == "" then sign .. whole else `{sign}{whole}.{fraction}`
310
+ end
311
+ if a.E < 0 and a.E >= -307 then
312
+ return tostring(Big.toNumber(a))
313
+ end
314
+ -- Four decimals, not the full 15 the branch above renders: out here the mantissa is
315
+ -- usually a reconstruction (a leaderboard key unpacks at SigFigs = 12), so the extra
316
+ -- digits would only show the packing's rounding error. %.4f can round 9.99998 up to
317
+ -- "10", outside the canonical window, so carry that into the exponent.
318
+ local mantissa, exponent = string.format("%.4f", a.M), a.E
319
+ if mantissa == "10.0000" or mantissa == "-10.0000" then
320
+ mantissa = if a.M < 0 then "-1.0000" else "1.0000"
321
+ exponent += 1
322
+ end
323
+ return `{(mantissa:gsub("%.?0+$", ""))}e{exponent}`
324
+ end
325
+
326
+ --- Replace the suffix table `toShort` renders with.
327
+ ---
328
+ --- Overridable because the conventions diverge past "T": plenty of idle games run
329
+ --- aa, ab, ac rather than Qa, Qi, Sx. Index 1 is the units tier and must be empty,
330
+ --- because it is what renders a plain number unchanged.
331
+ function Big.SetSuffixes(suffixes: { string }): ()
332
+ if type(suffixes) ~= "table" or #suffixes == 0 then
333
+ error("Scribe: suffixes must be a non-empty list of strings", 3)
334
+ end
335
+ for index, suffix in suffixes do
336
+ if type(suffix) ~= "string" then
337
+ error(`Scribe: suffix {index} must be a string, got {typeof(suffix)}`, 3)
338
+ end
339
+ end
340
+ if suffixes[1] ~= "" then
341
+ error('Scribe: the first suffix is the units tier and must be ""', 3)
342
+ end
343
+ SUFFIXES = table.clone(suffixes)
344
+ end
345
+
346
+ function Big.toShort(a: Big, decimals: number?): string
347
+ if a.M == 0 then
348
+ return "0"
349
+ end
350
+ local places = decimals or 2
351
+ if a.E < 3 then
352
+ -- Past the double's low end toNumber saturates to 0, which would render a real
353
+ -- value as "0".
354
+ if a.E < -307 then
355
+ return Big.toString(a)
356
+ end
357
+ local n = Big.toNumber(a)
358
+ if n % 1 == 0 then
359
+ return string.format("%.0f", n)
360
+ end
361
+ local text = string.format(`%.{places}f`, n)
362
+ -- A value smaller than the requested precision formats as a literal zero, so a
363
+ -- real balance would render as "0.00". Test the rendered text rather than the
364
+ -- exponent: that keeps 0.00999 rounding to "0.01" and overrides only a render
365
+ -- with no digit left in it.
366
+ if string.match(text, "[1-9]") == nil then
367
+ return Big.toString(a)
368
+ end
369
+ return text
370
+ end
371
+ local tier = math.floor(a.E / 3)
372
+ local suffix = SUFFIXES[tier + 1]
373
+ if suffix == nil then
374
+ return Big.toString(a)
375
+ end
376
+ local scaled = a.M * 10 ^ (a.E - tier * 3)
377
+ return string.format(`%.{places}f{suffix}`, scaled)
378
+ end
379
+
380
+ -- Coerce an operand of an arithmetic metamethod, erroring at level 3 so the blame
381
+ -- lands on the line holding the operator rather than inside this module.
382
+ --
383
+ -- __lt/__le are not routed through this: Luau rejects a mixed pair before the
384
+ -- metamethod runs and requires both sides to carry this metatable, so their `Big.from`
385
+ -- cannot fail.
386
+ local function operand(value: any, verb: string): Big
387
+ local coerced = Big.from(value)
388
+ if coerced == nil then
389
+ error(
390
+ `Scribe: cannot {verb} a Scribe.Big by a {type(value)}; expected a number, numeric string, or Scribe.Big`,
391
+ 3
392
+ )
393
+ end
394
+ return coerced
395
+ end
396
+
397
+ BIG_MT.__add = function(a, b)
398
+ return Big.add(operand(a, "add to"), operand(b, "add to"))
399
+ end
400
+ BIG_MT.__sub = function(a, b)
401
+ return Big.sub(operand(a, "subtract from"), operand(b, "subtract from"))
402
+ end
403
+ BIG_MT.__mul = function(a, b)
404
+ return Big.mul(operand(a, "multiply"), operand(b, "multiply"))
405
+ end
406
+ BIG_MT.__div = function(a, b)
407
+ -- `Big.div` returns nil on a zero divisor so its callers can choose what that means;
408
+ -- the operator has nobody to hand that choice to, so it raises like Divide does.
409
+ local result = Big.div(operand(a, "divide"), operand(b, "divide"))
410
+ if result == nil then
411
+ error("Scribe: divided a Scribe.Big by zero", 2)
412
+ end
413
+ return result
414
+ end
415
+ BIG_MT.__unm = function(a)
416
+ return Big.negate(a)
417
+ end
418
+ BIG_MT.__eq = function(a, b)
419
+ return Big.compare(a, b) == 0
420
+ end
421
+ BIG_MT.__lt = function(a, b)
422
+ return Big.compare(Big.from(a) :: Big, Big.from(b) :: Big) < 0
423
+ end
424
+ BIG_MT.__le = function(a, b)
425
+ return Big.compare(Big.from(a) :: Big, Big.from(b) :: Big) <= 0
426
+ end
427
+ BIG_MT.__tostring = function(a)
428
+ return Big.toString(a)
429
+ end
430
+
431
+ -- Named equivalents of the operators for explicit arithmetic and method chaining.
432
+ -- These return values; they never write a Scribe field. Reuse the operator bodies
433
+ -- so coercion and division errors agree.
434
+ -- Returns a new sum without changing the stored field.
435
+ function BIG_MT.Add(self: Big, other: Big | number | string): Big
436
+ return BIG_MT.__add(self, other)
437
+ end
438
+
439
+ -- Returns a new difference without changing the stored field.
440
+ function BIG_MT.Subtract(self: Big, other: Big | number | string): Big
441
+ return BIG_MT.__sub(self, other)
442
+ end
443
+
444
+ -- Returns a new product without changing the stored field.
445
+ function BIG_MT.Multiply(self: Big, other: Big | number | string): Big
446
+ return BIG_MT.__mul(self, other)
447
+ end
448
+
449
+ -- Returns a new quotient; division by zero errors.
450
+ function BIG_MT.Divide(self: Big, other: Big | number | string): Big
451
+ return BIG_MT.__div(self, other)
452
+ end
453
+
454
+ -- Returns the opposite value without changing the stored field.
455
+ function BIG_MT.Negate(self: Big): Big
456
+ return BIG_MT.__unm(self)
457
+ end
458
+
459
+ -- Unlike Luau's comparison operators, named comparison can accept a number or
460
+ -- numeric string without requiring both operands to carry the Big metatable.
461
+ -- Returns -1, 0, or 1 after validating the other operand.
462
+ function BIG_MT.Compare(self: Big, other: Big | number | string): number
463
+ return Big.compare(self, operand(other, "compare"))
464
+ end
465
+
466
+ -- Compares numeric value, accepting numbers and numeric strings.
467
+ function BIG_MT.Equals(self: Big, other: Big | number | string): boolean
468
+ return BIG_MT.Compare(self, other) == 0
469
+ end
470
+
471
+ -- Integer exponentiation carries the mantissa in two doubles (Dekker) so the 15-digit snap
472
+ -- runs once, at the end. Squaring over Big.mul instead compounds one rounding per pass and
473
+ -- produces wrong leaderboard ranking keys well before n = 1000.
474
+ --
475
+ -- Both operands stay in [1, 10) throughout this schedule, so every product lands in
476
+ -- [1, 100) and the window fixup is at most one divide by ten; a general rescale loop would
477
+ -- be dead code for the only caller.
478
+ local SPLIT = 134217729 -- 2^27 + 1, the Dekker splitter for a 53-bit significand
479
+
480
+ -- The exact product of two doubles as an unevaluated sum (hi + lo).
481
+ local function twoProd(x: number, y: number): (number, number)
482
+ local p = x * y
483
+ local cx = SPLIT * x
484
+ local hx = cx - (cx - x)
485
+ local lx = x - hx
486
+ local cy = SPLIT * y
487
+ local hy = cy - (cy - y)
488
+ local ly = y - hy
489
+ return p, ((hx * hy - p) + hx * ly + lx * hy) + lx * ly
490
+ end
491
+
492
+ local function ddMul(ah: number, al: number, bh: number, bl: number): (number, number)
493
+ local p, e = twoProd(ah, bh)
494
+ e += ah * bl + al * bh
495
+ local s = p + e
496
+ local bb = s - p
497
+ return s, (p - (s - bb)) + (e - bb)
498
+ end
499
+
500
+ -- Divide a double-double by ten. Ten is exact, so the only error is the final renormalize.
501
+ local function ddTenth(ah: number, al: number): (number, number)
502
+ local q1 = ah / 10
503
+ local p, e = twoProd(q1, 10)
504
+ local q2 = ((ah - p) + (al - e)) / 10
505
+ local s = q1 + q2
506
+ local bb = s - q1
507
+ return s, (q1 - (s - bb)) + (q2 - bb)
508
+ end
509
+
510
+ -- Past 2^53 an exponent is not an exact integer, so the squaring schedule cannot iterate it.
511
+ local MAX_POW_EXPONENT = 2 ^ 53
512
+
513
+ -- Non-negative integer exponents only, and the guard is not optional: the schedule cannot
514
+ -- detect a bad one and silently returns 9 for 3^2.5 and 1 for 3^-3. Returns nil rather than
515
+ -- raising, matching div, so the caller decides. 0^0 is 1.
516
+ function Big.pow(a: Big, n: number): Big?
517
+ if type(n) ~= "number" or n % 1 ~= 0 or n < 0 or n > MAX_POW_EXPONENT then
518
+ return nil
519
+ end
520
+ local rh, rl, re = 1, 0, 0
521
+ local bh, bl, be = a.M, 0, a.E
522
+ local k = n
523
+ while k > 0 do
524
+ if k % 2 == 1 then
525
+ local h, l = ddMul(rh, rl, bh, bl)
526
+ re += be
527
+ if math.abs(h) >= 10 then
528
+ h, l = ddTenth(h, l)
529
+ re += 1
530
+ end
531
+ rh, rl = h, l
532
+ end
533
+ k = math.floor(k / 2)
534
+ if k > 0 then
535
+ local h, l = ddMul(bh, bl, bh, bl)
536
+ be += be
537
+ if math.abs(h) >= 10 then
538
+ h, l = ddTenth(h, l)
539
+ be += 1
540
+ end
541
+ bh, bl = h, l
542
+ end
543
+ end
544
+ -- Only the high part: the double-double invariant is |lo| <= ulp(hi)/2, so rh + rl is rh.
545
+ -- Exiting through normalize applies the 15-digit snap and the exponent clamp, so pow
546
+ -- saturates exactly as mul does.
547
+ return normalize(rh, re)
548
+ end
549
+
550
+ -- Base-10 logarithm; `a.E` is already the exact integer part and this adds the fraction.
551
+ -- Total and unguarded on purpose: 0 gives -inf and a negative value nan, matching the
552
+ -- same call on a plain number, so a fresh {0, 0} balance needs no nil check at the call
553
+ -- site. Precision decays as E grows: the integer part and the fraction share 53 bits.
554
+ function Big.log10(a: Big): number
555
+ return a.E + math.log10(a.M)
556
+ end
557
+
558
+ -- Returns a new power; the exponent must be a non-negative integer.
559
+ function BIG_MT.Pow(self: Big, n: number): Big
560
+ local result = Big.pow(self, n)
561
+ if result == nil then
562
+ error(`Scribe: Pow needs a non-negative integer exponent no larger than 2^53, got {tostring(n)}`, 2)
563
+ end
564
+ return result
565
+ end
566
+
567
+ -- Returns the base-10 logarithm as a plain number.
568
+ function BIG_MT.Log10(self: Big): number
569
+ return Big.log10(self)
570
+ end
571
+
572
+ -- Formats a compact suffix or scientific-notation label.
573
+ function BIG_MT.Short(self: Big, decimals: number?): string
574
+ return Big.toShort(self, decimals)
575
+ end
576
+
577
+ -- Converts to a plain number, losing precision or overflowing when necessary.
578
+ function BIG_MT.ToNumber(self: Big): number
579
+ return Big.toNumber(self)
580
+ end
581
+
582
+ return Big