@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
package/src/init.luau ADDED
@@ -0,0 +1,2231 @@
1
+ --!strict
2
+ -- Scribe: persistent, fully-typed, automatically-replicated player data for Roblox
3
+ -- Luau, built on ProfileStore. One shared module declares the template and options and
4
+ -- returns { Server, Client }. The typed accessor tree needs the new Luau type solver;
5
+ -- without it the library still runs correctly (use `.Raw` as the untyped escape hatch).
6
+
7
+ local RunService = game:GetService("RunService")
8
+
9
+ local Types = require(script.Types)
10
+ local Util = require(script.Internal.Util)
11
+ local Marker = require(script.Internal.Marker)
12
+ local Template = require(script.Internal.Template)
13
+ local Log = require(script.Internal.Log)
14
+ local Metrics = require(script.Internal.Metrics)
15
+ local Health = require(script.Internal.Health)
16
+ local Addons = require(script.Internal.Addons)
17
+ local Config = require(script.Internal.Config)
18
+ local Budget = require(script.Internal.Budget)
19
+ local LeaderboardDiagnostics = require(script.Internal.LeaderboardDiagnostics)
20
+ -- Named BigMath because `Scribe.Big` is the declarator; this is the arithmetic.
21
+ local BigMath = require(script.Internal.Big)
22
+ -- Types only. Both are leaf modules with no services, so this is safe on the client.
23
+ local Exchange = require(script.Internal.Exchange)
24
+ local ExchangeLegType = require(script.Internal.ExchangeLeg)
25
+
26
+ export type ScribeTransport = Types.ScribeTransport
27
+ export type Op = Types.Op
28
+ export type LogEntry = Types.LogEntry
29
+ export type LogCode = Types.LogCode
30
+ export type LogLevel = Types.LogLevel
31
+ export type LogSinkOptions = Types.LogSinkOptions
32
+ export type LogCategory = Types.LogCategory
33
+ export type Status = Types.Status
34
+ export type LoadPhase = Types.LoadPhase
35
+ export type SaveInfo = Types.SaveInfo
36
+ export type BudgetSnapshot = Budget.Snapshot
37
+ export type ExchangeLeg = ExchangeLegType.Leg
38
+ export type OpenExchange = Exchange.OpenExchange
39
+ export type OpenLeg = Exchange.OpenLeg
40
+ --- One entry of the `Exchangeable` allowlist. See the Exchange guide for the rules.
41
+ export type ExchangeableSpec = {
42
+ Path: { string },
43
+ Kind: "Key" | "Qty" | "Stack",
44
+ Count: string?,
45
+ Identity: { string }?,
46
+ Ignore: { string }?,
47
+ }
48
+ export type LifecycleReason = Types.LifecycleReason
49
+ export type RequestReason = Types.RequestReason
50
+ export type PurchaseReason = Types.PurchaseReason
51
+ export type GiftReason = Types.GiftReason
52
+ export type ProductState = Types.ProductState
53
+ export type LeaderboardEntry = Types.LeaderboardEntry
54
+ export type LeaderboardStatus = Types.LeaderboardStatus
55
+ export type LeaderboardStatusInfo = Types.LeaderboardStatusInfo
56
+ export type LeaderboardSnapshotEntry = Types.LeaderboardSnapshotEntry
57
+ export type PassConfig = Types.PassConfig
58
+ export type PurchaseFilter = Types.PurchaseFilter
59
+ export type EconomyMeta = Types.EconomyMeta
60
+ export type EconomyConfig = Types.EconomyConfig
61
+ export type EconomyCurrencyConfig = Types.EconomyCurrencyConfig
62
+ export type EconomyFieldSpec = Types.EconomyFieldSpec
63
+ export type EconomyLogFn = Types.EconomyLogFn
64
+ -- LeaderboardConfig<T>, ProductConfig<T> and PurchaseSpec<T> are defined after the
65
+ -- type functions below, which they need to derive their paths from the template.
66
+
67
+ --------------------------------------------------------------------------------
68
+ -- The type function: walks the template type at type-check time and produces
69
+ -- the recursive typed accessor tree.
70
+ --------------------------------------------------------------------------------
71
+
72
+ -- selene: allow(undefined_variable) -- `types` is the type-function runtime library
73
+ export type function ValueType(T)
74
+ local ts = types
75
+
76
+ local nilType = ts.singleton(nil)
77
+
78
+ local function optional(t: type): type
79
+ return ts.unionof(t, nilType)
80
+ end
81
+
82
+ local anyType = ts.any
83
+ local optBool = optional(ts.boolean)
84
+ local optNumber = optional(ts.number)
85
+
86
+ local function fn(params: { type }, rets: { type }): type
87
+ return ts.newfunction({ head = params }, { head = rets })
88
+ end
89
+
90
+ local disconnectType = fn({}, {})
91
+
92
+ local function widen(t: type): type
93
+ if t:is("singleton") then
94
+ local value = t:value()
95
+ if type(value) == "boolean" then
96
+ return ts.boolean
97
+ elseif type(value) == "string" then
98
+ return ts.string
99
+ end
100
+ end
101
+ return t
102
+ end
103
+
104
+ -- Recursion budget: a self-referential template type would blow the type-function
105
+ -- stack, degrading the whole accessor tree to an error type. One past
106
+ -- Util.MAX_VALUE_DEPTH, so it can never bind before the runtime does and only a
107
+ -- cyclic type is cut off. Matches StatPathsType's cap below.
108
+ local MAX_DEPTH = 25
109
+ local MAX_CHILD_UNION = 12
110
+
111
+ -- One shared Scribe.Big type for the whole template. Luau resolves `<` and `<=`
112
+ -- by metatable identity rather than by shape, so a fresh type per field leaves
113
+ -- two big fields in the same template incomparable.
114
+ local bigType: type? = nil
115
+ local function bigValueType(): type
116
+ if bigType ~= nil then
117
+ return bigType
118
+ end
119
+ -- The shape Get returns; arithmetic resolves through the metatable.
120
+ local bigProps: { [type]: type } = {}
121
+ bigProps[ts.singleton("M")] = ts.number
122
+ bigProps[ts.singleton("E")] = ts.number
123
+ bigProps[ts.singleton("Short")] = ts.newfunction(
124
+ { head = { ts.any, ts.unionof(ts.number, ts.singleton(nil)) } },
125
+ { head = { ts.string } }
126
+ )
127
+ bigProps[ts.singleton("ToNumber")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
128
+ bigProps[ts.singleton("Log10")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
129
+
130
+ -- The metamethods must be typed over this table with its metatable, so the table
131
+ -- is built first and the metatable attached after. Typed over a metatable-less
132
+ -- copy they describe a different type from the one Get returns, and every
133
+ -- operator becomes an error. Operands widen to the union those methods accept,
134
+ -- because BIG_MT resolves both sides through Big.from.
135
+ local big = ts.newtable(bigProps, nil, nil)
136
+ -- Pow returns the big type itself, so it cannot go in bigProps: ts.newtable
137
+ -- snapshots that table. setproperty on the live type object instead.
138
+ big:setproperty(ts.singleton("Pow"), ts.newfunction({ head = { big, ts.number } }, { head = { big } }))
139
+ local operand = ts.unionof(big, ts.number, ts.string)
140
+ local binaryMethod = ts.newfunction({ head = { big, operand } }, { head = { big } })
141
+ for _, name in { "Add", "Subtract", "Multiply", "Divide" } do
142
+ big:setproperty(ts.singleton(name), binaryMethod)
143
+ end
144
+ big:setproperty(ts.singleton("Negate"), ts.newfunction({ head = { big } }, { head = { big } }))
145
+ big:setproperty(ts.singleton("Compare"), ts.newfunction({ head = { big, operand } }, { head = { ts.number } }))
146
+ big:setproperty(ts.singleton("Equals"), ts.newfunction({ head = { big, operand } }, { head = { ts.boolean } }))
147
+ local arith = ts.newfunction({ head = { operand, operand } }, { head = { big } })
148
+ local cmp = ts.newfunction({ head = { operand, operand } }, { head = { ts.boolean } })
149
+ local mtProps: { [type]: type } = {}
150
+ mtProps[ts.singleton("__add")] = arith
151
+ mtProps[ts.singleton("__sub")] = arith
152
+ mtProps[ts.singleton("__mul")] = arith
153
+ mtProps[ts.singleton("__div")] = arith
154
+ mtProps[ts.singleton("__unm")] = ts.newfunction({ head = { big } }, { head = { big } })
155
+ mtProps[ts.singleton("__lt")] = cmp
156
+ mtProps[ts.singleton("__le")] = cmp
157
+ -- __eq only ever runs with two tables, so it stays narrow.
158
+ mtProps[ts.singleton("__eq")] = ts.newfunction({ head = { big, big } }, { head = { ts.boolean } })
159
+ mtProps[ts.singleton("__tostring")] = ts.newfunction({ head = { big } }, { head = { ts.string } })
160
+ big:setmetatable(ts.newtable(mtProps, nil, nil))
161
+ bigType = big
162
+ return big
163
+ end
164
+
165
+ -- Big, Flags and SetOf carry their label in the metatable rather than in a field,
166
+ -- so each declarator's own type is already the read shape. See BigValue.
167
+ local function hasMarker(t: type, name: string): boolean
168
+ local mt = t:metatable()
169
+ return mt ~= nil and mt:readproperty(ts.singleton(name)) ~= nil
170
+ end
171
+
172
+ local function isBigMarker(t: type): boolean
173
+ return hasMarker(t, "__scribeBig")
174
+ end
175
+
176
+ -- Timed and ServerOnly read back as a bare T, which may not be a table, so unlike
177
+ -- the branded declarators their label has to be an ordinary field and a
178
+ -- whole-subtree read strips it here. This only ever removes a wrapper, which is
179
+ -- what keeps it cheap enough to run over every node.
180
+ -- Inputs are read-only so a narrower caller type is accepted; a mutable property is
181
+ -- invariant. Indexers are copied as is, since the runtime cannot make one read-only.
182
+ local readOnlyCache: { [type]: type } = {}
183
+ local function readOnlyDeep(t: type, depth: number): type
184
+ if depth > MAX_DEPTH or not t:is("table") then
185
+ return t
186
+ end
187
+ local cached = readOnlyCache[t]
188
+ if cached ~= nil then
189
+ return cached
190
+ end
191
+ local indexer = t:indexer()
192
+ local spec = if indexer ~= nil
193
+ then { index = indexer.index, readresult = indexer.readresult, writeresult = indexer.writeresult }
194
+ else nil
195
+ local out = ts.newtable(nil, spec, t:metatable())
196
+ readOnlyCache[t] = out
197
+ for key, prop in t:properties() do
198
+ local childType = prop.read or prop.write
199
+ if childType ~= nil then
200
+ out:setreadproperty(key, readOnlyDeep(childType, depth + 1))
201
+ end
202
+ end
203
+ return out
204
+ end
205
+
206
+ local unwrapCache: { [type]: type } = {}
207
+ local function unwrapWrappers(t: type, depth: number): type
208
+ if depth > MAX_DEPTH or not t:is("table") then
209
+ return t
210
+ end
211
+ local cached = unwrapCache[t]
212
+ if cached ~= nil then
213
+ return cached
214
+ end
215
+ local function memo(result: type): type
216
+ unwrapCache[t] = result
217
+ return result
218
+ end
219
+ local timed = t:readproperty(ts.singleton("__scribeTimed"))
220
+ if timed ~= nil then
221
+ return memo(unwrapWrappers(widen(timed), depth + 1))
222
+ end
223
+ local serverOnly = t:readproperty(ts.singleton("__scribeServerOnly"))
224
+ if serverOnly ~= nil then
225
+ return memo(unwrapWrappers(widen(serverOnly), depth + 1))
226
+ end
227
+ local derived = t:readproperty(ts.singleton("__scribeDerived"))
228
+ if derived ~= nil then
229
+ return memo(unwrapWrappers(widen(derived), depth + 1))
230
+ end
231
+ -- A marker cannot hide under one of the branded declarators: their metatable
232
+ -- brand means the shape below them is already the read shape.
233
+ if hasMarker(t, "__scribeBig") or hasMarker(t, "__scribeFlags") or hasMarker(t, "__scribeSet") then
234
+ return memo(t)
235
+ end
236
+ local props: { [type]: type } = {}
237
+ local rebuilt = false
238
+ for key, prop in t:properties() do
239
+ local childType = prop.read or prop.write
240
+ if childType ~= nil then
241
+ local mapped = unwrapWrappers(childType, depth + 1)
242
+ props[key] = mapped
243
+ if mapped ~= childType then
244
+ rebuilt = true
245
+ end
246
+ end
247
+ end
248
+ local spec: { index: type, readresult: type, writeresult: type }? = nil
249
+ local indexer = t:indexer()
250
+ if indexer ~= nil then
251
+ local mapped = unwrapWrappers(indexer.readresult, depth + 1)
252
+ spec = { index = indexer.index, readresult = mapped, writeresult = mapped }
253
+ if mapped ~= indexer.readresult then
254
+ rebuilt = true
255
+ end
256
+ end
257
+ if not rebuilt then
258
+ return memo(t)
259
+ end
260
+ return memo(ts.newtable(props, spec, nil))
261
+ end
262
+
263
+ -- A canonical key for a subtree, so two identical subtrees are built once. A template
264
+ -- repeats declarators heavily and Luau interns none of them.
265
+ --
266
+ -- Returns nil for anything it cannot describe exactly, and nil means do not cache.
267
+ -- tostring() is not the key: it truncates past roughly 25 fields, so two records
268
+ -- sharing a long prefix would collide. Only `table` and `singleton` are probed,
269
+ -- because an unknown tag fails the whole type function.
270
+ local opaqueIds: { [type]: string } = {}
271
+ local opaqueCount = 0
272
+ local signatureOf: (type, number, { [type]: boolean }) -> string?
273
+ signatureOf = function(t: type, depth: number, seen: { [type]: boolean }): string?
274
+ -- A cut-short walk or a cycle cannot be keyed.
275
+ if depth > MAX_DEPTH + 2 or seen[t] then
276
+ return nil
277
+ end
278
+ if t:is("singleton") then
279
+ local value = t:value()
280
+ return `s<{type(value)}:{tostring(value)}>`
281
+ end
282
+ if t:is("table") then
283
+ seen[t] = true
284
+ local function sub(child: type?): string?
285
+ if child == nil then
286
+ return "-"
287
+ end
288
+ return signatureOf(child, depth + 1, seen)
289
+ end
290
+ local parts: { string } = {}
291
+ for key, prop in t:properties() do
292
+ -- Signed separately: a field can differ in only one.
293
+ local keySig, readSig, writeSig = sub(key), sub(prop.read), sub(prop.write)
294
+ if keySig == nil or readSig == nil or writeSig == nil then
295
+ seen[t] = nil
296
+ return nil
297
+ end
298
+ table.insert(parts, `{keySig}={readSig}|{writeSig}`)
299
+ end
300
+ -- Sorted, because property iteration order is not guaranteed.
301
+ table.sort(parts)
302
+ local indexerSig = "-"
303
+ local indexer = t:indexer()
304
+ if indexer ~= nil then
305
+ local i, r, w = sub(indexer.index), sub(indexer.readresult), sub(indexer.writeresult)
306
+ if i == nil or r == nil or w == nil then
307
+ seen[t] = nil
308
+ return nil
309
+ end
310
+ indexerSig = `{i}=>{r}|{w}`
311
+ end
312
+ -- The metatable carries the declarator brands, which pick the accessor.
313
+ local metaSig = "-"
314
+ local mt = t:metatable()
315
+ if mt ~= nil then
316
+ local m = sub(mt)
317
+ if m == nil then
318
+ seen[t] = nil
319
+ return nil
320
+ end
321
+ metaSig = m
322
+ end
323
+ seen[t] = nil
324
+ return `t<{table.concat(parts, ",")};i:{indexerSig};m:{metaSig}>`
325
+ end
326
+ -- Not a table, so its rendering is its structure and is short enough not to
327
+ -- truncate.
328
+ local rendered = tostring(t)
329
+ if #rendered <= 64 then
330
+ return `p<{rendered}>`
331
+ end
332
+ -- Anything longer falls back to identity: exact, but never shared.
333
+ local id = opaqueIds[t]
334
+ if id == nil then
335
+ opaqueCount += 1
336
+ id = `o<{opaqueCount}>`
337
+ opaqueIds[t] = id
338
+ end
339
+ return id
340
+ end
341
+
342
+ local buildUncached: (type, boolean, number) -> type
343
+ local buildCache: { [number]: { [string]: type } } = {}
344
+ local function build(rawType: type, isRoot: boolean, depth: number): type
345
+ -- Roots are never cached: isRoot changes what is emitted.
346
+ if isRoot then
347
+ return buildUncached(rawType, isRoot, depth)
348
+ end
349
+ local key = signatureOf(rawType, 0, {})
350
+ if key == nil then
351
+ return buildUncached(rawType, isRoot, depth)
352
+ end
353
+ -- Keyed by depth too, because MAX_DEPTH truncates.
354
+ local atDepth = buildCache[depth]
355
+ if atDepth == nil then
356
+ atDepth = {}
357
+ buildCache[depth] = atDepth
358
+ end
359
+ local hit = atDepth[key]
360
+ if hit ~= nil then
361
+ return hit
362
+ end
363
+ local built = buildUncached(rawType, isRoot, depth)
364
+ atDepth[key] = built
365
+ return built
366
+ end
367
+ buildUncached = function(rawType: type, isRoot: boolean, depth: number): type
368
+ if depth > MAX_DEPTH then
369
+ return anyType
370
+ end
371
+ local t = widen(rawType)
372
+
373
+ -- The Scribe.ServerOnly marker has to come off first: every declarator check below
374
+ -- reads a marker off `t`, so with the wrapper on, ServerOnly(SetOf/Big/Flags/Timed)
375
+ -- matches none of them and the node loses its declarator surface. A second unwrap
376
+ -- after the SetOf block handles the inverse nesting, e.g. Timed(ServerOnly(false)).
377
+ if t:is("table") then
378
+ local inner = t:readproperty(ts.singleton("__scribeServerOnly"))
379
+ if inner ~= nil then
380
+ t = widen(inner)
381
+ end
382
+ end
383
+
384
+ -- A Scribe.Derived node reads as V and never writes, so this only records the
385
+ -- flag; the mutator block below is skipped as it is for the root accessor.
386
+ local isDerived = false
387
+ if t:is("table") then
388
+ local inner = t:readproperty(ts.singleton("__scribeDerived"))
389
+ if inner ~= nil then
390
+ isDerived = true
391
+ t = widen(inner)
392
+ end
393
+ end
394
+
395
+ local isTimed = false
396
+ if t:is("table") then
397
+ local inner = t:readproperty(ts.singleton("__scribeTimed"))
398
+ if inner ~= nil then
399
+ isTimed = true
400
+ t = widen(inner)
401
+ end
402
+ end
403
+
404
+ -- Without the marker a flags field is just { string } and would pick up the
405
+ -- array surface, none of which it supports. `t` is already the { string } a
406
+ -- read returns; the label is on the metatable.
407
+ local isFlags = t:is("table") and hasMarker(t, "__scribeFlags")
408
+
409
+ -- A big's value is an object with arithmetic metamethods rather than a number,
410
+ -- so it gets its own method surface and none of the table one.
411
+ local isBig = false
412
+ if t:is("table") and isBigMarker(t) then
413
+ isBig = true
414
+ t = bigValueType()
415
+ end
416
+
417
+ -- Without the marker a set is just { T } and would pick up Insert plus
418
+ -- index-based Remove, neither of which a set has. `t` is already the members.
419
+ local isSet = t:is("table") and hasMarker(t, "__scribeSet")
420
+
421
+ -- Second ServerOnly unwrap, for a marker nested inside another declarator
422
+ -- rather than wrapped around one. The server reads these normally;
423
+ -- StripServerOnly is what drops them from the client type.
424
+ if t:is("table") then
425
+ local inner = t:readproperty(ts.singleton("__scribeServerOnly"))
426
+ if inner ~= nil then
427
+ t = widen(inner)
428
+ end
429
+ end
430
+
431
+ -- Scribe.MapOf carries its key type as a singleton, the only way to tell a sparse
432
+ -- {[number]: V} map from an array: at the type level those are the same indexer.
433
+ -- Last, so a map wrapped in Scribe.ServerOnly is still seen as a map. `t` stays the
434
+ -- whole map; only the element is pulled back out, for the key events and Remove.
435
+ local mapKey: type? = nil
436
+ local mapValue: type? = nil
437
+ local mapElement: type? = nil
438
+ if t:is("table") and hasMarker(t, "__scribeMapKey") then
439
+ local indexer = t:indexer()
440
+ if indexer ~= nil then
441
+ mapKey = indexer.index
442
+ mapValue = indexer.readresult
443
+ mapElement = widen(indexer.readresult)
444
+ end
445
+ end
446
+
447
+ -- Insertion ordered, because the properties are applied one at a time below and a
448
+ -- later entry must overwrite an earlier one of the same name. A map keyed by type
449
+ -- cannot do that: two ts.singleton("Remove") calls are distinct objects.
450
+ local props: { { key: type, ty: type } } = {}
451
+ local indexerSpec: { index: type, readresult: type, writeresult: type }? = nil
452
+ local childLookups: { type } = {}
453
+
454
+ -- Strips a nested Timed / ServerOnly label, the one thing a read should not show.
455
+ local valueType = unwrapWrappers(t, depth)
456
+ local function add(name: string, ty: type)
457
+ table.insert(props, { key = ts.singleton(name), ty = ty })
458
+ end
459
+
460
+ -- Static children and container methods first, so the common node methods below win
461
+ -- on name collisions. Maps are excluded: their own block builds the same surface
462
+ -- with the declared key type, and two ts.singleton("Remove") calls are distinct
463
+ -- keys, so letting a map through here duplicates rather than overrides.
464
+ if t:is("table") and mapKey == nil and not isTimed and not isFlags and not isSet and not isBig then
465
+ for key, prop in t:properties() do
466
+ local childType = prop.read or prop.write
467
+ if childType ~= nil then
468
+ local childNode = build(childType, false, depth + 1)
469
+ table.insert(props, { key = key, ty = childNode })
470
+ table.insert(childLookups, fn({ key }, { childNode }))
471
+ end
472
+ end
473
+
474
+ -- OnChildChanged reports an existing child's value moving, once per write
475
+ -- and never coalesced, unlike Changed.
476
+ local childKeys: { type } = {}
477
+ local childValues: { type } = {}
478
+ for key, prop in t:properties() do
479
+ local childType = prop.read or prop.write
480
+ if childType ~= nil then
481
+ table.insert(childKeys, key)
482
+ table.insert(childValues, widen(childType))
483
+ end
484
+ end
485
+
486
+ local indexer = t:indexer()
487
+ if indexer ~= nil then
488
+ local elementType = widen(indexer.readresult)
489
+ local elementIn = readOnlyDeep(elementType, depth + 1)
490
+ if indexer.index:is("number") then
491
+ -- Array node: the indexer makes `arr[i]` an accessor node, which is
492
+ -- the only way to reach a Scribe.ArrayOf element field.
493
+ local elemNode = build(indexer.readresult, false, depth + 1)
494
+ table.insert(childLookups, fn({ indexer.index }, { elemNode }))
495
+ indexerSpec = {
496
+ index = indexer.index,
497
+ readresult = elemNode,
498
+ writeresult = elemNode,
499
+ }
500
+ add("Insert", fn({ elementIn, optNumber, optBool }, {}))
501
+ -- Remove returns nil on an empty/missing array (matches RemoveValue).
502
+ add("Remove", fn({ optNumber, optBool }, { optional(elementType) }))
503
+ add("RemoveValue", fn({ elementIn, optBool }, { optional(elementType), optNumber }))
504
+ add("Find", fn({ elementIn }, { optNumber }))
505
+ add("Has", fn({ elementIn }, { ts.boolean }))
506
+ add("OnInsert", fn({ fn({ elementType, ts.number }, {}) }, { disconnectType }))
507
+ add("OnRemove", fn({ fn({ elementType, ts.number }, {}) }, { disconnectType }))
508
+ else
509
+ -- Dictionary node: children are accessor nodes.
510
+ local childNode = build(indexer.readresult, false, depth + 1)
511
+ table.insert(childLookups, fn({ indexer.index }, { childNode }))
512
+ indexerSpec = {
513
+ index = indexer.index,
514
+ readresult = childNode,
515
+ writeresult = childNode,
516
+ }
517
+ add("Remove", fn({ ts.string, optBool }, { optional(elementType) }))
518
+ add("OnKeyAdded", fn({ fn({ indexer.index, elementType }, {}) }, { disconnectType }))
519
+ add("OnKeyRemoved", fn({ fn({ indexer.index, elementType }, {}) }, { disconnectType }))
520
+ end
521
+ add("Clear", fn({ optBool }, {}))
522
+ add("Count", fn({}, { ts.number }))
523
+ -- A dynamic container's children are homogeneous, so the key and value
524
+ -- types here are exact rather than a union over declared fields.
525
+ table.insert(childKeys, indexer.index)
526
+ table.insert(childValues, widen(indexer.readresult))
527
+ end
528
+
529
+ if #childKeys > 0 then
530
+ -- (key, new, old), matching Changed's new-first order. Both values are
531
+ -- optional: an added key has no old, a removed key has no new. On a
532
+ -- heterogeneous static table they widen to a union Luau will not narrow from
533
+ -- the key, which is accepted; that node kind has exact per-field listeners.
534
+ -- Past MAX_CHILD_UNION the pair is widened; a growing union is what exceeds the budget.
535
+ local childKey = if #childKeys > MAX_CHILD_UNION then ts.string else ts.unionof(table.unpack(childKeys))
536
+ local childValue = if #childValues > MAX_CHILD_UNION
537
+ then optional(anyType)
538
+ else optional(ts.unionof(table.unpack(childValues)))
539
+ add("OnChildChanged", fn({ fn({ childKey, childValue, childValue }, {}) }, { disconnectType }))
540
+ end
541
+ end
542
+
543
+ if mapKey ~= nil then
544
+ -- A map's children are accessor nodes keyed by the declared type; the key
545
+ -- events and Remove carry the element rather than the whole map.
546
+ local element = mapElement :: type
547
+ local childNode = build(mapValue :: type, false, depth + 1)
548
+ table.insert(childLookups, fn({ mapKey }, { childNode }))
549
+ indexerSpec = { index = mapKey, readresult = childNode, writeresult = childNode }
550
+ add("Remove", fn({ mapKey, optBool }, { optional(element) }))
551
+ add("OnKeyAdded", fn({ fn({ mapKey, element }, {}) }, { disconnectType }))
552
+ add("OnKeyRemoved", fn({ fn({ mapKey, element }, {}) }, { disconnectType }))
553
+ add("OnChildChanged", fn({ fn({ mapKey, optional(element), optional(element) }, {}) }, { disconnectType }))
554
+ add("Clear", fn({ optBool }, {}))
555
+ add("Count", fn({}, { ts.number }))
556
+ end
557
+
558
+ -- A homogeneous container keeps the exact child type. Static records use
559
+ -- an untyped lookup: overloads duplicate every recursive child node in the
560
+ -- callable surface and push ordinary templates past the Luau solver budget.
561
+ -- Direct property access remains exact; TypeScript can type this lookup too.
562
+ if #childLookups == 1 then
563
+ add("Child", childLookups[1])
564
+ elseif #childLookups > 1 then
565
+ add("Child", fn({ ts.unionof(ts.string, ts.number) }, { anyType }))
566
+ end
567
+
568
+ -- Common node methods.
569
+ add("Get", fn({}, { valueType }))
570
+ -- The root accessor cannot be Set or Updated at runtime, so those are left off the
571
+ -- root type. A big field declares its own wider Set and Update below; adding them
572
+ -- here too would duplicate rather than override, as the singletons are distinct keys.
573
+ if not isRoot and not isBig and not isDerived then
574
+ -- Writes take the unbranded shape: a caller writing a plain table literal
575
+ -- has no way to produce a map's metatable brand. Reads still hand back the
576
+ -- branded type, which assigns freely to the plain shape.
577
+ local writeType = if mapKey ~= nil and mapElement ~= nil
578
+ then ts.newtable(nil, { index = mapKey, readresult = mapElement, writeresult = mapElement }, nil)
579
+ else valueType
580
+ local writeIn = if mapKey ~= nil then writeType else readOnlyDeep(writeType, depth + 1)
581
+ add("Set", fn({ writeIn, optBool }, { valueType }))
582
+ add("Update", fn({ fn({ valueType }, { writeIn }), optBool }, { valueType }))
583
+ end
584
+ add("Clone", fn({}, { valueType }))
585
+ add("Default", fn({}, { valueType }))
586
+ -- (new, old) on every node. On a container it reports state, coalesced to one
587
+ -- fire per batch or received frame; which child moved is OnChildChanged's job.
588
+ add("Changed", fn({ fn({ valueType, valueType }, {}) }, { disconnectType }))
589
+ add("Observe", fn({ fn({ valueType }, {}) }, { disconnectType }))
590
+
591
+ if t:is("number") then
592
+ -- Min/Max read the declared bounds, so they stay on a derived field; the
593
+ -- two mutators do not.
594
+ if not isDerived then
595
+ add("Increment", fn({ ts.number, anyType }, { ts.number }))
596
+ add("Decrement", fn({ ts.number, anyType }, { ts.number }))
597
+ end
598
+ add("Min", fn({}, { optNumber }))
599
+ add("Max", fn({}, { optNumber }))
600
+ elseif t:is("boolean") and not isDerived then
601
+ add("Toggle", fn({ optBool }, { ts.boolean }))
602
+ end
603
+
604
+ if isBig then
605
+ -- Every entry point, Set included, takes a number, a numeric string, or
606
+ -- another big value, so the operand type is the same union everywhere.
607
+ local operand = ts.unionof(ts.number, ts.string, valueType)
608
+ add("Set", fn({ operand, optBool }, { valueType }))
609
+ add("Update", fn({ fn({ valueType }, { operand }), optBool }, { valueType }))
610
+ add("Increment", fn({ operand, anyType }, { valueType }))
611
+ add("Decrement", fn({ operand, anyType }, { valueType }))
612
+ add("Multiply", fn({ operand, optBool }, { valueType }))
613
+ add("Divide", fn({ operand, optBool }, { valueType }))
614
+ -- A big bound past the double range is only expressible as a numeric string,
615
+ -- so these return the same union the declarator accepts.
616
+ local optBound = optional(ts.unionof(ts.number, ts.string))
617
+ add("Min", fn({}, { optBound }))
618
+ add("Max", fn({}, { optBound }))
619
+ end
620
+
621
+ if isSet then
622
+ -- Membership surface. Get/Set still take the whole { T }.
623
+ local setIndexer = t:indexer()
624
+ local element = if setIndexer ~= nil then widen(setIndexer.readresult) else anyType
625
+ local elementIn = readOnlyDeep(element, depth + 1)
626
+ add("Add", fn({ elementIn, optBool }, { ts.boolean }))
627
+ add("Remove", fn({ elementIn, optBool }, { ts.boolean }))
628
+ add("Has", fn({ elementIn }, { ts.boolean }))
629
+ add("Count", fn({}, { ts.number }))
630
+ add("Clear", fn({ optBool }, {}))
631
+ end
632
+
633
+ if isFlags then
634
+ -- Named-member surface. Get/Set still take the whole { string } set.
635
+ add("Enable", fn({ ts.string, optBool }, {}))
636
+ add("Disable", fn({ ts.string, optBool }, {}))
637
+ add("Has", fn({ ts.string }, { ts.boolean }))
638
+ add("Toggle", fn({ ts.string, optBool }, { ts.boolean }))
639
+ add("Clear", fn({ optBool }, {}))
640
+ end
641
+
642
+ if isTimed then
643
+ add("SetTimed", fn({ valueType, ts.number, optBool }, {}))
644
+ add("ExtendTimed", fn({ ts.number, optBool }, {}))
645
+ add("Active", fn({}, { ts.boolean, optNumber }))
646
+ end
647
+
648
+ -- Read-only, not read/write. An accessor is never assigned to, and a read/write
649
+ -- property makes comparing two accessor trees invariant: the solver has to prove
650
+ -- each side is exactly the other, which is what exceeds its budget at Scribe().
651
+ local out = ts.newtable(nil, indexerSpec, nil)
652
+ for _, entry in props do
653
+ out:setreadproperty(entry.key, entry.ty)
654
+ end
655
+ return out
656
+ end
657
+
658
+ return build(T, true, 0)
659
+ end
660
+
661
+ -- Union of every static rankable leaf path in the template, dot-joined ("Coins",
662
+ -- "Stats.Wins"), for leaderboard `Stat` and purchase cost paths. Dynamic segments cannot
663
+ -- be enumerated at type level, so those paths must be cast to `any`; falls back to plain
664
+ -- `string` when the template has no such leaf. `IncludeBig` is true for leaderboards and
665
+ -- false for cost paths, which must be plain numbers.
666
+ -- selene: allow(undefined_variable)
667
+ export type function StatPathsType(T: type, IncludeBig: type?): type
668
+ local ts = types
669
+ local MAX_STAT_PATHS = 32
670
+ local includeBig = IncludeBig ~= nil and IncludeBig:is("singleton") and IncludeBig:value() == true
671
+
672
+ local function hasMarker(t: type, name: string): boolean
673
+ local mt = t:metatable()
674
+ return mt ~= nil and mt:readproperty(ts.singleton(name)) ~= nil
675
+ end
676
+
677
+ local function isBigMarker(t: type): boolean
678
+ return hasMarker(t, "__scribeBig")
679
+ end
680
+
681
+ local function isMapMarker(t: type): boolean
682
+ return hasMarker(t, "__scribeMapKey")
683
+ end
684
+
685
+ local paths: { type } = {}
686
+
687
+ local function widen(t: type): type
688
+ if t:is("singleton") then
689
+ local value = t:value()
690
+ if type(value) == "boolean" then
691
+ return ts.boolean
692
+ elseif type(value) == "string" then
693
+ return ts.string
694
+ end
695
+ end
696
+ return t
697
+ end
698
+
699
+ local function walk(rawType: type, prefix: string, depth: number)
700
+ if depth > 8 then
701
+ return
702
+ end
703
+ local t = widen(rawType)
704
+ if t:is("table") then
705
+ -- Unwrap the Scribe.Timed marker; its inner value is the leaf.
706
+ local inner = t:readproperty(ts.singleton("__scribeTimed"))
707
+ if inner ~= nil then
708
+ t = widen(inner)
709
+ end
710
+ end
711
+ if t:is("table") then
712
+ -- Same for Scribe.ServerOnly: the server is what reads leaderboard
713
+ -- stats, so a server-only number is still a valid stat path.
714
+ local serverOnly = t:readproperty(ts.singleton("__scribeServerOnly"))
715
+ if serverOnly ~= nil then
716
+ t = widen(serverOnly)
717
+ end
718
+ end
719
+ if t:is("table") then
720
+ -- And Scribe.Derived: a board reads its stat through the accessor tree,
721
+ -- which computes derived fields, so a derived number is a valid stat.
722
+ local derived = t:readproperty(ts.singleton("__scribeDerived"))
723
+ if derived ~= nil then
724
+ t = widen(derived)
725
+ end
726
+ end
727
+ if t:is("table") and isMapMarker(t) then
728
+ -- A map's entries live under dynamic keys, which cannot be enumerated at type
729
+ -- level. Recursing would offer the unaddressable "Field.__scribeMapValue".
730
+ return
731
+ end
732
+ if t:is("table") and isBigMarker(t) then
733
+ -- Always terminal: a big's type is its real shape, so recursing would expose the
734
+ -- object's own M and E and offer "Coins.M" as a stat path. When a big counts, the
735
+ -- field itself is the path, or a template whose only rankable field is big
736
+ -- produces an empty union and collapses the gate to `string`.
737
+ if includeBig and prefix ~= "" then
738
+ table.insert(paths, ts.singleton(prefix))
739
+ end
740
+ return
741
+ end
742
+ if t:is("number") then
743
+ if prefix ~= "" then
744
+ table.insert(paths, ts.singleton(prefix))
745
+ end
746
+ return
747
+ end
748
+ if t:is("table") then
749
+ for key, prop in t:properties() do
750
+ local childType = prop.read or prop.write
751
+ if childType ~= nil and key:is("singleton") then
752
+ local name = key:value()
753
+ if type(name) == "string" then
754
+ walk(childType, if prefix == "" then name else `{prefix}.{name}`, depth + 1)
755
+ end
756
+ end
757
+ end
758
+ end
759
+ end
760
+
761
+ walk(T, "", 0)
762
+
763
+ if #paths == 0 then
764
+ return ts.string
765
+ end
766
+ if #paths == 1 then
767
+ return paths[1]
768
+ end
769
+ if #paths > MAX_STAT_PATHS then
770
+ -- A union this size is what the solver cannot afford.
771
+ return ts.string
772
+ end
773
+ return ts.unionof(table.unpack(paths))
774
+ end
775
+
776
+ -- T with every Scribe.ServerOnly subtree removed, at any depth, so the client type
777
+ -- cannot name a field that reads nil there. Applied to the raw template before
778
+ -- ValueType, which unwraps the marker and loses the information.
779
+ -- selene: allow(undefined_variable)
780
+ type function StripServerOnly(T)
781
+ local ts = types
782
+ local MARKER = ts.singleton("__scribeServerOnly")
783
+ -- Matches ValueType's budget: a cyclic template must not blow the stack.
784
+ local MAX_DEPTH = 25
785
+
786
+ local function isServerOnly(t: type): boolean
787
+ return t:is("table") and t:readproperty(MARKER) ~= nil
788
+ end
789
+
790
+ local function strip(t: type, depth: number): type
791
+ if depth > MAX_DEPTH or not t:is("table") then
792
+ return t
793
+ end
794
+ local out = ts.copy(t)
795
+ for key, prop in t:properties() do
796
+ local childType = prop.read or prop.write
797
+ if childType ~= nil then
798
+ if isServerOnly(childType) then
799
+ out:setproperty(key, nil) -- the whole subtree leaves the client type
800
+ else
801
+ out:setproperty(key, strip(childType, depth + 1))
802
+ end
803
+ end
804
+ end
805
+ -- Element shapes live behind the indexer, not in properties: without this a
806
+ -- ServerOnly field inside an ArrayOf or DictOf entry stays in the client type.
807
+ local indexer = t:indexer()
808
+ if indexer ~= nil then
809
+ local element = strip(indexer.readresult, depth + 1)
810
+ out:setindexer(indexer.index, element)
811
+ end
812
+ return out
813
+ end
814
+
815
+ return strip(T, 0)
816
+ end
817
+
818
+ -- Grant callbacks receive the typed accessor tree when a template type is supplied,
819
+ -- and stay `any` for the untyped default so un-annotated configs stay clean.
820
+ -- selene: allow(undefined_variable)
821
+ export type function GrantDataType(T)
822
+ if T:is("any") or T:is("unknown") then
823
+ return types.any
824
+ end
825
+ return ValueType(T)
826
+ end
827
+
828
+ -- Store proxies expose declared roots, without the root accessor's methods.
829
+ -- selene: allow(undefined_variable)
830
+ type function StoreDataType(S: type): type
831
+ local ts = types
832
+ if not S:is("table") then
833
+ return ts.any
834
+ end
835
+
836
+ local fields = ts.newtable(nil, S:indexer(), nil)
837
+ local names: { [type]: type } = {}
838
+ local index = 0
839
+ for key, prop in S:properties() do
840
+ local fieldType = prop.read or prop.write
841
+ if fieldType ~= nil then
842
+ index += 1
843
+ -- Avoid accessor names such as Get while building each field's type.
844
+ local alias = ts.singleton(`_storeField{index}`)
845
+ fields:setproperty(alias, fieldType)
846
+ names[key] = alias
847
+ end
848
+ end
849
+ local nodes = ValueType(fields)
850
+ local roots = ts.newtable(nil, nodes:indexer(), nil)
851
+ for key, alias in names do
852
+ roots:setproperty(key, nodes:readproperty(alias))
853
+ end
854
+ return roots
855
+ end
856
+
857
+ -- The client `Data` is the accessor tree root plus the client API. A type function
858
+ -- rather than `ValueType<T> & { ... }`, because normalizing an intersection over a
859
+ -- large accessor tree exceeds the solver's budget at the Scribe() call site.
860
+ -- selene: allow(undefined_variable)
861
+ type function BuildClientDataType(T, S)
862
+ local ts = types
863
+
864
+ local function optional(t: type): type
865
+ return ts.unionof(t, ts.singleton(nil))
866
+ end
867
+
868
+ local function fn(params: { type }, rets: { type }): type
869
+ return ts.newfunction({ head = params }, { head = rets })
870
+ end
871
+
872
+ local anyTable = ts.newtable(nil, { index = ts.string, readresult = ts.any, writeresult = ts.any }, nil)
873
+ local stringToNumber = ts.newtable(nil, { index = ts.string, readresult = ts.number, writeresult = ts.number }, nil)
874
+
875
+ local entryProps: { [type]: type } = {}
876
+ entryProps[ts.singleton("Rank")] = ts.number
877
+ entryProps[ts.singleton("UserId")] = ts.number
878
+ entryProps[ts.singleton("Name")] = ts.string
879
+ -- `number | BigScore`, not `number`: a Scribe.Big board hands back the big itself,
880
+ -- and the board's kind is a runtime property of the name passed in, so the type
881
+ -- cannot pick one and the caller narrows.
882
+ local bigScoreProps: { [type]: type } = {}
883
+ bigScoreProps[ts.singleton("M")] = ts.number
884
+ bigScoreProps[ts.singleton("E")] = ts.number
885
+ bigScoreProps[ts.singleton("Short")] = ts.newfunction(
886
+ { head = { ts.any, ts.unionof(ts.number, ts.singleton(nil)) } },
887
+ { head = { ts.string } }
888
+ )
889
+ bigScoreProps[ts.singleton("ToNumber")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
890
+ bigScoreProps[ts.singleton("Log10")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
891
+ entryProps[ts.singleton("Score")] = ts.unionof(ts.number, ts.newtable(bigScoreProps, nil, nil))
892
+ local leaderboardEntry = ts.newtable(entryProps, nil, nil)
893
+ local entryArray =
894
+ ts.newtable(nil, { index = ts.number, readresult = leaderboardEntry, writeresult = leaderboardEntry }, nil)
895
+ local anyArray = ts.newtable(nil, { index = ts.number, readresult = anyTable, writeresult = anyTable }, nil)
896
+
897
+ local statusType = ts.unionof(ts.singleton("Healthy"), ts.singleton("Degraded"), ts.singleton("Outage"))
898
+
899
+ local saveInfoProps: { [type]: type } = {}
900
+ saveInfoProps[ts.singleton("LastSaveAt")] = optional(ts.number)
901
+ saveInfoProps[ts.singleton("LastResult")] = optional(ts.unionof(ts.singleton("Ok"), ts.singleton("Fail")))
902
+ saveInfoProps[ts.singleton("Dirty")] = ts.boolean
903
+ saveInfoProps[ts.singleton("Size")] = optional(ts.number)
904
+ local saveInfo = ts.newtable(saveInfoProps, nil, nil)
905
+
906
+ local out = ts.copy(ValueType(StripServerOnly(T)))
907
+ local function add(name: string, ty: type)
908
+ out:setproperty(ts.singleton(name), ty)
909
+ end
910
+
911
+ add("IsReady", fn({}, { ts.boolean }))
912
+ add("Batch", fn({ fn({}, {}) }, {}))
913
+ add("Stop", fn({}, {}))
914
+ add("WaitForData", fn({ optional(ts.number) }, { ts.boolean }))
915
+ add("Request", ts.newfunction({ head = { ts.string }, tail = ts.any }, { tail = ts.any }))
916
+ -- RequestOnce(name, key, ...): the key is a required second string, so a plain
917
+ -- Request argument list fails to type-check rather than silently becoming a key.
918
+ add("RequestOnce", ts.newfunction({ head = { ts.string, ts.string }, tail = ts.any }, { tail = ts.any }))
919
+ add("GetLeaderboard", fn({ ts.string, optional(ts.number) }, { entryArray }))
920
+ add("GetMyRank", fn({ ts.string }, { optional(ts.number) }))
921
+ add("OnLeaderboard", ts.any)
922
+ add("GetServiceStatus", fn({}, { statusType }))
923
+ add("OnServiceStatus", ts.any)
924
+ add("GetShared", fn({ ts.any }, { optional(anyTable) }))
925
+ add("OnSharedChanged", ts.any)
926
+ add("Owns", fn({ ts.string }, { ts.boolean }))
927
+ add("OwnsAsync", fn({ ts.string, optional(ts.number) }, { ts.boolean }))
928
+ add("ObserveOwned", fn({ ts.string, fn({ ts.boolean }, {}) }, { fn({}, {}) }))
929
+ add("OnOwnershipChanged", ts.any)
930
+ add("GetSaveInfo", fn({}, { saveInfo }))
931
+ add("GetGiftCredits", fn({}, { stringToNumber }))
932
+ local purchaseFilterProps: { [type]: type } = {}
933
+ purchaseFilterProps[ts.singleton("Kind")] = optional(ts.unionof(ts.singleton("Robux"), ts.singleton("InGame")))
934
+ purchaseFilterProps[ts.singleton("Category")] = optional(ts.string)
935
+ purchaseFilterProps[ts.singleton("ItemId")] = optional(ts.string)
936
+ purchaseFilterProps[ts.singleton("Since")] = optional(ts.number)
937
+ purchaseFilterProps[ts.singleton("Limit")] = optional(ts.number)
938
+ local purchaseFilter = optional(ts.newtable(purchaseFilterProps, nil, nil))
939
+ add("GetPurchases", fn({ purchaseFilter }, { anyArray }))
940
+ local stringArray = ts.newtable(nil, { index = ts.number, readresult = ts.string, writeresult = ts.string }, nil)
941
+ add("GetProductInfo", fn({ ts.string }, { optional(anyTable) }))
942
+ add("GetPrice", fn({ ts.string }, { optional(ts.number) }))
943
+ add("GetProductInfoAsync", fn({ ts.string, optional(ts.number) }, { optional(anyTable) }))
944
+ add("GetPriceAsync", fn({ ts.string, optional(ts.number) }, { optional(ts.number) }))
945
+ add("ObserveProductInfo", fn({ ts.string, fn({ optional(anyTable) }, {}) }, { fn({}, {}) }))
946
+ add("PromptPurchase", fn({ ts.string }, { ts.boolean, optional(ts.string), optional(ts.newtable(nil, nil, nil)) }))
947
+ add("GetProductState", fn({ ts.string }, { ts.string }))
948
+ add("ObserveProductState", fn({ ts.string, fn({ ts.string }, {}) }, { fn({}, {}) }))
949
+ add("PrefetchProductInfo", fn({ optional(stringArray) }, {}))
950
+ add("RefreshProductInfo", fn({ optional(ts.string) }, {}))
951
+ add("Mock", fn({ optional(anyTable), optional(anyTable) }, {}))
952
+ add(
953
+ "MockCommand",
954
+ ts.newfunction({ head = { ts.string, ts.newfunction({ tail = ts.any }, { tail = ts.any }) } }, { head = {} })
955
+ )
956
+ add("Raw", ts.any)
957
+ add("ServerStore", StoreDataType(StripServerOnly(S)))
958
+
959
+ return out
960
+ end
961
+
962
+ -- selene: allow(undefined_variable)
963
+ export type function ClientDataType(T)
964
+ return BuildClientDataType(T, types.any)
965
+ end
966
+
967
+ -- The server `Data` API. P is the Player class type, passed in as a type argument
968
+ -- because class types are not constructible inside a type function. A type function
969
+ -- for the same complexity-budget reason as ClientDataType.
970
+ -- selene: allow(undefined_variable)
971
+ type function BuildServerDataType(T, P, S)
972
+ local ts = types
973
+
974
+ local node = ValueType(T)
975
+
976
+ local function optional(t: type): type
977
+ return ts.unionof(t, ts.singleton(nil))
978
+ end
979
+
980
+ local function fn(params: { type }, rets: { type }): type
981
+ return ts.newfunction({ head = params }, { head = rets })
982
+ end
983
+
984
+ local anyTable = ts.newtable(nil, { index = ts.string, readresult = ts.any, writeresult = ts.any }, nil)
985
+ local stringToNumber = ts.newtable(nil, { index = ts.string, readresult = ts.number, writeresult = ts.number }, nil)
986
+ local optAnyTable = optional(anyTable)
987
+ local anyArray = ts.newtable(nil, { index = ts.number, readresult = anyTable, writeresult = anyTable }, nil)
988
+ local boolAndReason = { ts.boolean, optional(ts.string) }
989
+
990
+ local entryProps: { [type]: type } = {}
991
+ entryProps[ts.singleton("Rank")] = ts.number
992
+ entryProps[ts.singleton("UserId")] = ts.number
993
+ entryProps[ts.singleton("Name")] = ts.string
994
+ -- `number | BigScore`: a Scribe.Big board hands back the big itself, as in
995
+ -- ClientDataType above.
996
+ local bigScoreProps: { [type]: type } = {}
997
+ bigScoreProps[ts.singleton("M")] = ts.number
998
+ bigScoreProps[ts.singleton("E")] = ts.number
999
+ bigScoreProps[ts.singleton("Short")] = ts.newfunction(
1000
+ { head = { ts.any, ts.unionof(ts.number, ts.singleton(nil)) } },
1001
+ { head = { ts.string } }
1002
+ )
1003
+ bigScoreProps[ts.singleton("ToNumber")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
1004
+ bigScoreProps[ts.singleton("Log10")] = ts.newfunction({ head = { ts.any } }, { head = { ts.number } })
1005
+ entryProps[ts.singleton("Score")] = ts.unionof(ts.number, ts.newtable(bigScoreProps, nil, nil))
1006
+ local leaderboardEntry = ts.newtable(entryProps, nil, nil)
1007
+ local entryArray =
1008
+ ts.newtable(nil, { index = ts.number, readresult = leaderboardEntry, writeresult = leaderboardEntry }, nil)
1009
+
1010
+ local saveInfoProps: { [type]: type } = {}
1011
+ saveInfoProps[ts.singleton("LastSaveAt")] = optional(ts.number)
1012
+ saveInfoProps[ts.singleton("LastResult")] = optional(ts.unionof(ts.singleton("Ok"), ts.singleton("Fail")))
1013
+ saveInfoProps[ts.singleton("Dirty")] = ts.boolean
1014
+ saveInfoProps[ts.singleton("Size")] = optional(ts.number)
1015
+ local saveInfo = ts.newtable(saveInfoProps, nil, nil)
1016
+
1017
+ local versionProps: { [type]: type } = {}
1018
+ versionProps[ts.singleton("VersionId")] = ts.string
1019
+ versionProps[ts.singleton("CreatedAt")] = ts.number
1020
+ versionProps[ts.singleton("Size")] = optional(ts.number)
1021
+ local versionRecord = ts.newtable(versionProps, nil, nil)
1022
+ local versionArray =
1023
+ ts.newtable(nil, { index = ts.number, readresult = versionRecord, writeresult = versionRecord }, nil)
1024
+
1025
+ local flushOptsProps: { [type]: type } = {}
1026
+ flushOptsProps[ts.singleton("Force")] = optional(ts.boolean)
1027
+ flushOptsProps[ts.singleton("Timeout")] = optional(ts.number)
1028
+ local flushOpts = optional(ts.newtable(flushOptsProps, nil, nil))
1029
+
1030
+ local restoreOptsProps: { [type]: type } = {}
1031
+ restoreOptsProps[ts.singleton("RollBackReserved")] = optional(ts.boolean)
1032
+ local restoreOpts = optional(ts.newtable(restoreOptsProps, nil, nil))
1033
+
1034
+ -- Keep in sync with Types.LifecycleReason. Spelled out here because a type
1035
+ -- function cannot reference an exported type alias.
1036
+ local reasonUnion = ts.unionof(
1037
+ ts.singleton("load-failed"),
1038
+ ts.singleton("migration-failed"),
1039
+ ts.singleton("erasing"),
1040
+ ts.singleton("session-ended"),
1041
+ ts.singleton("player-left"),
1042
+ ts.singleton("shutdown"),
1043
+ ts.singleton("still-loading"),
1044
+ ts.singleton("timeout")
1045
+ )
1046
+
1047
+ local props: { [type]: type } = {}
1048
+ local function add(name: string, ty: type)
1049
+ props[ts.singleton(name)] = ty
1050
+ end
1051
+
1052
+ add("Get", fn({ P }, { node }))
1053
+ add("WaitForData", fn({ P, optional(ts.number) }, { optional(node), optional(reasonUnion) }))
1054
+ add(
1055
+ "GetState",
1056
+ fn({ P }, {
1057
+ ts.unionof(ts.singleton("Loading"), ts.singleton("Ready"), ts.singleton("SessionEnded")),
1058
+ optional(
1059
+ ts.unionof(
1060
+ ts.singleton("WaitingForErase"),
1061
+ ts.singleton("AcquiringSession"),
1062
+ ts.singleton("ReadingProfile"),
1063
+ ts.singleton("Retrying"),
1064
+ ts.singleton("Initializing"),
1065
+ ts.singleton("Importing"),
1066
+ ts.singleton("ImportThrottled")
1067
+ )
1068
+ ),
1069
+ })
1070
+ )
1071
+
1072
+ add("Batch", fn({ P, fn({}, {}) }, {}))
1073
+ add("Transaction", fn({ P, fn({}, {}) }, boolAndReason))
1074
+
1075
+ add("Flush", fn({ P, flushOpts }, { ts.boolean }))
1076
+ add("GetSaveInfo", fn({ P }, { saveInfo }))
1077
+ add("GetOffline", fn({ ts.number }, { optAnyTable }))
1078
+ local updateOfflineOptsProps: { [type]: type } = {}
1079
+ updateOfflineOptsProps[ts.singleton("Validate")] = optional(ts.boolean)
1080
+ local updateOfflineOpts = optional(ts.newtable(updateOfflineOptsProps, nil, nil))
1081
+ add(
1082
+ "UpdateOffline",
1083
+ fn(
1084
+ { ts.number, fn({ anyTable }, {}), updateOfflineOpts },
1085
+ { ts.boolean, optional(ts.string), optional(anyArray) }
1086
+ )
1087
+ )
1088
+ add("ListVersions", fn({ ts.number, optional(ts.number) }, { versionArray }))
1089
+ add("GetVersion", fn({ ts.number, ts.string }, { optAnyTable }))
1090
+ add("RestoreVersion", fn({ ts.number, ts.string, restoreOpts }, boolAndReason))
1091
+
1092
+ -- Command(name, spec?, handler): the spec shape and the handler's `player` param are
1093
+ -- typed; per-arg types cannot be recovered, since the Args literals widen. Args
1094
+ -- elements are `any` rather than `string` because Commands.Register also accepts
1095
+ -- declarators and shape tables, and validates the entries itself at register time.
1096
+ local commandArgs = ts.newtable(nil, { index = ts.number, readresult = ts.any, writeresult = ts.any }, nil)
1097
+ local commandSpecProps: { [type]: type } = {}
1098
+ commandSpecProps[ts.singleton("Args")] = optional(commandArgs)
1099
+ commandSpecProps[ts.singleton("Idempotent")] = optional(ts.boolean)
1100
+ local commandSpec = ts.newtable(commandSpecProps, nil, nil)
1101
+ local commandHandler = ts.newfunction({ head = { P }, tail = ts.any }, { tail = ts.any })
1102
+ add("Command", fn({ ts.string, ts.unionof(commandSpec, commandHandler), optional(commandHandler) }, {}))
1103
+
1104
+ add("GetLeaderboard", fn({ ts.string, optional(ts.number), optional(ts.number) }, { entryArray }))
1105
+ add("GetMyRank", fn({ P, ts.string }, { optional(ts.number) }))
1106
+ add("GetLeaderboardRefreshIn", fn({ ts.string }, { optional(ts.number) }))
1107
+ local boardStatusProps: { [type]: type } = {}
1108
+ boardStatusProps[ts.singleton("Status")] =
1109
+ ts.unionof(ts.singleton("Starting"), ts.singleton("Healthy"), ts.singleton("Degraded"))
1110
+ for _, key in { "PendingWrites", "RetryingWrites", "RejectedWrites" } do
1111
+ boardStatusProps[ts.singleton(key)] = ts.number
1112
+ end
1113
+ for _, key in { "LastReadAt", "ReadAge", "LastWriteAt" } do
1114
+ boardStatusProps[ts.singleton(key)] = optional(ts.number)
1115
+ end
1116
+ for _, key in { "LastReadError", "LastWriteError" } do
1117
+ boardStatusProps[ts.singleton(key)] = optional(ts.string)
1118
+ end
1119
+ add("GetLeaderboardStatus", fn({ ts.string }, { optional(ts.newtable(boardStatusProps, nil, nil)) }))
1120
+ add("GetLeaderboardResetIn", fn({ ts.string }, { optional(ts.number) }))
1121
+
1122
+ add("PromptGift", fn({ P, ts.string, ts.number }, boolAndReason))
1123
+ add("PromptPurchase", fn({ P, ts.string }, boolAndReason))
1124
+ add("GetProductState", fn({ P, ts.string }, { ts.string }))
1125
+ add("GetGiftCredits", fn({ P }, { stringToNumber }))
1126
+ add("HandleReceipt", fn({ ts.any }, { ts.any }))
1127
+ add("TryHandleReceipt", fn({ ts.any }, { optional(ts.any) }))
1128
+ add("Owns", fn({ P, ts.string }, { ts.boolean }))
1129
+ add("OwnsAsync", fn({ P, ts.string, optional(ts.number) }, { ts.boolean }))
1130
+ add("ObserveOwned", fn({ P, ts.string, fn({ ts.boolean }, {}) }, { fn({}, {}) }))
1131
+ add("OnOwnershipChanged", ts.any)
1132
+ add("GrantPerk", fn({ P, ts.string }, {}))
1133
+ add("RevokePerk", fn({ P, ts.string }, {}))
1134
+
1135
+ -- Purchase spec: Cost.Path is the template's numeric-leaf path union and
1136
+ -- Grant receives the typed accessor tree.
1137
+ local costProps: { [type]: type } = {}
1138
+ -- false: a cost path must be a plain number balance. Monetization refuses a
1139
+ -- non-number at runtime, so this rejects a Scribe.Big path at author time.
1140
+ costProps[ts.singleton("Path")] = StatPathsType(T, ts.singleton(false))
1141
+ costProps[ts.singleton("Amount")] = ts.number
1142
+ local purchaseProps: { [type]: type } = {}
1143
+ purchaseProps[ts.singleton("Cost")] = ts.newtable(costProps, nil, nil)
1144
+ purchaseProps[ts.singleton("Category")] = optional(ts.string)
1145
+ purchaseProps[ts.singleton("ItemId")] = ts.string
1146
+ purchaseProps[ts.singleton("Grant")] = optional(fn({ node }, {}))
1147
+ purchaseProps[ts.singleton("Meta")] = optAnyTable
1148
+ add("Purchase", fn({ P, ts.newtable(purchaseProps, nil, nil) }, boolAndReason))
1149
+ add("RecordPurchase", fn({ P, anyTable }, {}))
1150
+ -- OpenLeg and OpenExchange are rebuilt here: a type function cannot reach an alias.
1151
+ local openLegProps: { [type]: type } = {}
1152
+ local pathSegment = ts.unionof(ts.string, ts.number)
1153
+ openLegProps[ts.singleton("Path")] =
1154
+ ts.newtable(nil, { index = ts.number, readresult = pathSegment, writeresult = pathSegment }, nil)
1155
+ openLegProps[ts.singleton("Kind")] = ts.string
1156
+ openLegProps[ts.singleton("Key")] = optional(ts.any)
1157
+ openLegProps[ts.singleton("Amount")] = optional(ts.number)
1158
+ local openLeg = ts.newtable(openLegProps, nil, nil)
1159
+ local openLegArray = ts.newtable(nil, { index = ts.number, readresult = openLeg, writeresult = openLeg }, nil)
1160
+ local openProps: { [type]: type } = {}
1161
+ openProps[ts.singleton("Id")] = ts.string
1162
+ openProps[ts.singleton("State")] =
1163
+ ts.unionof(ts.singleton("Claimed"), ts.unionof(ts.singleton("Staked"), ts.singleton("Delivering")))
1164
+ openProps[ts.singleton("Partner")] = optional(ts.number)
1165
+ openProps[ts.singleton("Staked")] = openLegArray
1166
+ openProps[ts.singleton("Owed")] = openLegArray
1167
+ openProps[ts.singleton("Since")] = optional(ts.number)
1168
+ local openExchange = ts.newtable(openProps, nil, nil)
1169
+ local openArray =
1170
+ ts.newtable(nil, { index = ts.number, readresult = openExchange, writeresult = openExchange }, nil)
1171
+ local exchangeProps: { [type]: type } = {}
1172
+ exchangeProps[ts.singleton("Attempt")] = fn(
1173
+ { P, anyArray, P, anyArray },
1174
+ { optional(ts.string), optional(ts.string) }
1175
+ )
1176
+ exchangeProps[ts.singleton("Open")] = fn({ P }, { openArray })
1177
+ exchangeProps[ts.singleton("Discard")] = fn({ ts.string }, boolAndReason)
1178
+ exchangeProps[ts.singleton("Settle")] = fn({ ts.string, ts.string }, boolAndReason)
1179
+ exchangeProps[ts.singleton("Redirect")] = fn({ ts.string, ts.number, ts.string }, boolAndReason)
1180
+ add("Exchange", ts.newtable(exchangeProps, nil, nil))
1181
+
1182
+ -- Returned by Scribe.Server.
1183
+ add("Stop", fn({}, {}))
1184
+ local purchaseFilterProps: { [type]: type } = {}
1185
+ purchaseFilterProps[ts.singleton("Kind")] = optional(ts.unionof(ts.singleton("Robux"), ts.singleton("InGame")))
1186
+ purchaseFilterProps[ts.singleton("Category")] = optional(ts.string)
1187
+ purchaseFilterProps[ts.singleton("ItemId")] = optional(ts.string)
1188
+ purchaseFilterProps[ts.singleton("Since")] = optional(ts.number)
1189
+ purchaseFilterProps[ts.singleton("Limit")] = optional(ts.number)
1190
+ local purchaseFilter = optional(ts.newtable(purchaseFilterProps, nil, nil))
1191
+ add("GetPurchases", fn({ P, purchaseFilter }, { anyArray }))
1192
+
1193
+ local cooldownOptsProps: { [type]: type } = {}
1194
+ cooldownOptsProps[ts.singleton("IncludeOfflineTime")] = optional(ts.boolean)
1195
+ local cooldownOpts = optional(ts.newtable(cooldownOptsProps, nil, nil))
1196
+ add("OnCooldown", fn({ P, ts.string, ts.number, cooldownOpts }, { ts.boolean, ts.number }))
1197
+ add("PeekCooldown", fn({ P, ts.string }, { ts.boolean, ts.number }))
1198
+ add("ClearCooldown", fn({ P, ts.string }, {}))
1199
+
1200
+ add("Erase", fn({ ts.number }, boolAndReason))
1201
+ add("Export", fn({ ts.number }, { optional(ts.string) }))
1202
+
1203
+ add("OnSave", ts.any)
1204
+ add("SessionEnded", ts.any)
1205
+ add("OnCooldownEnded", ts.any)
1206
+ add("OnLeaderboard", ts.any)
1207
+ add("OnAnomaly", ts.any)
1208
+ add("OnGiftReceived", ts.any)
1209
+ add("OnGiftCredit", ts.any)
1210
+ add("OnMessage", ts.any)
1211
+ add("SendMessage", fn({ ts.number, ts.any }, { ts.boolean }))
1212
+ add("ProfileStore", ts.any)
1213
+ add("Raw", ts.any)
1214
+ add("ServerStore", StoreDataType(S))
1215
+
1216
+ return ts.newtable(props, { index = P, readresult = node, writeresult = node }, nil)
1217
+ end
1218
+
1219
+ -- selene: allow(undefined_variable)
1220
+ export type function ServerDataType(T, P)
1221
+ return BuildServerDataType(T, P, types.any)
1222
+ end
1223
+
1224
+ --------------------------------------------------------------------------------
1225
+ -- Typed field declarators
1226
+ --------------------------------------------------------------------------------
1227
+
1228
+ export type Timed<T> = { __scribeTimed: T }
1229
+ -- What a Scribe.Flags field reads back: the enabled member names. The label sits in
1230
+ -- the metatable so a whole-table read shows the members rather than the label.
1231
+ export type Flags = typeof(setmetatable({} :: { string }, {} :: { __scribeFlags: true }))
1232
+ -- A set reads back as its members. Label in the metatable, as above.
1233
+ export type SetOf<T> = typeof(setmetatable({} :: { T }, {} :: { __scribeSet: true }))
1234
+ export type ServerOnly<T> = { __scribeServerOnly: T }
1235
+ -- A derived field reads back as its output type, which may be a scalar, so the label
1236
+ -- is an ordinary field stripped by unwrapWrappers rather than a metatable entry.
1237
+ export type Derived<T> = { __scribeDerived: T }
1238
+
1239
+ export type NumberMeta = { Min: number?, Max: number? }
1240
+ -- Scribe.Number only. `Precision` opts into a narrower wire form; Min and Max alone
1241
+ -- select nothing. Kept off NumberMeta because a bounded Int already packs from its
1242
+ -- own bounds, so Precision has nothing to say there.
1243
+ export type FloatMeta = { Min: number?, Max: number?, Precision: (number | "f32")? }
1244
+ -- Scribe.Big only. A bound past 1.8e308 must be written as a numeric string, because
1245
+ -- a larger literal is already math.huge and the template validator rejects it.
1246
+ export type BigMeta = { Min: (number | string)?, Max: (number | string)? }
1247
+ export type StringMeta = { MaxLength: number? }
1248
+ -- Scribe.CFrame only. The same knob as FloatMeta's Precision pointing the other way,
1249
+ -- since a CFrame defaults to the lossy form. "exact" is the only value: a CFrame has no
1250
+ -- intermediate widths to name.
1251
+ export type CFrameMeta = { Precision: "exact"? }
1252
+ -- Container declarator options. Not generic in the element type on purpose: an
1253
+ -- element-typed option would let Luau infer the element type from it rather than
1254
+ -- from `shape`, silently redefining the field.
1255
+ export type ArrayOpts = { MaxItems: number?, Evict: ("Front" | "Back")? }
1256
+ export type SetOpts = { MaxItems: number? }
1257
+ export type CooldownOptions = { IncludeOfflineTime: boolean? }
1258
+ export type MapKeyType = "integer" | "string"
1259
+ -- What a Scribe.Big field reads back, which is also what the declarator returns.
1260
+ -- `__scribeBig` lives in the metatable rather than in the fields: a label field travels
1261
+ -- into every read, so `Get().Wealth.__scribeBig` would typecheck while being nil.
1262
+ type BigFields = {
1263
+ M: number,
1264
+ E: number,
1265
+ Short: (self: any, decimals: number?) -> string,
1266
+ ToNumber: (self: any) -> number,
1267
+ -- Pow returns another big, typed `any` rather than BigValue: spelling the recursion
1268
+ -- here tips bundles in test/TypeCheck.luau past the solver's complexity budget. The
1269
+ -- accessor tree gets the real self-referential type from ValueType above.
1270
+ Pow: (self: any, n: number) -> any,
1271
+ Log10: (self: any) -> number,
1272
+ -- The marker stays shallow, like Pow; accessor reads gain exact recursive
1273
+ -- result types from bigValueType above. BigMath.Big is only the M/E shape.
1274
+ Add: (self: any, other: BigMath.Big | number | string) -> any,
1275
+ Subtract: (self: any, other: BigMath.Big | number | string) -> any,
1276
+ Multiply: (self: any, other: BigMath.Big | number | string) -> any,
1277
+ Divide: (self: any, other: BigMath.Big | number | string) -> any,
1278
+ Negate: (self: any) -> any,
1279
+ Compare: (self: any, other: BigMath.Big | number | string) -> number,
1280
+ Equals: (self: any, other: BigMath.Big | number | string) -> boolean,
1281
+ }
1282
+ type BigMt = { __scribeBig: true }
1283
+ export type BigValue = typeof(setmetatable({} :: BigFields, {} :: BigMt))
1284
+ -- What a Scribe.MapOf field reads back: the whole map. The declared key is a
1285
+ -- singleton that has to become a real indexer key type, hence the type function; the
1286
+ -- label and the key ride the metatable, as with Big, Flags and SetOf.
1287
+ -- selene: allow(undefined_variable)
1288
+ type function MapShape(K, V)
1289
+ local ts = types
1290
+ local key = if K:is("singleton") and K:value() == "integer" then ts.number else ts.string
1291
+ local out = ts.newtable(nil, { index = key, readresult = V, writeresult = V }, nil)
1292
+ local mt: { [type]: type } = {}
1293
+ mt[ts.singleton("__scribeMapKey")] = K
1294
+ out:setmetatable(ts.newtable(mt, nil, nil))
1295
+ return out
1296
+ end
1297
+ export type MapOf<K, V> = MapShape<K, V>
1298
+ export type DictOpts = { MaxKeys: number?, MaxKeyLength: number? }
1299
+
1300
+ -- Template-aware config types. Annotate a config local with one and `Stat` / `Cost.Path`
1301
+ -- become the template's numeric leaf-path union while `Grant` receives the typed accessor
1302
+ -- tree. The annotation is required: in the same table literal that declares the template,
1303
+ -- Luau widens the string literals before the template type is known.
1304
+ export type LeaderboardConfig<T = any> = {
1305
+ Stat: StatPathsType<T, true>,
1306
+ Limit: number?,
1307
+ Scale: number?,
1308
+ -- Scribe.Big stats only: significant figures the ranking key carries, 1 to 15
1309
+ -- (default 12). Every extra figure costs a factor of ten of exponent range,
1310
+ -- because the two halves share one integer under 2^53.
1311
+ SigFigs: number?,
1312
+ Replicate: boolean?, -- default false: server-only (Data.GetLeaderboard on the server); true streams the board to clients
1313
+ RefreshInterval: number?, -- approximate seconds between reads of this board (default 60, floor 60, jittered)
1314
+ WriteInterval: number?, -- minimum seconds between changed-score writes per player/store (default 30, minimum 1); ignored for Server scope
1315
+ StoreName: string?, -- override the OrderedDataStore name (default "LB_<board>"); a periodic board appends the period
1316
+ Period: ("Daily" | "Weekly")?, -- a board that resets; nil is lifetime
1317
+ Mode: ("Gain" | "Peak")?, -- with Period: the gain since it began (default) or the peak seen in it
1318
+ Scope: ("Global" | "Server")?, -- "Server" ranks the players on this server, with no store behind it
1319
+ }
1320
+
1321
+ export type ProductConfig<T = any> = {
1322
+ Id: number,
1323
+ Category: string?,
1324
+ Grant: ((data: GrantDataType<T>) -> ())?,
1325
+ Grants: string?,
1326
+ }
1327
+
1328
+ export type PurchaseSpec<T = any> = {
1329
+ Cost: { Path: StatPathsType<T, false>, Amount: number },
1330
+ Category: string?,
1331
+ ItemId: string,
1332
+ Grant: ((data: GrantDataType<T>) -> ())?,
1333
+ Meta: { [string]: any }?,
1334
+ }
1335
+
1336
+ -- Loose, read-only option shapes. They deliberately do not depend on T: inside the
1337
+ -- Scribe({ ... }) literal the template type is still being inferred, so strict fields
1338
+ -- would widen and reject valid configs. Read-only props keep annotated strict tables
1339
+ -- assignable.
1340
+ type LeaderboardConfigLoose = {
1341
+ read Stat: string,
1342
+ read Limit: number?,
1343
+ read Scale: number?,
1344
+ read SigFigs: number?,
1345
+ read Replicate: boolean?,
1346
+ read RefreshInterval: number?,
1347
+ read WriteInterval: number?,
1348
+ read StoreName: string?,
1349
+ read Period: string?,
1350
+ read Mode: string?,
1351
+ read Scope: string?,
1352
+ }
1353
+
1354
+ type ProductConfigLoose = {
1355
+ read Id: number,
1356
+ read Category: string?,
1357
+ read Grant: ((data: any) -> ())?,
1358
+ read Grants: string?,
1359
+ }
1360
+
1361
+ -- Economy is loose for the same reason: a Resolve lambda's parameter would
1362
+ -- generalize inside the literal and a strict field would reject it. Annotate a
1363
+ -- config local with the exported `Scribe.EconomyConfig` for strict checking.
1364
+ type EconomyCurrencyConfigLoose = {
1365
+ read Label: string?,
1366
+ read Fields: { Types.EconomyFieldSpec }?,
1367
+ read Resolve: ((player: any) -> { [string]: any })?,
1368
+ }
1369
+
1370
+ type EconomyConfigLoose = {
1371
+ read Resolve: ((player: any) -> { [string]: any })?,
1372
+ read Prefix: boolean?,
1373
+ read Currencies: { read [string]: EconomyCurrencyConfigLoose }?,
1374
+ read LogEconomyEvent: Types.EconomyLogFn?,
1375
+ }
1376
+
1377
+ --- Passed to ImportLegacyData and OnPlayerInit for pacing legacy-store reads.
1378
+ export type MigrationContext = {
1379
+ --- Yields until `count` requests are spare, or `timeout` passes. Returns whether
1380
+ --- they were granted, and an optional release to call once they have been issued.
1381
+ AwaitBudget: (requestType: string, count: number?, timeout: number?) -> (boolean, () -> ()),
1382
+ }
1383
+
1384
+ export type ScribeOptions<T, S = any> = {
1385
+ Template: T,
1386
+ -- One unsaved tree per server, replicated to everyone.
1387
+ ServerStore: S?,
1388
+ Transport: (Types.ScribeTransport | "Default")?,
1389
+
1390
+ Migrations: { [number]: (data: { [string]: any }) -> () }?,
1391
+ UserOwnsGamePassAsync: ((userId: number, passId: number) -> boolean)?, -- advanced/test seam
1392
+ GetProductInfoAsync: ((assetId: number, infoType: any) -> { [string]: any }?)?, -- advanced/test seam
1393
+ GetPolicyInfoAsync: ((player: Player) -> { [string]: any }?)?, -- advanced/test seam
1394
+ DevMode: boolean?, -- advanced/test seam: overrides the RunService:IsStudio() default
1395
+ IsRunning: boolean?, -- advanced/test seam: overrides the RunService:IsRunning() default (false builds the edit-mode client half)
1396
+ MigrationShadow: boolean?, -- audit aid: re-runs migrations against raw pre-Reconcile data and warns on divergence (re-executes your migration bodies)
1397
+ -- Adopt data from another library, once, before Scribe has ever saved for this player.
1398
+ -- The third argument paces reads on the DataStore budget.
1399
+ ImportLegacyData: ((player: Player, userId: number, migration: MigrationContext) -> { [string]: any }?)?,
1400
+ MigrationConcurrency: number?, -- imports allowed to run at once; defaults to 2
1401
+ -- The fourth argument is the same MigrationContext: ImportLegacyData only fires for a
1402
+ -- player who has never saved, so a game already on Scribe finishes moving here.
1403
+ OnPlayerInit: ((
1404
+ player: Player,
1405
+ rawData: { [string]: any },
1406
+ isNewProfile: boolean,
1407
+ migration: MigrationContext
1408
+ ) -> ())?,
1409
+ OnPlayerLeaving: ((player: Player, data: any, reason: LifecycleReason) -> ())?,
1410
+
1411
+ -- persistence
1412
+ ProfileStoreIndex: string, -- REQUIRED: the DataStore name (each game must name its own store)
1413
+ ProfileKeyPrefix: string, -- REQUIRED: prefix for per-player keys (e.g. "PLAYER_"); "" means bare user-id keys
1414
+ SaveInterval: number?, -- seconds between autosaves per profile (default 300, floor 15)
1415
+ ProfileStore: any?, -- explicit ProfileStore module (module table or ModuleScript)
1416
+ Mode: ("Live" | "Mock" | "NoSave")?, -- persistence mode (default "Live"); overrides the legacy flags below
1417
+ TargetUserId: number?, -- load this user's profile instead of the joining player's
1418
+ -- Legacy persistence flags, superseded by Mode. Still honoured when Mode is
1419
+ -- absent; ignored (with a startup warning) when it is present.
1420
+ UseMock: boolean?,
1421
+ ViewedUserId: number?,
1422
+ OverriddenUserId: number?,
1423
+ DontSave: boolean?,
1424
+ ResetData: boolean?,
1425
+ LoadFailurePolicy: ("Kick" | "Wait")?,
1426
+ LoadTimeout: number?,
1427
+ EraseJoinTimeout: number?,
1428
+ VersionAheadPolicy: ("Kick" | "Allow")?, -- default "Kick": fail closed when data is from a newer deploy
1429
+ KickOnSessionEnd: boolean?,
1430
+ LoadFailureMessage: string?,
1431
+ -- Per-cause overrides for the kick text. Each falls back to LoadFailureMessage when
1432
+ -- that is set, and to its own wording otherwise, so naming one never flattens the rest.
1433
+ LegacyImportFailureMessage: string?,
1434
+ MigrationFailureMessage: string?,
1435
+ VersionAheadMessage: string?,
1436
+ SchemaFailureMessage: string?,
1437
+ RateLimitedMessage: string?,
1438
+ ErasingMessage: string?,
1439
+ SessionEndMessage: string?,
1440
+ -- Per-cause overrides for the session-end kick, falling back to SessionEndMessage.
1441
+ SessionStolenMessage: string?,
1442
+ SessionInterruptedMessage: string?,
1443
+
1444
+ -- services
1445
+ Leaderboards: { read [string]: LeaderboardConfigLoose }?,
1446
+ PeriodReset: { read UtcOffset: number?, read WeekStart: string? }?, -- the clock periodic boards reset on: hours from UTC (-12 to 14, default 0) and the day a week starts (default Monday)
1447
+ Products: { read [string]: ProductConfigLoose }?,
1448
+ RetiredProducts: { read [string]: ProductConfigLoose }?,
1449
+ Passes: { [string]: PassConfig }?,
1450
+ Perks: { string }?,
1451
+ OwnReceipts: boolean?,
1452
+
1453
+ -- exchanging
1454
+ Exchangeable: { [string]: ExchangeableSpec }?,
1455
+ PurchaseLog: {
1456
+ RobuxCap: number?,
1457
+ InGameCap: number?,
1458
+ ReplicateRobux: boolean?,
1459
+ ReplicateInGame: boolean?,
1460
+ PurchaseLogCategories: { string }?,
1461
+ }?,
1462
+
1463
+ -- gifting
1464
+ GiftCooldown: number?,
1465
+ GiftMaxPending: number?,
1466
+ GiftIntentTTL: number?,
1467
+ PurchaseIdTTL: number?,
1468
+ MaxProcessedPurchaseIds: number?,
1469
+ MaxReceiptHistoryBytes: number?,
1470
+ PurchaseClaimTTL: number?,
1471
+ MaxPurchaseClaims: number?,
1472
+ AllowDuplicateGifts: boolean?,
1473
+ NoGiftIntentPolicy: ("GrantOrCredit" | "Hold")?,
1474
+
1475
+ -- economy analytics
1476
+ Economy: EconomyConfigLoose?,
1477
+
1478
+ -- behaviour / limits
1479
+ CommandRateLimit: number?,
1480
+ RequestTimeout: number?,
1481
+ MaxInboundBytes: number?,
1482
+ MaxInboundRetainedBytes: number?,
1483
+ MaxOutboundBytes: number?,
1484
+ MaxInboundFrameRate: number?,
1485
+ TransportChannel: string?,
1486
+
1487
+ -- integrity
1488
+ BoundsPolicy: ("Clamp" | "Reject")?,
1489
+ WipeGuardPolicy: ("Warn" | "Block")?,
1490
+ SchemaPolicy: ("Warn" | "Reject")?, -- check stored data against the template at load; off when absent
1491
+ BudgetPolicy: "Defer"?, -- burst-drain eligible leaderboard writes and budget-pace erasure; background request pacing is always on
1492
+ WipeGuardShrinkRatio: number?,
1493
+
1494
+ -- diagnostics
1495
+ LogLevel: ("Debug" | "Info" | "Warn" | "Error" | "Fatal")?,
1496
+ LogRingLevel: Types.LogLevel?,
1497
+ LogRingSize: number?, -- entries Log.GetRecent retains (default 512)
1498
+ StatusThresholds: { FailWindow: number?, FailCount: number?, RecoverStreak: number? }?,
1499
+ Banner: boolean?, -- default true: print one "Scribe vX.Y.Z ... ready" line on load
1500
+ StudioHook: boolean?, -- default false: the Studio debug hooks the Scribe Studio plugin reads
1501
+ }
1502
+
1503
+ export type ServerData<T, S = any> = BuildServerDataType<T, Player, S>
1504
+
1505
+ export type ClientData<T, S = any> = BuildClientDataType<T, S>
1506
+
1507
+ -- One player's typed accessor tree: the type of `Data[player]`, `Data.Get(player)` and
1508
+ -- the client's `Data.Get()`. A plain alias because a type function cannot be invoked
1509
+ -- across a module boundary: `Scribe.ValueType<T>` silently resolves to `any` rather than
1510
+ -- erroring, so this is the only way a consumer can name the type.
1511
+ export type PlayerData<T> = ValueType<T>
1512
+
1513
+ export type Bundle<T, S = any> = {
1514
+ Server: ServerData<T, S>,
1515
+ Client: ClientData<T, S>,
1516
+ }
1517
+
1518
+ --------------------------------------------------------------------------------
1519
+ -- Exported type reference
1520
+ --
1521
+ -- Doc blocks for the exported types, gathered here rather than beside the declarations:
1522
+ -- @interface/@type blocks are keyed by name, and half of these types are re-exported
1523
+ -- from Types.luau with nothing here to sit beside. A new exported type needs a block or
1524
+ -- it renders nowhere.
1525
+ --------------------------------------------------------------------------------
1526
+
1527
+ --------------------------------------------------------------------------------
1528
+ -- Runtime
1529
+ --------------------------------------------------------------------------------
1530
+
1531
+ local KNOWN_OPTION_KEYS: { [string]: boolean } = {
1532
+ Template = true,
1533
+ ServerStore = true,
1534
+ Exchangeable = true,
1535
+ Transport = true,
1536
+ TransportChannel = true,
1537
+ Migrations = true,
1538
+ UserOwnsGamePassAsync = true,
1539
+ GetProductInfoAsync = true,
1540
+ GetPolicyInfoAsync = true,
1541
+ DevMode = true,
1542
+ IsRunning = true,
1543
+ MigrationShadow = true,
1544
+ ImportLegacyData = true,
1545
+ MigrationConcurrency = true,
1546
+ OnPlayerInit = true,
1547
+ OnPlayerLeaving = true,
1548
+ ProfileStoreIndex = true,
1549
+ ProfileKeyPrefix = true,
1550
+ SaveInterval = true,
1551
+ ProfileStore = true,
1552
+ Mode = true,
1553
+ TargetUserId = true,
1554
+ UseMock = true,
1555
+ ViewedUserId = true,
1556
+ OverriddenUserId = true,
1557
+ DontSave = true,
1558
+ ResetData = true,
1559
+ LoadFailurePolicy = true,
1560
+ LoadTimeout = true,
1561
+ EraseJoinTimeout = true,
1562
+ VersionAheadPolicy = true,
1563
+ KickOnSessionEnd = true,
1564
+ LoadFailureMessage = true,
1565
+ LegacyImportFailureMessage = true,
1566
+ MigrationFailureMessage = true,
1567
+ VersionAheadMessage = true,
1568
+ SchemaFailureMessage = true,
1569
+ RateLimitedMessage = true,
1570
+ ErasingMessage = true,
1571
+ SessionEndMessage = true,
1572
+ SessionStolenMessage = true,
1573
+ SessionInterruptedMessage = true,
1574
+ Leaderboards = true,
1575
+ PeriodReset = true,
1576
+ Products = true,
1577
+ RetiredProducts = true,
1578
+ Passes = true,
1579
+ Perks = true,
1580
+ OwnReceipts = true,
1581
+ PurchaseLog = true,
1582
+ GiftCooldown = true,
1583
+ GiftMaxPending = true,
1584
+ GiftIntentTTL = true,
1585
+ PurchaseIdTTL = true,
1586
+ MaxProcessedPurchaseIds = true,
1587
+ MaxReceiptHistoryBytes = true,
1588
+ PurchaseClaimTTL = true,
1589
+ MaxPurchaseClaims = true,
1590
+ AllowDuplicateGifts = true,
1591
+ NoGiftIntentPolicy = true,
1592
+ Economy = true,
1593
+ CommandRateLimit = true,
1594
+ RequestTimeout = true,
1595
+ MaxInboundBytes = true,
1596
+ MaxInboundRetainedBytes = true,
1597
+ MaxOutboundBytes = true,
1598
+ MaxInboundFrameRate = true,
1599
+ BoundsPolicy = true,
1600
+ WipeGuardPolicy = true,
1601
+ SchemaPolicy = true,
1602
+ BudgetPolicy = true,
1603
+ WipeGuardShrinkRatio = true,
1604
+ LogLevel = true,
1605
+ LogRingLevel = true,
1606
+ LogRingSize = true,
1607
+ StatusThresholds = true,
1608
+ Banner = true,
1609
+ StudioHook = true,
1610
+ }
1611
+
1612
+ local function buildBundle<T, S>(options: ScribeOptions<T, S>): Bundle<T, S>
1613
+ if type(options) ~= "table" then
1614
+ error("Scribe: options must be a table", 2)
1615
+ end
1616
+ if type((options :: any).Template) ~= "table" then
1617
+ error("Scribe: options.Template is required and must be a table", 2)
1618
+ end
1619
+ local anyOpts = options :: any
1620
+ -- Server only on purpose: the client reads neither of these. Validating them before
1621
+ -- the realm branch would force the live DataStore name and key format into the shared
1622
+ -- module every client requires, rather than behind `if RunService:IsServer()`.
1623
+ if RunService:IsServer() then
1624
+ -- Storage location is intentional, never defaulted: two games (or a test
1625
+ -- build) accidentally sharing the "Default" store is a silent data hazard.
1626
+ if type(anyOpts.ProfileStoreIndex) ~= "string" or anyOpts.ProfileStoreIndex == "" then
1627
+ error("Scribe: options.ProfileStoreIndex is required: name your game's DataStore explicitly", 2)
1628
+ end
1629
+ -- Required, but "" is legitimate: it means bare user-id keys, which is what a
1630
+ -- game adopting an existing store keyed only by user id needs. Absent or
1631
+ -- non-string is still an error, so the choice stays explicit.
1632
+ if type(anyOpts.ProfileKeyPrefix) ~= "string" then
1633
+ error(
1634
+ 'Scribe: options.ProfileKeyPrefix is required: set a per-player key prefix (e.g. "PLAYER_"), or "" for bare user-id keys',
1635
+ 2
1636
+ )
1637
+ end
1638
+ end
1639
+
1640
+ -- Scribe.Configure refuses to run past this point, because its process-wide values
1641
+ -- are applied during construction. Set after the option guards, so a call that
1642
+ -- only fails a guard does not poison the flag for a later Configure.
1643
+ Config.BundleConstructed = true
1644
+
1645
+ -- Luau does not reject unknown table keys, so a misspelled option name is silently
1646
+ -- ignored. Catch it in Studio with a startup warning.
1647
+ if RunService:IsStudio() then
1648
+ for key in options :: any do
1649
+ if type(key) == "string" and not KNOWN_OPTION_KEYS[key] then
1650
+ Log.Warn(
1651
+ "Lifecycle",
1652
+ "UNKNOWN_OPTION",
1653
+ `unknown Scribe option "{key}": check the spelling`,
1654
+ { Option = key }
1655
+ )
1656
+ end
1657
+ end
1658
+ end
1659
+
1660
+ local anyOptions = options :: any
1661
+ local purchaseLog = anyOptions.PurchaseLog or {}
1662
+ -- Purchase logs are server-only unless explicitly opted in: they exist for
1663
+ -- auditing/support first, and most games never show them to the client.
1664
+ local compiled = Template.Compile(anyOptions.Template, {
1665
+ ReplicateRobuxLog = purchaseLog.ReplicateRobux == true,
1666
+ ReplicateInGameLog = purchaseLog.ReplicateInGame == true,
1667
+ ServerStore = anyOptions.ServerStore,
1668
+ })
1669
+
1670
+ -- Template safety: deep-freeze after compilation; any accidental
1671
+ -- mutation of the shared template throws at the call site.
1672
+ Util.deepFreeze(anyOptions.Template)
1673
+ Util.deepFreeze(anyOptions.ServerStore)
1674
+
1675
+ -- A Sandboxed script cannot fire a non-Sandboxed event, so a Sandboxed Scribe
1676
+ -- silently never sends a replication frame and nothing syncs. Usually caused by
1677
+ -- inserting the package from the toolbox rather than syncing it from source.
1678
+ local sandboxOk, sandboxed = pcall(function()
1679
+ return (script :: any).Sandboxed
1680
+ end)
1681
+ if sandboxOk and sandboxed == true then
1682
+ Log.Warn(
1683
+ "Lifecycle",
1684
+ "SANDBOXED",
1685
+ "the Scribe package is Sandboxed, so it cannot fire its replication RemoteEvents and nothing will sync. "
1686
+ .. "Set Sandboxed = false on the Scribe package (and ProfileStore).",
1687
+ {}
1688
+ )
1689
+ end
1690
+
1691
+ -- Edit mode (a storybook, the command bar, a plugin) has no server, yet
1692
+ -- RunService:IsServer() is still true there. Dispatching on that alone builds the
1693
+ -- server half, which resolves the transport and leaves RemoteEvents saved into the
1694
+ -- place file; the client half understands edit mode. `IsRunning` is also the seam
1695
+ -- specs use, since RunService cannot be patched.
1696
+ local isRunning = if anyOptions.IsRunning ~= nil then anyOptions.IsRunning == true else RunService:IsRunning()
1697
+
1698
+ local bundle: any
1699
+ if RunService:IsServer() and isRunning then
1700
+ local Server = require(script.Server) :: any
1701
+ local serverData = Server.new(anyOptions, compiled)
1702
+ local clientStub = setmetatable({}, {
1703
+ __index = function()
1704
+ error("Scribe: the Client API is not available on the server", 2)
1705
+ end,
1706
+ })
1707
+ bundle = { Server = serverData, Client = clientStub }
1708
+ else
1709
+ local Client = require(script.Client) :: any
1710
+ local clientData = Client.new(anyOptions, compiled)
1711
+ local serverStub = setmetatable({}, {
1712
+ __index = function()
1713
+ error(
1714
+ if isRunning
1715
+ then "Scribe: the Server API is not available on the client. Client writes go through Data.Request commands"
1716
+ else "Scribe: the Server API is not available in edit mode. Scribe builds only the client half there (storybooks, the command bar)",
1717
+ 2
1718
+ )
1719
+ end,
1720
+ })
1721
+ bundle = { Server = serverStub, Client = clientData }
1722
+ end
1723
+
1724
+ -- Studio-only: expose the (frozen) raw template so Scribe Studio's
1725
+ -- edit-mode lint can introspect the canonical bundle-returning module.
1726
+ if RunService:IsStudio() then
1727
+ bundle.__ScribeTemplate = anyOptions.Template
1728
+ end
1729
+
1730
+ return bundle :: any
1731
+ end
1732
+
1733
+ -- Shared entry point for bundle creation, declarators, and diagnostics.
1734
+ local Scribe = {}
1735
+
1736
+ Scribe.Version = require(script.Internal.Version)
1737
+
1738
+ -- Keeps this field and its subtree off the client.
1739
+ function Scribe.ServerOnly<T>(value: T): ServerOnly<T>
1740
+ return Marker.make("ServerOnly", value) :: any
1741
+ end
1742
+
1743
+ -- Replicates a root field to every client.
1744
+ function Scribe.Shared<T>(value: T): T
1745
+ return Marker.make("Shared", value) :: any
1746
+ end
1747
+
1748
+ -- Keeps a root field unsaved; its visibility wrappers still apply.
1749
+ function Scribe.Session<T>(value: T): T
1750
+ return Marker.make("Session", value) :: any
1751
+ end
1752
+
1753
+ -- Declares integer data with optional bounds.
1754
+ function Scribe.Int(default: number, meta: NumberMeta?): number
1755
+ return Marker.make("Int", default, meta :: any) :: any
1756
+ end
1757
+
1758
+ -- Declares floating-point data with optional bounds and wire precision.
1759
+ function Scribe.Number(default: number, meta: FloatMeta?): number
1760
+ return Marker.make("Number", default, meta :: any) :: any
1761
+ end
1762
+
1763
+ -- Declares large-range numbers; numeric strings are limited to 256 bytes.
1764
+ function Scribe.Big(default: (number | string)?, meta: BigMeta?): BigValue
1765
+ return Marker.make("Big", if default == nil then 0 else default, meta :: any) :: any
1766
+ end
1767
+
1768
+ -- Declares string data with an optional byte limit.
1769
+ function Scribe.String(default: string, meta: StringMeta?): string
1770
+ return Marker.make("String", default, meta :: any) :: any
1771
+ end
1772
+
1773
+ -- Restricts a string field to the declared members.
1774
+ function Scribe.Enum(default: string, members: { string }): string
1775
+ return Marker.make("Enum", default, { Members = members }) :: any
1776
+ end
1777
+
1778
+ -- Stores up to 32 named booleans as one field.
1779
+ function Scribe.Flags(members: { string }): Flags
1780
+ return Marker.make("Flags", {}, { Members = members }) :: any
1781
+ end
1782
+
1783
+ -- Declares a leaf reset to its default after SetTimed expires.
1784
+ function Scribe.Timed<T>(default: T): Timed<T>
1785
+ return Marker.make("Timed", default) :: any
1786
+ end
1787
+
1788
+ -- Seeds missing profile values with a pure factory, also sampled at declaration.
1789
+ -- `(...any) -> T` (not `() -> T`) so standard-library functions with optional
1790
+ -- params typecheck when passed directly, e.g. `Scribe.Dynamic(os.time)`.
1791
+ function Scribe.Dynamic<T>(factory: (...any) -> T): T
1792
+ return Marker.make("Dynamic", factory(), { Factory = factory :: any }) :: any
1793
+ end
1794
+
1795
+ -- Declares a read-only value computed from named inputs; compute must be pure.
1796
+ function Scribe.Derived<T>(output: T, inputs: { string }, compute: (...any) -> T): Derived<T>
1797
+ return Marker.make("Derived", output, { Inputs = inputs, Compute = compute :: any }) :: any
1798
+ end
1799
+
1800
+ -- Allows an absent leaf value; the inner default is not seeded.
1801
+ function Scribe.Optional<T>(inner: T): T?
1802
+ return Marker.make("Optional", inner) :: any
1803
+ end
1804
+
1805
+ -- Declares a typed array with optional size and eviction limits.
1806
+ function Scribe.ArrayOf<T>(shape: T, opts: ArrayOpts?): { T }
1807
+ if opts ~= nil then
1808
+ for key in opts :: any do
1809
+ -- A silently dropped option (MaxKeys on an ArrayOf, say) leaves the
1810
+ -- container uncapped while reading as protected; refuse it.
1811
+ if key ~= "MaxItems" and key ~= "Evict" then
1812
+ error(`Scribe.ArrayOf: unknown option "{tostring(key)}" (ArrayOf takes MaxItems and Evict)`, 2)
1813
+ end
1814
+ end
1815
+ end
1816
+ return Marker.make("ArrayOf", nil, {
1817
+ Element = shape,
1818
+ MaxItems = if opts then opts.MaxItems else nil,
1819
+ Evict = if opts then opts.Evict else nil,
1820
+ }) :: any
1821
+ end
1822
+
1823
+ -- Declares unique scalar members with an optional size limit.
1824
+ function Scribe.SetOf<T>(element: T, opts: SetOpts?): SetOf<T>
1825
+ if opts ~= nil then
1826
+ for key in opts :: any do
1827
+ if key ~= "MaxItems" then
1828
+ error(`Scribe.SetOf: unknown option "{tostring(key)}" (SetOf takes MaxItems)`, 2)
1829
+ end
1830
+ end
1831
+ end
1832
+ -- A set is deduplicated and sorted, neither of which works on a record: table.sort
1833
+ -- throws a bare comparison error on the second member. Refuse it here rather than at
1834
+ -- the surprising second Add.
1835
+ if type(element) == "table" and (element :: any).__scribeMarker == nil then
1836
+ error("Scribe.SetOf takes a scalar element (Scribe.String, Scribe.Int, ...), not a record shape", 2)
1837
+ end
1838
+ return Marker.make("SetOf", nil, {
1839
+ Element = element,
1840
+ MaxItems = if opts then opts.MaxItems else nil,
1841
+ Unique = true,
1842
+ }) :: any
1843
+ end
1844
+
1845
+ -- Declares a map with integer or string keys and a value schema.
1846
+ function Scribe.MapOf<K, V>(keyType: K & MapKeyType, value: V, opts: DictOpts?): MapOf<K, V>
1847
+ if keyType ~= "integer" and keyType ~= "string" then
1848
+ error(`Scribe.MapOf: keyType must be "integer" or "string", got {tostring(keyType)}`, 2)
1849
+ end
1850
+ if opts ~= nil then
1851
+ for key in opts :: any do
1852
+ if key ~= "MaxKeys" and key ~= "MaxKeyLength" then
1853
+ error(`Scribe.MapOf: unknown option "{tostring(key)}" (MapOf takes MaxKeys and MaxKeyLength)`, 2)
1854
+ end
1855
+ end
1856
+ end
1857
+ if keyType == "integer" and opts ~= nil and (opts :: any).MaxKeyLength ~= nil then
1858
+ error("Scribe.MapOf: MaxKeyLength applies to string keys only", 2)
1859
+ end
1860
+ return Marker.make("MapOf", nil, {
1861
+ Element = value,
1862
+ KeyType = keyType,
1863
+ MaxKeys = if opts then opts.MaxKeys else nil,
1864
+ MaxKeyLength = if opts then opts.MaxKeyLength else nil,
1865
+ }) :: any
1866
+ end
1867
+
1868
+ -- Declares a string-keyed dictionary with a value schema and optional limits.
1869
+ function Scribe.DictOf<V>(shape: V, opts: DictOpts?): { [string]: V }
1870
+ if opts ~= nil then
1871
+ for key in opts :: any do
1872
+ if key ~= "MaxKeys" and key ~= "MaxKeyLength" then
1873
+ error(`Scribe.DictOf: unknown option "{tostring(key)}" (DictOf takes MaxKeys and MaxKeyLength)`, 2)
1874
+ end
1875
+ end
1876
+ end
1877
+ return Marker.make("DictOf", nil, {
1878
+ Element = shape,
1879
+ MaxKeys = if opts then opts.MaxKeys else nil,
1880
+ MaxKeyLength = if opts then opts.MaxKeyLength else nil,
1881
+ }) :: any
1882
+ end
1883
+
1884
+ -- Roblox datatype fields (opt-in serialization): stored and replicated as a
1885
+ -- compact packed buffer; Get/Set/Update/Observe convert at the boundary so
1886
+ -- callers only ever see the real datatype.
1887
+ local function datatypeMarker(name: string, default: any, precision: string?): any
1888
+ return Marker.make("Datatype", default, { Datatype = name, Precision = precision })
1889
+ end
1890
+
1891
+ -- Declares Vector3 data, packed for storage and replication.
1892
+ function Scribe.Vector3(default: Vector3): Vector3
1893
+ return datatypeMarker("Vector3", default)
1894
+ end
1895
+
1896
+ function Scribe.Vector2(default: Vector2): Vector2
1897
+ return datatypeMarker("Vector2", default)
1898
+ end
1899
+
1900
+ function Scribe.Vector3int16(default: Vector3int16): Vector3int16
1901
+ return datatypeMarker("Vector3int16", default)
1902
+ end
1903
+
1904
+ function Scribe.Vector2int16(default: Vector2int16): Vector2int16
1905
+ return datatypeMarker("Vector2int16", default)
1906
+ end
1907
+
1908
+ -- Declares packed CFrame data; Precision = "exact" preserves its f32 components.
1909
+ function Scribe.CFrame(default: CFrame, meta: CFrameMeta?): CFrame
1910
+ if meta ~= nil then
1911
+ for key in meta :: any do
1912
+ if key ~= "Precision" then
1913
+ error(`Scribe.CFrame: unknown option "{tostring(key)}" (CFrame takes Precision)`, 2)
1914
+ end
1915
+ end
1916
+ end
1917
+ return datatypeMarker("CFrame", default, if meta then meta.Precision else nil)
1918
+ end
1919
+
1920
+ function Scribe.Color3(default: Color3): Color3
1921
+ return datatypeMarker("Color3", default)
1922
+ end
1923
+
1924
+ function Scribe.BrickColor(default: BrickColor): BrickColor
1925
+ return datatypeMarker("BrickColor", default)
1926
+ end
1927
+
1928
+ function Scribe.UDim(default: UDim): UDim
1929
+ return datatypeMarker("UDim", default)
1930
+ end
1931
+
1932
+ function Scribe.UDim2(default: UDim2): UDim2
1933
+ return datatypeMarker("UDim2", default)
1934
+ end
1935
+
1936
+ function Scribe.Rect(default: Rect): Rect
1937
+ return datatypeMarker("Rect", default)
1938
+ end
1939
+
1940
+ function Scribe.NumberRange(default: NumberRange): NumberRange
1941
+ return datatypeMarker("NumberRange", default)
1942
+ end
1943
+
1944
+ function Scribe.NumberSequence(default: NumberSequence): NumberSequence
1945
+ return datatypeMarker("NumberSequence", default)
1946
+ end
1947
+
1948
+ function Scribe.ColorSequence(default: ColorSequence): ColorSequence
1949
+ return datatypeMarker("ColorSequence", default)
1950
+ end
1951
+
1952
+ function Scribe.DateTime(default: DateTime): DateTime
1953
+ return datatypeMarker("DateTime", default)
1954
+ end
1955
+
1956
+ function Scribe.EnumItem(default: EnumItem): EnumItem
1957
+ return datatypeMarker("EnumItem", default)
1958
+ end
1959
+
1960
+ function Scribe.Font(default: Font): Font
1961
+ return datatypeMarker("Font", default)
1962
+ end
1963
+
1964
+ function Scribe.PhysicalProperties(default: PhysicalProperties): PhysicalProperties
1965
+ return datatypeMarker("PhysicalProperties", default)
1966
+ end
1967
+
1968
+ -- Codec helpers for packing and unpacking Roblox datatypes.
1969
+ Scribe.Datatypes = require(script.Internal.Datatypes)
1970
+
1971
+ -- Formats a number or Big value with suffixes and rounded decimal places.
1972
+ function Scribe.Short(value: (number | BigValue)?, decimals: number?): string
1973
+ if decimals ~= nil and (type(decimals) ~= "number" or decimals < 0 or decimals % 1 ~= 0) then
1974
+ error(`Scribe.Short: decimals must be a non-negative whole number, got {tostring(decimals)}`, 2)
1975
+ end
1976
+ local big = BigMath.from(value)
1977
+ if big == nil then
1978
+ error(`Scribe.Short: expected a number or a Scribe.Big value, got {typeof(value)}`, 2)
1979
+ end
1980
+ return BigMath.toShort(big, decimals)
1981
+ end
1982
+
1983
+ -- Replaces suffixes used by Short; the first suffix must be empty.
1984
+ function Scribe.SetShortSuffixes(suffixes: { string })
1985
+ BigMath.SetSuffixes(suffixes)
1986
+ end
1987
+
1988
+ -- Sets process-wide options before any bundle is built; conflicting calls error.
1989
+ function Scribe.Configure(config: { AutoSaveInterval: number? })
1990
+ if type(config) ~= "table" then
1991
+ error("Scribe.Configure: config must be a table", 2)
1992
+ end
1993
+ for key in config :: { [string]: any } do
1994
+ if key ~= "AutoSaveInterval" then
1995
+ error(`Scribe.Configure: unknown key "{tostring(key)}" (Configure takes AutoSaveInterval)`, 2)
1996
+ end
1997
+ end
1998
+ if Config.BundleConstructed then
1999
+ error("Scribe.Configure must be called before any Scribe bundle is constructed", 2)
2000
+ end
2001
+ local interval = config.AutoSaveInterval
2002
+ if interval ~= nil then
2003
+ if type(interval) ~= "number" or interval ~= interval or interval <= 0 then
2004
+ error("Scribe.Configure: AutoSaveInterval must be a positive number of seconds", 2)
2005
+ end
2006
+ if
2007
+ Config.AutoSaveSource == "Configure"
2008
+ and Config.AutoSaveInterval ~= nil
2009
+ and Config.AutoSaveInterval ~= interval
2010
+ then
2011
+ error(
2012
+ `Scribe.Configure: AutoSaveInterval was already set to {Config.AutoSaveInterval}; `
2013
+ .. "it is a process-wide setting, so configure it once",
2014
+ 2
2015
+ )
2016
+ end
2017
+ Config.AutoSaveInterval = interval
2018
+ Config.AutoSaveSource = "Configure"
2019
+ end
2020
+ end
2021
+
2022
+ Scribe.Reason = table.freeze({
2023
+ LoadFailed = "load-failed" :: Types.LifecycleReason,
2024
+ MigrationFailed = "migration-failed" :: Types.LifecycleReason,
2025
+ Erasing = "erasing" :: Types.LifecycleReason,
2026
+ SessionEnded = "session-ended" :: Types.LifecycleReason,
2027
+ PlayerLeft = "player-left" :: Types.LifecycleReason,
2028
+ Shutdown = "shutdown" :: Types.LifecycleReason,
2029
+ StillLoading = "still-loading" :: Types.LifecycleReason,
2030
+ Timeout = "timeout" :: Types.LifecycleReason,
2031
+ })
2032
+
2033
+ -- Named framework refusals for Request; handlers may return their own reasons.
2034
+ Scribe.RequestReason = table.freeze({
2035
+ RateLimited = "rate-limited" :: Types.RequestReason,
2036
+ NotReady = "not-ready" :: Types.RequestReason,
2037
+ UnknownCommand = "unknown-command" :: Types.RequestReason,
2038
+ BadArgs = "bad-args" :: Types.RequestReason,
2039
+ BadIdempotencyKey = "bad-idempotency-key" :: Types.RequestReason,
2040
+ Error = "error" :: Types.RequestReason,
2041
+ ReplyEncodeFailed = "reply-encode-failed" :: Types.RequestReason,
2042
+ Timeout = "timeout" :: Types.RequestReason,
2043
+ SendFailed = "send-failed" :: Types.RequestReason,
2044
+ EditMode = "edit-mode" :: Types.RequestReason,
2045
+ MockError = "mock-error" :: Types.RequestReason,
2046
+ })
2047
+
2048
+ -- Identity marker distinguishing framework request failures from handler replies.
2049
+ Scribe.RequestFailed = Types.RequestFailed
2050
+
2051
+ -- Fixed soft-currency purchase refusals; grant errors return their own text.
2052
+ Scribe.PurchaseReason = table.freeze({
2053
+ DataNotLoaded = "player data not loaded" :: Types.PurchaseReason,
2054
+ InvalidCostSpec = "invalid Cost spec" :: Types.PurchaseReason,
2055
+ InvalidCostAmount = "invalid Cost amount" :: Types.PurchaseReason,
2056
+ InvalidCostPath = "invalid cost path" :: Types.PurchaseReason,
2057
+ CostPathNotSpendable = "cost path is not a spendable number" :: Types.PurchaseReason,
2058
+ InsufficientFunds = "insufficient funds" :: Types.PurchaseReason,
2059
+ PaidRandomRestricted = "paid random items are not available for this account" :: Types.PurchaseReason,
2060
+ PolicyPending = "cannot check account settings right now; try again in a moment" :: Types.PurchaseReason,
2061
+ })
2062
+
2063
+ -- Fixed gift refusals; other failures may return diagnostic text.
2064
+ Scribe.GiftReason = table.freeze({
2065
+ ProductRetired = "product retired" :: Types.GiftReason,
2066
+ BuyerDataNotLoaded = "buyer data not loaded" :: Types.GiftReason,
2067
+ InvalidRecipient = "invalid recipient" :: Types.GiftReason,
2068
+ CannotGiftYourself = "cannot gift yourself" :: Types.GiftReason,
2069
+ GiftCooldown = "gift cooldown" :: Types.GiftReason,
2070
+ TooManyPending = "too many pending gifts" :: Types.GiftReason,
2071
+ DataServicesDown = "data services are experiencing issues; try again later" :: Types.GiftReason,
2072
+ RecipientAlreadyOwns = "recipient already owns this" :: Types.GiftReason,
2073
+ CreditReserveFailed = "could not reserve gift credit; try again later" :: Types.GiftReason,
2074
+ DeliveryFailed = "could not deliver gift; try again later" :: Types.GiftReason,
2075
+ DeliveryUnconfirmed = "gift delivery could not be confirmed; do not send it again" :: Types.GiftReason,
2076
+ AlreadyPending = "a gift of this item is already pending; try again shortly" :: Types.GiftReason,
2077
+ IntentRecordFailed = "could not record gift intent; try again later" :: Types.GiftReason,
2078
+ PaidRandomRestricted = "paid random items are not available for this account" :: Types.GiftReason,
2079
+ PolicyPending = "cannot check account settings right now; try again in a moment" :: Types.GiftReason,
2080
+ })
2081
+
2082
+ -- Named eligibility states for product queries and purchase prompts.
2083
+ Scribe.ProductState = table.freeze({
2084
+ Purchasable = "purchasable" :: Types.ProductState,
2085
+ Owned = "owned" :: Types.ProductState,
2086
+ PaidRandomRestricted = "paid-random-restricted" :: Types.ProductState,
2087
+ PolicyPending = "policy-pending" :: Types.ProductState,
2088
+ NotLoaded = "not-loaded" :: Types.ProductState,
2089
+ })
2090
+
2091
+ -- Named replication operations for diagnostics.
2092
+ Scribe.OpKind = table.freeze({
2093
+ Init = "Init" :: Types.OpKind,
2094
+ Set = "Set" :: Types.OpKind,
2095
+ Insert = "Insert" :: Types.OpKind,
2096
+ Remove = "Remove" :: Types.OpKind,
2097
+ Clear = "Clear" :: Types.OpKind,
2098
+ })
2099
+
2100
+ -- Named severity levels for logging and log filters.
2101
+ Scribe.LogLevel = table.freeze({
2102
+ Debug = "Debug" :: Types.LogLevel,
2103
+ Info = "Info" :: Types.LogLevel,
2104
+ Warn = "Warn" :: Types.LogLevel,
2105
+ Error = "Error" :: Types.LogLevel,
2106
+ Fatal = "Fatal" :: Types.LogLevel,
2107
+ })
2108
+
2109
+ -- Named subsystem categories for log filters.
2110
+ Scribe.LogCategory = table.freeze({
2111
+ Persistence = "Persistence" :: Types.LogCategory,
2112
+ Replication = "Replication" :: Types.LogCategory,
2113
+ Transport = "Transport" :: Types.LogCategory,
2114
+ Commands = "Commands" :: Types.LogCategory,
2115
+ Leaderboards = "Leaderboards" :: Types.LogCategory,
2116
+ Monetization = "Monetization" :: Types.LogCategory,
2117
+ Gifting = "Gifting" :: Types.LogCategory,
2118
+ Integrity = "Integrity" :: Types.LogCategory,
2119
+ Lifecycle = "Lifecycle" :: Types.LogCategory,
2120
+ Derived = "Derived" :: Types.LogCategory,
2121
+ Exchanges = "Exchanges" :: Types.LogCategory,
2122
+ })
2123
+
2124
+ -- Named DataStore health states.
2125
+ Scribe.Status = table.freeze({
2126
+ Healthy = "Healthy" :: Types.Status,
2127
+ Degraded = "Degraded" :: Types.Status,
2128
+ Outage = "Outage" :: Types.Status,
2129
+ })
2130
+
2131
+ -- Named per-board health states, separate from DataStore health.
2132
+ Scribe.LeaderboardStatus = table.freeze({
2133
+ Starting = "Starting" :: Types.LeaderboardStatus,
2134
+ Healthy = "Healthy" :: Types.LeaderboardStatus,
2135
+ Degraded = "Degraded" :: Types.LeaderboardStatus,
2136
+ })
2137
+
2138
+ -- Named profile lifecycle states returned by GetState.
2139
+ Scribe.SessionState = table.freeze({
2140
+ Loading = "Loading" :: Types.SessionState,
2141
+ Ready = "Ready" :: Types.SessionState,
2142
+ SessionEnded = "SessionEnded" :: Types.SessionState,
2143
+ })
2144
+
2145
+ -- Named stages reported while a profile is loading.
2146
+ Scribe.LoadPhase = table.freeze({
2147
+ WaitingForErase = "WaitingForErase" :: Types.LoadPhase,
2148
+ AcquiringSession = "AcquiringSession" :: Types.LoadPhase,
2149
+ ReadingProfile = "ReadingProfile" :: Types.LoadPhase,
2150
+ Retrying = "Retrying" :: Types.LoadPhase,
2151
+ Initializing = "Initializing" :: Types.LoadPhase,
2152
+ Importing = "Importing" :: Types.LoadPhase,
2153
+ ImportThrottled = "ImportThrottled" :: Types.LoadPhase,
2154
+ })
2155
+
2156
+ -- Named replication targets for declared fields.
2157
+ Scribe.Visibility = table.freeze({
2158
+ Replicated = "Replicated" :: Types.Visibility,
2159
+ ServerOnly = "ServerOnly" :: Types.Visibility,
2160
+ Shared = "Shared" :: Types.Visibility,
2161
+ })
2162
+
2163
+ -- Alias of Reason using the matching exported type name.
2164
+ Scribe.LifecycleReason = Scribe.Reason
2165
+
2166
+ -- Returns the server bundle prefix, or PLAYER_ before setup and on clients.
2167
+ function Scribe.GetProfileKeyPrefix(): string
2168
+ return Addons.ProfileKeyPrefix()
2169
+ end
2170
+
2171
+ -- Returns current DataStore health.
2172
+ function Scribe.GetStatus(): Status
2173
+ return Health.GetStatus()
2174
+ end
2175
+
2176
+ -- Returns cached board health without DataStore requests; empty on clients.
2177
+ function Scribe.GetLeaderboardSnapshot(): { LeaderboardSnapshotEntry }
2178
+ return if RunService:IsServer() then LeaderboardDiagnostics.Snapshot() else {}
2179
+ end
2180
+
2181
+ -- Fires when DataStore health changes.
2182
+ Scribe.OnStatusChanged = Health.OnStatusChanged
2183
+
2184
+ -- Fires for each Error or Fatal log entry.
2185
+ Scribe.OnIssue = Log.OnIssue
2186
+
2187
+ -- Adds a filtered, bounded log sink; returns its disconnect function.
2188
+ function Scribe.AddLogSink(fn: (entry: LogEntry) -> (), options: LogSinkOptions?): () -> ()
2189
+ return Log.AddSink(fn :: any, options)
2190
+ end
2191
+
2192
+ -- Registers plugin actions; returned cleanup removes only this registration.
2193
+ function Scribe.RegisterAddon(name: string, actions: Addons.Actions): () -> ()
2194
+ return Addons.Register(name, actions)
2195
+ end
2196
+
2197
+ -- Returns filtered retained logs, oldest first; Limit keeps the newest entries.
2198
+ function Scribe.GetRecentLogs(filter: Log.LogFilter?): { LogEntry }
2199
+ return Log.GetRecent(filter)
2200
+ end
2201
+
2202
+ -- Returns this context's counters and distribution summaries.
2203
+ function Scribe.GetMetrics(): { [string]: number | { Count: number, Average: number, Max: number } }
2204
+ return Metrics.Get()
2205
+ end
2206
+
2207
+ -- Returns recent distribution percentiles with sample age and window size.
2208
+ function Scribe.GetPercentiles(): { [string]: Metrics.Percentiles }
2209
+ return Metrics.GetPercentiles()
2210
+ end
2211
+
2212
+ -- Reads current DataStore allowances; Available is false if the query fails.
2213
+ function Scribe.GetBudgetSnapshot(): Budget.Snapshot
2214
+ return Budget.Snapshot()
2215
+ end
2216
+
2217
+ -- Builds a Server/Client bundle; calling Scribe(options) uses the same function.
2218
+ Scribe.new = buildBundle
2219
+
2220
+ -- The metatable is attached through a cast so it stays invisible to the type
2221
+ -- system; the callable type is declared explicitly below instead (the new
2222
+ -- solver does not yet instantiate generic __call metamethods).
2223
+ setmetatable(Scribe :: any, {
2224
+ __call = function<T, S>(_self: any, options: ScribeOptions<T, S>): Bundle<T, S>
2225
+ return buildBundle(options)
2226
+ end,
2227
+ })
2228
+
2229
+ export type ScribeModule = typeof(Scribe) & <T, S>(options: ScribeOptions<T, S>) -> Bundle<T, S>
2230
+
2231
+ return (Scribe :: any) :: ScribeModule