@quenty/saveslot 2.7.1 → 2.8.1

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.
@@ -1,18 +1,27 @@
1
1
  --!strict
2
2
  --[=[
3
+ Binds the save slot system to a live [Player].
4
+
5
+ The slot model itself -- the roster, per-slot stores, selection, create/delete/reset,
6
+ export/import, ephemeral slots and playtime -- lives in [HasSaveSlotsDataStore], built here over
7
+ the player's datastore. What stays behind is everything that only means something for a player in
8
+ this server: replicating the slot container under them, the client remotes, teleport data, and
9
+ summary providers (which are handed the [Player]).
10
+
11
+ Every slot method below is a straight delegation. Reach for [HasSaveSlotsDataStore] directly only
12
+ when there is no player to bind -- admin tooling acting on someone who is not in this server.
13
+
3
14
  @class HasSaveSlots
4
15
  ]=]
5
16
 
6
17
  local require = require(script.Parent.loader).load(script)
7
18
 
8
- local HttpService = game:GetService("HttpService")
9
-
10
19
  local Binder = require("Binder")
11
20
  local Brio = require("Brio")
12
21
  local DataStoreStage = require("DataStoreStage")
13
22
  local HasSaveSlotsBase = require("HasSaveSlotsBase")
23
+ local HasSaveSlotsDataStore = require("HasSaveSlotsDataStore")
14
24
  local HasSaveSlotsInterface = require("HasSaveSlotsInterface")
15
- local InMemoryDataStore = require("InMemoryDataStore")
16
25
  local Maid = require("Maid")
17
26
  local Observable = require("Observable")
18
27
  local ObservableMap = require("ObservableMap")
@@ -21,71 +30,70 @@ local PlayerDataStoreService = require("PlayerDataStoreService")
21
30
  local Promise = require("Promise")
22
31
  local Remoting = require("Remoting")
23
32
  local Rx = require("Rx")
24
- local RxBrioUtils = require("RxBrioUtils")
25
33
  local SaveSlotCodeUtils = require("SaveSlotCodeUtils")
26
34
  local SaveSlotConstants = require("SaveSlotConstants")
27
35
  local SaveSlotData = require("SaveSlotData")
28
36
  local SaveSlotExportUtils = require("SaveSlotExportUtils")
29
37
  local SaveSlotSharedDataStoreService = require("SaveSlotSharedDataStoreService")
30
38
  local ServiceBag = require("ServiceBag")
39
+ local Signal = require("Signal")
31
40
  local TeleportDataService = require("TeleportDataService")
41
+ local ValueObject = require("ValueObject")
32
42
 
33
43
  -- A summary provider contributes one named piece of a slot's Summary. It is called with the player and
34
44
  -- the slot's DataStoreStage and returns an Observable of a JSON-serializable value. Providers are
35
45
  -- aggregated into a table keyed by their registered name; see RegisterSummaryProvider and _setupSummary.
36
46
  export type SummaryProvider = (Player, DataStoreStage.DataStoreStage) -> Observable.Observable<any>
37
47
 
48
+ -- Re-exported so consumers keep naming this through HasSaveSlots; see HasSaveSlotsDataStore.
49
+ export type SaveSlotCreateMetadata = HasSaveSlotsDataStore.SaveSlotCreateMetadata
50
+
38
51
  -- A provider that errors (when called, or mid-stream) contributes this sentinel rather than stalling or
39
52
  -- failing the whole aggregate; _setupSummary strips it back out before writing the Summary. Compared by
40
53
  -- identity, so it never collides with a real value (even an empty table) a provider might emit.
41
54
  local NONE = {}
42
55
 
43
- -- The caller-supplied fields for a new slot. SlotId and SlotIndex are assigned by PromiseCreateSlot
44
- -- itself (from a fresh GUID and the slotIndex argument), so they are never taken from here.
45
- -- TimePlayed seeds the new slot's accrued playtime, which is what lets a copy of a slot (duplicate or
46
- -- export/import) carry the playtime that belongs to the progress being copied.
47
- export type SaveSlotCreateMetadata = {
48
- SlotName: string?,
49
- Summary: SaveSlotData.SaveSlotSummary?,
50
- TimePlayed: number?,
51
- }
52
-
53
- local HasSaveSlots = setmetatable({}, HasSaveSlotsBase)
56
+ local HasSaveSlots = {}
54
57
  HasSaveSlots.ClassName = "HasSaveSlots"
55
58
  HasSaveSlots.__index = HasSaveSlots
59
+ -- Runtime inheritance only. Typing the metatable target as `any` keeps the old solver from chasing
60
+ -- the full HasSaveSlotsBase type here, which -- now that this class also names HasSaveSlotsDataStore
61
+ -- across every delegation -- overflows its complexity budget ("Code is too complex"). The inherited
62
+ -- surface is supplied structurally below.
63
+ setmetatable(HasSaveSlots :: any, HasSaveSlotsBase)
64
+
65
+ -- Minimal structural surface inherited from HasSaveSlotsBase, for this class and its consumers. See
66
+ -- the setmetatable note above for why we don't intersect HasSaveSlotsBase.HasSaveSlotsBase.
67
+ type HasSaveSlotsBaseLike = {
68
+ _obj: Player,
69
+ _maid: Maid.Maid,
70
+
71
+ ActiveSlotId: ValueObject.ValueObject<SaveSlotData.SlotId?>,
72
+ LastActiveSlotId: ValueObject.ValueObject<SaveSlotData.SlotId?>,
73
+ ActiveTransferableEphemeralKey: ValueObject.ValueObject<string?>,
74
+ MaxSlotCount: ValueObject.ValueObject<number>,
75
+ SlotChanged: Signal.Signal<SaveSlotData.SlotId>,
76
+
77
+ PromiseHasSaveSlotFromTeleport: (self: any) -> Promise.Promise<boolean>,
78
+ PromiseLoadSaveSlotFromTeleport: (self: any) -> Promise.Promise<SaveSlotData.SlotId?>,
79
+ Destroy: (self: any) -> (),
80
+ }
56
81
 
57
82
  export type HasSaveSlots =
58
83
  typeof(setmetatable(
59
84
  {} :: {
60
- _obj: Player,
61
85
  _serviceBag: ServiceBag.ServiceBag,
62
86
  _playerDataStoreService: any,
63
- _slotContainer: Folder,
64
- _slotMap: { [SaveSlotData.SlotId]: Folder },
65
- -- The in-memory stores backing ephemeral (session-only) slots, keyed by slot id. A slot's
66
- -- IsEphemeral property is the discriminator (see _isEphemeral); this holds the store objects a
67
- -- property can't. See PromiseSelectEphemeralSlot.
68
- _ephemeralStores: { [SaveSlotData.SlotId]: InMemoryDataStore.InMemoryDataStore },
69
- -- The shared-store key each transferable ephemeral slot was loaded from, so a teleport can
70
- -- re-save its live state under that key and carry it forward. See PromiseSelectTransferableEphemeralSlot.
71
- _transferableEphemeralKeys: { [SaveSlotData.SlotId]: string },
72
- _codeGenerator: SaveSlotCodeUtils.CodeGenerator,
73
- _loadPromise: Promise.Promise<{}>,
87
+ -- A HasSaveSlotsDataStore. Untyped for the reason given on GetSlotsDataStore.
88
+ _slotsDataStore: any,
74
89
  _remoting: any,
75
- _dataStore: any,
76
- _systemStore: any,
77
- _metadataStore: any,
78
90
  _summaryProviders: ObservableMap.ObservableMap<string, SummaryProvider>,
79
- _lastActiveSlotId: SaveSlotData.SlotId?,
80
91
  _teleportDataService: any,
81
92
  _sharedSaveSlotDataStoreService: any,
82
- _playSessionSlotId: SaveSlotData.SlotId?,
83
- _playSessionStart: number?,
84
- _playSessionLastFlush: number?,
85
93
  },
86
94
  {} :: typeof({ __index = HasSaveSlots })
87
95
  ))
88
- & HasSaveSlotsBase.HasSaveSlotsBase
96
+ & HasSaveSlotsBaseLike
89
97
 
90
98
  function HasSaveSlots.new(player: Player, serviceBag: ServiceBag.ServiceBag): HasSaveSlots
91
99
  local self: HasSaveSlots = setmetatable(HasSaveSlotsBase.new(player, serviceBag) :: any, HasSaveSlots)
@@ -95,24 +103,39 @@ function HasSaveSlots.new(player: Player, serviceBag: ServiceBag.ServiceBag): Ha
95
103
  self._teleportDataService = self._serviceBag:GetService(TeleportDataService)
96
104
  self._sharedSaveSlotDataStoreService = self._serviceBag:GetService(SaveSlotSharedDataStoreService)
97
105
 
98
- self._slotContainer = self._maid:Add(Instance.new("Folder"))
99
- self._slotContainer.Name = SaveSlotConstants.METADATA_CONTAINER_NAME
100
- self._slotContainer.Archivable = false
101
- self._slotContainer.Parent = self._obj
102
-
103
- self._slotMap = {}
104
- self._ephemeralStores = {}
105
- self._transferableEphemeralKeys = {}
106
- self._codeGenerator = SaveSlotCodeUtils.generateDefaultCode
107
-
108
106
  self._summaryProviders = self._maid:Add(ObservableMap.new())
109
107
 
110
- self._loadPromise = self._maid:GivePromise(self:_promiseLoadSlots())
108
+ -- UserId is read defensively because it is not indexable on every stand-in a binder can be bound to.
109
+ local okUserId, userId = pcall(function()
110
+ return self._obj.UserId
111
+ end)
112
+
113
+ -- Annotated rather than inlined into the call: inferring this table against the class's
114
+ -- intersection type tips luau-lsp into "Code is too complex to typecheck".
115
+ local options: HasSaveSlotsDataStore.HasSaveSlotsDataStoreOptions = {
116
+ ActiveSlotId = self.ActiveSlotId,
117
+ LastActiveSlotId = self.LastActiveSlotId,
118
+ ActiveTransferableEphemeralKey = self.ActiveTransferableEphemeralKey,
119
+ MaxSlotCount = self.MaxSlotCount,
120
+ SharedDataStoreService = self._sharedSaveSlotDataStoreService,
121
+ PromisePreSelect = function(slotId: SaveSlotData.SlotId)
122
+ return self:_promisePreSelectFromSaveSlotService(slotId)
123
+ end,
124
+ UserId = if okUserId and type(userId) == "number" then userId else nil,
125
+ UserName = self._obj.Name,
126
+ TrackPlaytime = true,
127
+ }
128
+
129
+ self._slotsDataStore =
130
+ self._maid:Add(HasSaveSlotsDataStore.new(self._playerDataStoreService:PromiseDataStore(self._obj), options))
131
+
132
+ -- Replicate the slot roster from the player, which is where the client reads it (see
133
+ -- SaveSlotDataService). The slot system itself has no idea a player is involved.
134
+ self._maid:GiveTask(self._slotsDataStore.SlotContainerParent:Mount(self._obj))
111
135
 
112
136
  self._remoting = self._maid:Add(Remoting.Server.new(self._obj, "HasSaveSlots"))
113
137
 
114
138
  self:_setupSummary()
115
- self:_setupPlaytimeTracking()
116
139
  self:_setupRemotes()
117
140
 
118
141
  self._maid:GiveTask(HasSaveSlotsInterface.Server:Implement(self._obj, self))
@@ -120,53 +143,50 @@ function HasSaveSlots.new(player: Player, serviceBag: ServiceBag.ServiceBag): Ha
120
143
  return self
121
144
  end
122
145
 
146
+ --[=[
147
+ Returns the underlying player-independent slot system, a [HasSaveSlotsDataStore]. Prefer the
148
+ delegating methods on this class; this is for code that needs to hand the slot system to something
149
+ that does not know about players.
150
+
151
+ Typed `any` deliberately: naming `HasSaveSlotsDataStore.HasSaveSlotsDataStore` anywhere in this
152
+ file -- even once -- pushes the old solver over its complexity budget ("Code is too complex"). The
153
+ delegating methods below still carry their own precise return types, which is what callers read;
154
+ require the module directly for a typed handle.
155
+
156
+ @return HasSaveSlotsDataStore
157
+ ]=]
158
+ function HasSaveSlots.GetSlotsDataStore(self: HasSaveSlots): any
159
+ return self._slotsDataStore
160
+ end
161
+
123
162
  --[=[
124
163
  Observes the [DataStoreStage] for the active slot as a [Brio]
125
164
  ]=]
126
165
  function HasSaveSlots.ObserveActiveSlotStoreBrio(
127
166
  self: HasSaveSlots
128
167
  ): Observable.Observable<Brio.Brio<DataStoreStage.DataStoreStage>>
129
- return Rx.fromPromise(self._loadPromise):Pipe({
130
- Rx.switchMap(function()
131
- return self.ActiveSlotId
132
- :ObserveBrio(function(slotId: SaveSlotData.SlotId?)
133
- return (slotId ~= nil)
134
- end)
135
- :Pipe({
136
- RxBrioUtils.map(function(slotId: SaveSlotData.SlotId)
137
- return self:_getSlotStore(slotId)
138
- end) :: any,
139
- }) :: any
140
- end) :: any,
141
- }) :: any
168
+ return self._slotsDataStore:ObserveActiveSlotStoreBrio()
142
169
  end
143
170
 
144
171
  --[=[
145
172
  Returns the [DataStoreStage] for the active slot
146
173
  ]=]
147
174
  function HasSaveSlots.PromiseActiveSlotStore(self: HasSaveSlots): Promise.Promise<DataStoreStage.DataStoreStage?>
148
- return (self._loadPromise :: any):Then(function()
149
- if not self.ActiveSlotId.Value then
150
- return (Promise :: any).resolved(nil)
151
- end
152
- return self:_getSlotStore(self.ActiveSlotId.Value)
153
- end)
175
+ return self._slotsDataStore:PromiseActiveSlotStore()
154
176
  end
155
177
 
156
178
  --[=[
157
179
  Promises that all slots have loaded
158
180
  ]=]
159
181
  function HasSaveSlots.PromiseSlotsLoaded(self: HasSaveSlots): Promise.Promise<any>
160
- return self._loadPromise
182
+ return self._slotsDataStore:PromiseSlotsLoaded()
161
183
  end
162
184
 
163
185
  --[=[
164
186
  Returns whether the slot with the given ID exists
165
187
  ]=]
166
188
  function HasSaveSlots.PromiseHasSlot(self: HasSaveSlots, slotId: SaveSlotData.SlotId?): Promise.Promise<boolean>
167
- return (self._loadPromise :: any):Then(function()
168
- return slotId and ((self._slotMap[slotId] :: Folder?) ~= nil)
169
- end)
189
+ return self._slotsDataStore:PromiseHasSlot(slotId)
170
190
  end
171
191
 
172
192
  -- SaveSlotService owns the callbacks and runs them. Reached through the module instance rather than by
@@ -189,72 +209,16 @@ end
189
209
  Selects the slot with the given ID
190
210
  ]=]
191
211
  function HasSaveSlots.PromiseSelectSlot(self: HasSaveSlots, slotId: SaveSlotData.SlotId): Promise.Promise<any>
192
- return (self._loadPromise :: any):Then(function()
193
- if slotId == self.ActiveSlotId.Value then
194
- return -- Already set
195
- end
196
-
197
- local slot = self._slotMap[slotId]
198
- if not slot then
199
- return (Promise :: any).rejected(`Slot \{{slotId}\} not found`)
200
- end
201
-
202
- local function setSlot()
203
- self.ActiveSlotId.Value = slotId
204
- SaveSlotData.LastPlayedTime:Set(slot, os.time())
205
- end
206
-
207
- local function promiseSetSlot()
208
- return self._maid
209
- :GivePromise(self:_promisePreSelectFromSaveSlotService(slotId))
210
- :Then(function(allowed: boolean)
211
- if not allowed then
212
- return (Promise :: any).rejected(`Slot \{{slotId}\} refused by a pre-select callback`)
213
- end
214
-
215
- return setSlot()
216
- end)
217
- end
218
-
219
- -- Initialize or save and switch
220
- if self.ActiveSlotId.Value == nil then
221
- return promiseSetSlot()
222
- end
223
-
224
- -- Leaving an ephemeral slot has nothing to persist, so switch without a datastore flush (the flush
225
- -- exists to save the outgoing slot's progress, and an ephemeral slot has none).
226
- if self:_isEphemeral(self.ActiveSlotId.Value) then
227
- return promiseSetSlot()
228
- end
229
-
230
- return self._maid:GivePromise(self._dataStore:Save()):Then(promiseSetSlot)
231
- end)
212
+ return self._slotsDataStore:PromiseSelectSlot(slotId)
232
213
  end
233
214
 
234
215
  --[=[
235
216
  Clears the active slot selection, returning the player to a no-slot state --
236
217
  the counterpart to [HasSaveSlots.PromiseSelectSlot], backing a "back to menu"
237
- affordance. The active slot's progress is flushed first (mirroring the save
238
- PromiseSelectSlot runs when switching away), and the last-active slot is
239
- remembered, so [HasSaveSlots.PromiseSelectLastSaveSlot] can resume it later.
240
- A no-op when no slot is active.
218
+ affordance. See [HasSaveSlotsDataStore.PromiseDeselectSlot].
241
219
  ]=]
242
220
  function HasSaveSlots.PromiseDeselectSlot(self: HasSaveSlots): Promise.Promise<()>
243
- return (self._loadPromise :: any):Then(function()
244
- if self.ActiveSlotId.Value == nil then
245
- return -- Already deselected
246
- end
247
-
248
- -- An ephemeral slot has nothing to flush, so clear it without a datastore save.
249
- if self:_isEphemeral(self.ActiveSlotId.Value) then
250
- self.ActiveSlotId.Value = nil
251
- return
252
- end
253
-
254
- return self._dataStore:Save():Then(function()
255
- self.ActiveSlotId.Value = nil
256
- end)
257
- end)
221
+ return self._slotsDataStore:PromiseDeselectSlot()
258
222
  end
259
223
 
260
224
  --[=[
@@ -265,46 +229,12 @@ function HasSaveSlots.PromiseCreateSlot(
265
229
  slotIndex: number,
266
230
  metadata: SaveSlotCreateMetadata?
267
231
  ): Promise.Promise<SaveSlotData.SlotId>
268
- return (self._loadPromise :: any):Then(function()
269
- if (slotIndex < 1) or (slotIndex > self.MaxSlotCount.Value) then
270
- return (Promise :: any).rejected(`Index must be in range [1, {self.MaxSlotCount.Value}]`)
271
- end
272
-
273
- for existingSlotId, slot in self._slotMap do
274
- if self:_isEphemeral(existingSlotId) then
275
- continue -- ephemeral slots carry no meaningful index; never let one block a real index
276
- end
277
- if slotIndex == SaveSlotData.SlotIndex:Get(slot) then
278
- return (Promise :: any).rejected(`Slot {slotIndex} already exists`)
279
- end
280
- end
281
-
282
- local slotId = HttpService:GenerateGUID(false)
283
- local data = {
284
- SlotId = slotId,
285
- SlotIndex = slotIndex,
286
- SlotName = (metadata and metadata.SlotName) or `Slot {slotIndex}`,
287
- CreatedTime = os.time(),
288
- Summary = metadata and metadata.Summary,
289
- TimePlayed = metadata and metadata.TimePlayed,
290
- }
291
-
292
- self:_buildSlot(slotId, data, true)
293
- return slotId
294
- end)
232
+ return self._slotsDataStore:PromiseCreateSlot(slotIndex, metadata)
295
233
  end
296
234
 
297
235
  --[=[
298
- Exports a slot's saved data into a plain, serializable [SaveSlotExportUtils.SaveSlotExport].
299
- Rejects the main/default slot by default: its store is the player's shared root datastore, so
300
- exporting it would leak the SaveSlots system data and universe-scoped global data living
301
- alongside it. Only isolated non-main slot substores are exportable.
302
-
303
- `allowMainSlot` opts out of that refusal for trusted admin tooling (see [SaveSlotCmdrService]).
304
- The SaveSlots system data is always stripped from the result, so the export never carries the
305
- slot roster or the other slots' saved data. Universe-scoped global data sharing the root store
306
- is indistinguishable from the main slot's own data and is still carried, which is why this is
307
- not exposed through [SaveSlotService].
236
+ Exports a slot's saved data into a plain, serializable [SaveSlotExportUtils.SaveSlotExport]. Refuses
237
+ the main slot unless `allowMainSlot` is set -- see [HasSaveSlotsDataStore.PromiseExportSlot].
308
238
 
309
239
  @param slotId SlotId
310
240
  @param allowMainSlot boolean? -- defaults to false
@@ -315,97 +245,32 @@ function HasSaveSlots.PromiseExportSlot(
315
245
  slotId: SaveSlotData.SlotId,
316
246
  allowMainSlot: boolean?
317
247
  ): Promise.Promise<SaveSlotExportUtils.SaveSlotExport>
318
- return (self._loadPromise :: any):Then(function()
319
- local slot = self._slotMap[slotId]
320
- if not slot then
321
- return (Promise :: any).rejected(`Slot \{{slotId}\} not found`)
322
- end
323
-
324
- local isMainSlot = SaveSlotExportUtils.isMainSlotIndex(SaveSlotData.SlotIndex:Get(slot))
325
- if isMainSlot and not allowMainSlot then
326
- return (Promise :: any).rejected("Cannot export the main slot")
327
- end
328
-
329
- -- As in PromiseDuplicateSlot: bring the live session's accrued time into TimePlayed before it is
330
- -- read, so an export of the active slot carries its playtime up to this moment.
331
- self:_flushPlaytime()
332
-
333
- local metadata = SaveSlotData:Get(slot)
334
- return self:_getSlotStore(slotId):LoadAll({}):Then(function(sourceData)
335
- local data = if type(sourceData) == "table" then table.clone(sourceData) else {}
336
-
337
- if isMainSlot then
338
- -- The main slot's store is the player's shared root, so LoadAll pulls the SaveSlots system
339
- -- data with it -- the slot roster and every non-main slot's saved data. Drop it so the
340
- -- export is only this slot, and so importing it can't nest a whole roster inside a slot
341
- -- (mirrors PromiseDuplicateSlot, which strips the same key for the same reason).
342
- data[SaveSlotConstants.SYSTEM_STORE_KEY] = nil
343
- end
344
-
345
- return SaveSlotExportUtils.create(data, metadata.SlotName, metadata.Summary, metadata.TimePlayed)
346
- end)
347
- end)
248
+ return self._slotsDataStore:PromiseExportSlot(slotId, allowMainSlot)
348
249
  end
349
250
 
350
251
  --[=[
351
- Imports an exported slot into a fresh slot at the lowest free non-main index, seeding the new
352
- slot's store with the exported data. Never uses the main/default index -- importing onto the
353
- shared root store would wipe the player's global data. Resolves to the new slot's id. Rejects a
354
- malformed export, or when no non-main index is free.
252
+ Imports an exported slot into a fresh slot, at the lowest free non-main index by default. See
253
+ [HasSaveSlotsDataStore.PromiseImportSlot].
355
254
 
356
255
  @param export SaveSlotExportUtils.SaveSlotExport
256
+ @param targetSlotIndex number? -- defaults to the lowest free non-main index
357
257
  @return Promise<SlotId>
358
258
  ]=]
359
259
  function HasSaveSlots.PromiseImportSlot(
360
260
  self: HasSaveSlots,
361
- export: SaveSlotExportUtils.SaveSlotExport
261
+ export: SaveSlotExportUtils.SaveSlotExport,
262
+ targetSlotIndex: number?
362
263
  ): Promise.Promise<SaveSlotData.SlotId>
363
- return (self._loadPromise :: any):Then(function()
364
- if not SaveSlotExportUtils.isSaveSlotExport(export) then
365
- return (Promise :: any).rejected("Bad save slot export")
366
- end
367
-
368
- -- Lowest free index strictly above the main slot: an imported slot must never occupy the
369
- -- default index, whose store is the shared root datastore.
370
- local usedIndices = {}
371
- for existingSlotId, slot in self._slotMap do
372
- if not self:_isEphemeral(existingSlotId) then
373
- usedIndices[SaveSlotData.SlotIndex:Get(slot)] = true
374
- end
375
- end
376
- local freeIndex = SaveSlotConstants.DEFAULT_SLOT_INDEX + 1
377
- while usedIndices[freeIndex] do
378
- freeIndex += 1
379
- end
380
- if freeIndex > self.MaxSlotCount.Value then
381
- return (Promise :: any).rejected("No free non-main slot index available")
382
- end
383
-
384
- return self:PromiseCreateSlot(freeIndex, {
385
- SlotName = export.slotName,
386
- Summary = export.summary,
387
- -- Absent on exports taken before playtime was carried; those import as before, with no playtime.
388
- TimePlayed = export.timePlayed,
389
- }):Then(function(newSlotId: SaveSlotData.SlotId)
390
- -- freeIndex is always > DEFAULT_SLOT_INDEX, so this store is an isolated substore
391
- -- (never the shared root); a plain Overwrite cannot touch system or global data.
392
- self:_getSlotStore(newSlotId):Overwrite(export.data)
393
-
394
- -- Flush so the imported slot survives a crash before the next autosave.
395
- return self._dataStore:Save():Then(function()
396
- return newSlotId
397
- end)
398
- end)
399
- end)
264
+ return self._slotsDataStore:PromiseImportSlot(export, targetSlotIndex)
400
265
  end
401
266
 
402
267
  --[=[
403
- Exports a non-main slot (see [HasSaveSlots.PromiseExportSlot]) and writes it to the shared save
404
- slot store under the given key.
268
+ Exports a non-main slot and writes it to the shared save slot store under the given key. See
269
+ [HasSaveSlotsDataStore.PromiseSaveSlotToSharedDataStore].
405
270
 
406
271
  @param slotId SlotId
407
272
  @param key string
408
- @param allowMainSlot boolean? -- defaults to false, see [HasSaveSlots.PromiseExportSlot]
273
+ @param allowMainSlot boolean? -- defaults to false
409
274
  @return Promise<boolean>
410
275
  ]=]
411
276
  function HasSaveSlots.PromiseSaveSlotToSharedDataStore(
@@ -414,14 +279,12 @@ function HasSaveSlots.PromiseSaveSlotToSharedDataStore(
414
279
  key: string,
415
280
  allowMainSlot: boolean?
416
281
  ): Promise.Promise<boolean>
417
- return self:PromiseExportSlot(slotId, allowMainSlot):Then(function(export)
418
- return self._sharedSaveSlotDataStoreService:PromiseWrite(key, export)
419
- end)
282
+ return self._slotsDataStore:PromiseSaveSlotToSharedDataStore(slotId, key, allowMainSlot)
420
283
  end
421
284
 
422
285
  --[=[
423
- Reads an export from the shared save slot store and imports it into a fresh non-main slot (see
424
- [HasSaveSlots.PromiseImportSlot]). Rejects when no export is stored under the key.
286
+ Reads an export from the shared save slot store and imports it into a fresh non-main slot. See
287
+ [HasSaveSlotsDataStore.PromiseImportSlotFromSharedDataStore].
425
288
 
426
289
  @param key string
427
290
  @return Promise<SlotId>
@@ -430,25 +293,14 @@ function HasSaveSlots.PromiseImportSlotFromSharedDataStore(
430
293
  self: HasSaveSlots,
431
294
  key: string
432
295
  ): Promise.Promise<SaveSlotData.SlotId>
433
- -- Maid-owned like the other shared-store reads: this one is not even gated behind _loadPromise, so
434
- -- nothing upstream rejects it when the player leaves mid-read.
435
- return self._maid:GivePromise(self._sharedSaveSlotDataStoreService:PromiseRead(key)):Then(function(export)
436
- if not self.Destroy then
437
- return (Promise :: any).rejected() -- Destroyed. Empty, so it stays out of the logs
438
- end
439
-
440
- if export == nil then
441
- return (Promise :: any).rejected(`No save slot stored under \{{key}\}`)
442
- end
443
- return self:PromiseImportSlot(export)
444
- end)
296
+ return self._slotsDataStore:PromiseImportSlotFromSharedDataStore(key)
445
297
  end
446
298
 
447
299
  --[=[
448
- Loads the export stored under the given shared-store key into a fresh ephemeral slot and selects it,
449
- remembering the key so a teleport can carry the slot forward (see the transferable-ephemeral teleport
450
- provider in [SaveSlotService]). Like every ephemeral slot it is never persisted, stays out of the slot
451
- list, and is torn down on deselect. Rejects when no valid export is stored under the key.
300
+ Resumes a transfer from the given shared-store key into a fresh ephemeral slot and selects it. Only
301
+ entries written as transfers are accepted; a share code is redeemed through
302
+ [HasSaveSlots.PromiseImportEphemeralSaveSlotFromCode]. See
303
+ [HasSaveSlotsDataStore.PromiseSelectTransferableEphemeralSlot].
452
304
 
453
305
  @param key string
454
306
  @return Promise<SlotId>
@@ -457,75 +309,17 @@ function HasSaveSlots.PromiseSelectTransferableEphemeralSlot(
457
309
  self: HasSaveSlots,
458
310
  key: string
459
311
  ): Promise.Promise<SaveSlotData.SlotId>
460
- return (self._loadPromise :: any):Then(function()
461
- -- Maid-owned for the same reason as _promiseLoadSlots: this read runs on the join path (a teleport
462
- -- arriving with an ephemeral key) and outlives a leave, and its continuation builds a slot.
463
- return self._maid:GivePromise(self._sharedSaveSlotDataStoreService:PromiseRead(key)):Then(function(export)
464
- if not self.Destroy then
465
- -- Destroyed. Rejecting keeps the Promise<SlotId> contract honest -- a nil fulfilment reads as
466
- -- "imported, no slot" to a caller like SaveSlotCmdrService. Empty, so it stays out of the logs.
467
- return (Promise :: any).rejected()
468
- end
469
-
470
- if export == nil then
471
- return (Promise :: any).rejected(`No save slot stored under \{{key}\}`)
472
- end
473
- if not SaveSlotExportUtils.isSaveSlotExport(export) then
474
- return (Promise :: any).rejected("Bad save slot export in shared store")
475
- end
476
-
477
- local slotId = HttpService:GenerateGUID(false)
478
- self:_buildSlot(slotId, {
479
- SlotId = slotId,
480
- SlotIndex = SaveSlotConstants.EPHEMERAL_SLOT_INDEX,
481
- SlotName = export.slotName or "Transfer",
482
- CreatedTime = os.time(),
483
- Summary = export.summary,
484
- }, true, true)
485
-
486
- -- Seed the in-memory store before selecting so a consumer of ObserveActiveSlotStoreBrio never
487
- -- observes an empty active slot; then remember the key this slot transfers under.
488
- self:_getSlotStore(slotId):Overwrite(export.data)
489
- self._transferableEphemeralKeys[slotId] = key
490
-
491
- return self:PromiseSelectSlot(slotId):Then(function()
492
- return slotId
493
- end)
494
- end)
495
- end)
312
+ return self._slotsDataStore:PromiseSelectTransferableEphemeralSlot(key)
496
313
  end
497
314
 
498
315
  --[=[
499
- Builds this player's teleport slice for a transferable ephemeral slot: re-saves the active slot's
500
- *current live* data to the shared store under its key and returns a slice carrying that key. Resolves
501
- nil when the active slot is not a transferable ephemeral slot. A failed re-save degrades to nil so a
502
- teleport is never blocked (the destination then re-loads the last saved state). Asynchronous -- it is
503
- consumed through [TeleportDataService.PromiseBuildTeleportData].
316
+ Builds this player's teleport slice for a transferable ephemeral slot. See
317
+ [HasSaveSlotsDataStore.PromiseBuildEphemeralTransferSlice].
504
318
 
505
319
  @return Promise<{ [string]: any }?>
506
320
  ]=]
507
321
  function HasSaveSlots.PromiseBuildEphemeralTransferSlice(self: HasSaveSlots): Promise.Promise<{ [string]: any }?>
508
- return (self._loadPromise :: any):Then(function(): any
509
- local slotId = self.ActiveSlotId.Value
510
- if not slotId then
511
- return nil
512
- end
513
- local storeKey = self._transferableEphemeralKeys[slotId]
514
- if not storeKey then
515
- return nil
516
- end
517
-
518
- return self:PromiseExportSlot(slotId)
519
- :Then(function(export)
520
- return self._sharedSaveSlotDataStoreService:PromiseWrite(storeKey, export)
521
- end)
522
- :Then(function()
523
- return { [SaveSlotConstants.TELEPORT_DATA_EPHEMERAL_KEY] = storeKey }
524
- end)
525
- :Catch(function()
526
- return nil
527
- end)
528
- end)
322
+ return self._slotsDataStore:PromiseBuildEphemeralTransferSlice()
529
323
  end
530
324
 
531
325
  --[=[
@@ -534,10 +328,12 @@ end
534
328
  the common case, e.g. a menu resume hop -- carries it too; a server-initiated teleport still works via
535
329
  the trusted band. Resolves to the slot id, or nil when none arrived.
536
330
 
537
- Because the client band is honored, a client can present any key it knows. The key resolves to a
538
- server-side shared-store entry and only ever seeds a throwaway (never-persisted) slot, so the exposure
539
- is read-only visibility of a snapshot whose code you already have -- acceptable for the dev/Cmdr tooling
540
- this backs. Harden (longer code entropy / ownership) before exposing it to a player-facing surface.
331
+ Because the client band is honored, a client can present any key it knows -- which is why the entry
332
+ behind it must have been written as a transfer (see [SaveSlotExportUtils.Kind]). A share code, the one
333
+ key players deliberately pass around, is refused here, so redeeming one stays a decision the server
334
+ makes in [HasSaveSlots.PromiseImportEphemeralSaveSlotFromCode] rather than something a teleport can do.
335
+ A transfer key is itself replicated (see `ActiveTransferableEphemeralKey`) and only ever seeds a
336
+ throwaway, never-persisted slot, so what it exposes is read-only visibility of that snapshot.
541
337
 
542
338
  @return Promise<SlotId?>
543
339
  ]=]
@@ -562,36 +358,15 @@ end
562
358
  @param generator CodeGenerator
563
359
  ]=]
564
360
  function HasSaveSlots.SetCodeGenerator(self: HasSaveSlots, generator: SaveSlotCodeUtils.CodeGenerator): ()
565
- assert(type(generator) == "function", "Bad generator")
566
- self._codeGenerator = generator
567
- end
568
-
569
- -- Builds a code for a slot from the configured generator, resolving the owner's identity defensively
570
- -- (player.UserId is not indexable on every stand-in) and the slot's name/index from its metadata.
571
- function HasSaveSlots._generateCode(self: HasSaveSlots, slotId: SaveSlotData.SlotId): string
572
- local slot = self._slotMap[slotId]
573
- local metadata = if slot then SaveSlotData:Get(slot) else nil
574
- local okUserId, userId = pcall(function()
575
- return self._obj.UserId
576
- end)
577
-
578
- return self._codeGenerator({
579
- userId = if okUserId and type(userId) == "number" then userId else nil,
580
- userName = self._obj.Name,
581
- slotName = metadata and metadata.SlotName,
582
- slotIndex = metadata and metadata.SlotIndex,
583
- })
361
+ self._slotsDataStore:SetCodeGenerator(generator)
584
362
  end
585
363
 
586
364
  --[=[
587
- Exports a slot to the shared store under a fresh generated code and resolves to that code. The code
588
- is a shareable handle other sessions load with [HasSaveSlots.PromiseImportEphemeralSaveSlotFromCode].
589
- Defaults to the active slot. Refuses the main slot unless `allowMainSlot` is set (see
590
- [HasSaveSlots.PromiseExportSlot]). The code format comes from the configured generator (see
591
- [HasSaveSlots.SetCodeGenerator]).
365
+ Exports a slot to the shared store under a fresh generated code and resolves to that code. See
366
+ [HasSaveSlotsDataStore.PromiseExportSaveSlotToCode].
592
367
 
593
368
  @param slotId SlotId? -- defaults to the active slot
594
- @param allowMainSlot boolean? -- defaults to false, see [HasSaveSlots.PromiseExportSlot]
369
+ @param allowMainSlot boolean? -- defaults to false
595
370
  @return Promise<string>
596
371
  ]=]
597
372
  function HasSaveSlots.PromiseExportSaveSlotToCode(
@@ -599,22 +374,13 @@ function HasSaveSlots.PromiseExportSaveSlotToCode(
599
374
  slotId: SaveSlotData.SlotId?,
600
375
  allowMainSlot: boolean?
601
376
  ): Promise.Promise<string>
602
- return (self._loadPromise :: any):Then(function()
603
- local targetSlotId = slotId or self.ActiveSlotId.Value
604
- if not targetSlotId then
605
- return (Promise :: any).rejected("No slot to export")
606
- end
607
-
608
- local code = self:_generateCode(targetSlotId)
609
- return self:PromiseSaveSlotToSharedDataStore(targetSlotId, code, allowMainSlot):Then(function()
610
- return code
611
- end)
612
- end)
377
+ return self._slotsDataStore:PromiseExportSaveSlotToCode(slotId, allowMainSlot)
613
378
  end
614
379
 
615
380
  --[=[
616
- Loads the slot stored under the given code into a fresh transferable ephemeral slot and selects it
617
- (see [HasSaveSlots.PromiseSelectTransferableEphemeralSlot]). Resolves to the new slot id.
381
+ Redeems a share code into a fresh transferable ephemeral slot and selects it. The slot transfers
382
+ onward under a freshly minted key, never the code itself. See
383
+ [HasSaveSlotsDataStore.PromiseImportEphemeralSaveSlotFromCode].
618
384
 
619
385
  @param code string
620
386
  @return Promise<SlotId>
@@ -623,16 +389,15 @@ function HasSaveSlots.PromiseImportEphemeralSaveSlotFromCode(
623
389
  self: HasSaveSlots,
624
390
  code: string
625
391
  ): Promise.Promise<SaveSlotData.SlotId>
626
- return self:PromiseSelectTransferableEphemeralSlot(code)
392
+ return self._slotsDataStore:PromiseImportEphemeralSaveSlotFromCode(code)
627
393
  end
628
394
 
629
395
  --[=[
630
- Exports a slot as a raw JSON string (no shared store), for direct inspection or attaching to a bug
631
- report. Defaults to the active slot. Refuses the main slot unless `allowMainSlot` is set (see
632
- [HasSaveSlots.PromiseExportSlot]).
396
+ Exports a slot as a raw JSON string (no shared store). See
397
+ [HasSaveSlotsDataStore.PromiseExportSaveSlotToJson].
633
398
 
634
399
  @param slotId SlotId? -- defaults to the active slot
635
- @param allowMainSlot boolean? -- defaults to false, see [HasSaveSlots.PromiseExportSlot]
400
+ @param allowMainSlot boolean? -- defaults to false
636
401
  @return Promise<string>
637
402
  ]=]
638
403
  function HasSaveSlots.PromiseExportSaveSlotToJson(
@@ -640,110 +405,23 @@ function HasSaveSlots.PromiseExportSaveSlotToJson(
640
405
  slotId: SaveSlotData.SlotId?,
641
406
  allowMainSlot: boolean?
642
407
  ): Promise.Promise<string>
643
- return (self._loadPromise :: any):Then(function()
644
- local targetSlotId = slotId or self.ActiveSlotId.Value
645
- if not targetSlotId then
646
- return (Promise :: any).rejected("No slot to export")
647
- end
648
-
649
- return self:PromiseExportSlot(targetSlotId, allowMainSlot):Then(function(export)
650
- return HttpService:JSONEncode(export)
651
- end)
652
- end)
408
+ return self._slotsDataStore:PromiseExportSaveSlotToJson(slotId, allowMainSlot)
653
409
  end
654
410
 
655
411
  --[=[
656
- Duplicates the slot with the given ID into a new slot at the lowest free index,
657
- copying its saved data and accrued playtime. Resolves to the new slot's id. The copy is not
658
- selected, its timestamps and session counters start fresh, and its name is suffixed with
659
- " (Copy)". Rejects when the source slot is missing or every index is in use.
660
-
661
- An ephemeral slot may be duplicated: the copy is a real, persisted slot seeded with the ephemeral
662
- slot's live in-memory data, which is how a throwaway session is turned into a save. It keeps the
663
- source's name unsuffixed (the copy is the first real slot for that session, not a second copy of an
664
- existing save) and, like any duplicate, is not selected -- see
665
- [HasSaveSlots.PromisePersistEphemeralSlot] for the version that continues play on the new slot.
412
+ Duplicates the slot with the given ID into a new slot at the lowest free index, copying its saved
413
+ data and accrued playtime. See [HasSaveSlotsDataStore.PromiseDuplicateSlot].
666
414
  ]=]
667
415
  function HasSaveSlots.PromiseDuplicateSlot(
668
416
  self: HasSaveSlots,
669
417
  slotId: SaveSlotData.SlotId
670
418
  ): Promise.Promise<SaveSlotData.SlotId>
671
- return (self._loadPromise :: any):Then(function()
672
- local sourceSlot = self._slotMap[slotId]
673
- if not sourceSlot then
674
- return (Promise :: any).rejected(`Slot \{{slotId}\} not found`)
675
- end
676
-
677
- local sourceIsEphemeral = self:_isEphemeral(slotId)
678
-
679
- -- The source is usually the live active slot, whose current session has not landed in TimePlayed
680
- -- yet; fold it in first so the copy carries the playtime the player is actually looking at.
681
- self:_flushPlaytime()
682
-
683
- -- Lowest free positive index, filling gaps left by deletions (mirrors PromiseSelectNewSaveSlot).
684
- local usedIndices = {}
685
- for existingSlotId, slot in self._slotMap do
686
- if not self:_isEphemeral(existingSlotId) then
687
- usedIndices[SaveSlotData.SlotIndex:Get(slot)] = true
688
- end
689
- end
690
- local freeIndex = 1
691
- while usedIndices[freeIndex] do
692
- freeIndex += 1
693
- end
694
- if freeIndex > self.MaxSlotCount.Value then
695
- return (Promise :: any).rejected("All slots are already in use")
696
- end
697
-
698
- local sourceMetadata = SaveSlotData:Get(sourceSlot)
699
-
700
- -- Read the source's saved data before creating the copy so a read failure leaves no orphan slot.
701
- return self:_getSlotStore(slotId):LoadAll({}):Then(function(sourceData)
702
- -- The default slot shares the player's root store with the SaveSlots system data. Never carry
703
- -- that system key across into the copy's saved data.
704
- local slotData = if type(sourceData) == "table" then table.clone(sourceData) else {}
705
- slotData[SaveSlotConstants.SYSTEM_STORE_KEY] = nil
706
-
707
- return self
708
- :PromiseCreateSlot(freeIndex, {
709
- SlotName = if sourceIsEphemeral
710
- then sourceMetadata.SlotName
711
- else `{sourceMetadata.SlotName} (Copy)`,
712
- Summary = sourceMetadata.Summary,
713
- -- Playtime describes the progress being copied, not the slot it happens to live in, so
714
- -- it travels with that progress rather than resetting the copy to a never-played slot.
715
- TimePlayed = sourceMetadata.TimePlayed,
716
- })
717
- :Then(function(newSlotId: SaveSlotData.SlotId)
718
- local destStore = self:_getSlotStore(newSlotId)
719
-
720
- if destStore == self._dataStore then
721
- -- The copy is the default slot, whose store is the shared root. Merge so the SaveSlots
722
- -- system store living alongside it survives (a plain Overwrite would wipe it).
723
- destStore:OverwriteMerge(slotData)
724
- else
725
- destStore:Overwrite(slotData)
726
- end
727
-
728
- -- Flush so the duplicated data survives a crash before the next autosave.
729
- return self._dataStore:Save():Then(function()
730
- return newSlotId
731
- end)
732
- end)
733
- end)
734
- end)
419
+ return self._slotsDataStore:PromiseDuplicateSlot(slotId)
735
420
  end
736
421
 
737
422
  --[=[
738
- Turns an ephemeral slot into a real save: duplicates it into a fresh persisted slot at the lowest free
739
- index (see [HasSaveSlots.PromiseDuplicateSlot]) and selects that slot, so play continues on data that
740
- is now being written. Defaults to the active slot, which in practice is the only ephemeral slot there
741
- is -- one stops existing the moment it stops being active. Resolves to the new slot's id.
742
-
743
- The copy is taken from the ephemeral slot's live in-memory data at the moment this runs, and selecting
744
- the new slot retires the ephemeral one, so anything written to the old store between the copy and the
745
- selection is dropped. Rejects when no slot is active, the slot is missing, the slot is not ephemeral,
746
- or every index is in use.
423
+ Turns an ephemeral slot into a real save and selects it. See
424
+ [HasSaveSlotsDataStore.PromisePersistEphemeralSlot].
747
425
 
748
426
  @param slotId SlotId? -- defaults to the active slot
749
427
  @return Promise<SlotId>
@@ -752,88 +430,14 @@ function HasSaveSlots.PromisePersistEphemeralSlot(
752
430
  self: HasSaveSlots,
753
431
  slotId: SaveSlotData.SlotId?
754
432
  ): Promise.Promise<SaveSlotData.SlotId>
755
- return (self._loadPromise :: any):Then(function()
756
- local targetSlotId = slotId or self.ActiveSlotId.Value
757
- if not targetSlotId then
758
- return (Promise :: any).rejected("No slot to persist")
759
- end
760
-
761
- if not self._slotMap[targetSlotId] then
762
- return (Promise :: any).rejected(`Slot \{{targetSlotId}\} not found`)
763
- end
764
-
765
- if not self:_isEphemeral(targetSlotId) then
766
- return (Promise :: any).rejected(`Slot \{{targetSlotId}\} is already persisted`)
767
- end
768
-
769
- return self:PromiseDuplicateSlot(targetSlotId):Then(function(newSlotId: SaveSlotData.SlotId)
770
- return self:PromiseSelectSlot(newSlotId):Then(function()
771
- return newSlotId
772
- end)
773
- end)
774
- end)
433
+ return self._slotsDataStore:PromisePersistEphemeralSlot(slotId)
775
434
  end
776
435
 
777
436
  --[=[
778
- Deletes the slot with the given ID. Deleting an ephemeral slot ends that session -- it is deselected
779
- and retired along with its in-memory store -- rather than being refused for being the active slot.
437
+ Deletes the slot with the given ID. See [HasSaveSlotsDataStore.PromiseDeleteSlot].
780
438
  ]=]
781
439
  function HasSaveSlots.PromiseDeleteSlot(self: HasSaveSlots, slotId: SaveSlotData.SlotId): Promise.Promise<any>
782
- return (self._loadPromise :: any):Then(function()
783
- -- An ephemeral slot only exists while it is active, so deleting one is retiring it. Nothing was
784
- -- ever persisted, so there is no stored data to wipe afterwards -- hence the early return.
785
- if self:_isEphemeral(slotId) then
786
- if slotId == self.ActiveSlotId.Value then
787
- return self:PromiseDeselectSlot()
788
- end
789
- self:_destroyEphemeralSlot(slotId)
790
- return (Promise :: any).resolved()
791
- end
792
-
793
- if slotId == self.ActiveSlotId.Value then
794
- return (Promise :: any).rejected("Cannot delete active slot")
795
- end
796
-
797
- local slot = self._slotMap[slotId]
798
- if not slot then
799
- return (Promise :: any).rejected(`Slot \{{slotId}\} not found`)
800
- end
801
-
802
- self._maid[slotId] = nil
803
-
804
- -- The continue pointer must not outlive its slot. When the deleted slot is the one the player
805
- -- would resume on (e.g. the just-deselected active slot, or a never-reselected last-active),
806
- -- clear the last-active memory so "Continue" stops offering a slot that no longer exists.
807
- if slotId == self._lastActiveSlotId then
808
- self._lastActiveSlotId = nil
809
- self.LastActiveSlotId.Value = nil
810
- end
811
-
812
- -- Wipe default slot
813
- local slotIndex = SaveSlotData.SlotIndex:Get(slot)
814
- local deletePromise = nil
815
-
816
- if slotIndex == SaveSlotConstants.DEFAULT_SLOT_INDEX then
817
- deletePromise = self._dataStore:PromiseKeyList():Then(function(keys)
818
- for _, key in keys do
819
- if key ~= SaveSlotConstants.SYSTEM_STORE_KEY then
820
- self._dataStore:Delete(key)
821
- end
822
- end
823
- self._metadataStore:Delete(slotId)
824
- end)
825
- else
826
- -- Or delete slot from substore
827
- self._systemStore:GetSubStore(SaveSlotConstants.SLOT_STORE_KEY):Delete(slotId)
828
- self._metadataStore:Delete(slotId)
829
- deletePromise = (Promise :: any).resolved()
830
- end
831
-
832
- -- Flush the deletion to prevent stale reads
833
- return deletePromise:Then(function()
834
- return self._dataStore:Save()
835
- end)
836
- end)
440
+ return self._slotsDataStore:PromiseDeleteSlot(slotId)
837
441
  end
838
442
 
839
443
  --[=[
@@ -842,104 +446,25 @@ end
842
446
  are gone.
843
447
  ]=]
844
448
  function HasSaveSlots.PromiseDeleteAllSlots(self: HasSaveSlots): Promise.Promise<any>
845
- return (self._loadPromise :: any):Then(function()
846
- -- Clear the selection first so the previously active slot is deletable
847
- self.ActiveSlotId.Value = nil
848
- self._lastActiveSlotId = nil
849
- self.LastActiveSlotId.Value = nil
850
-
851
- local slotIds = {}
852
- for slotId in self._slotMap do
853
- table.insert(slotIds, slotId)
854
- end
855
-
856
- -- Delete sequentially to avoid concurrent datastore saves
857
- local promise = (Promise :: any).resolved()
858
- for _, slotId in slotIds do
859
- promise = promise:Then(function()
860
- return self:PromiseDeleteSlot(slotId)
861
- end)
862
- end
863
- return promise
864
- end)
449
+ return self._slotsDataStore:PromiseDeleteAllSlots()
865
450
  end
866
451
 
867
452
  --[=[
868
- Resets the slot with the given id to a fresh empty one -- equivalent to deleting the slot
869
- and creating a new one at the same index. The slot keeps its index and name; its saved data
870
- and metadata (timestamps) start fresh. Resolves to the new slot id.
871
-
872
- When the reset slot is the active slot, the selection clears and then reselects the fresh
873
- slot: everything bound to [HasSaveSlots.ObserveActiveSlotStoreBrio] tears down as the
874
- selection clears and rebuilds against the empty store on reselect, so consumers reset
875
- reactively without wiping their own state. A non-active slot is left unselected, and its
876
- "Continue" pointer (when it was the last-active slot) is carried across to the fresh id so
877
- the reset slot stays resumable. Rejects when the slot is missing.
453
+ Resets the slot with the given id to a fresh empty one. See [HasSaveSlotsDataStore.PromiseResetSlot].
878
454
  ]=]
879
455
  function HasSaveSlots.PromiseResetSlot(
880
456
  self: HasSaveSlots,
881
457
  slotId: SaveSlotData.SlotId
882
458
  ): Promise.Promise<SaveSlotData.SlotId>
883
- return (self._loadPromise :: any):Then(function(): any
884
- local slot = self._slotMap[slotId]
885
- if not slot then
886
- return (Promise :: any).rejected(`Slot \{{slotId}\} not found`)
887
- end
888
-
889
- if self:_isEphemeral(slotId) then
890
- return (Promise :: any).rejected("Cannot reset an ephemeral slot")
891
- end
892
-
893
- local metadata = SaveSlotData:Get(slot)
894
- local wasActive = (slotId == self.ActiveSlotId.Value)
895
- -- PromiseDeleteSlot clears the continue pointer when it targets the last-active slot; capture it
896
- -- now so the non-active path can move it onto the fresh slot id below.
897
- local wasLastActive = (slotId == self._lastActiveSlotId)
898
-
899
- if wasActive then
900
- -- Clear the selection so the slot is deletable, skipping the deselect flush that would
901
- -- persist progress we are about to delete.
902
- self.ActiveSlotId.Value = nil
903
- end
904
-
905
- return self:PromiseDeleteSlot(slotId)
906
- :Then(function()
907
- return self:PromiseCreateSlot(metadata.SlotIndex, { SlotName = metadata.SlotName })
908
- end)
909
- :Then(function(newSlotId: SaveSlotData.SlotId)
910
- if wasActive then
911
- -- Reselecting restores the continue pointer via the ActiveSlotId hook.
912
- return self:PromiseSelectSlot(newSlotId):Then(function()
913
- return newSlotId
914
- end)
915
- end
916
-
917
- -- Non-active reset never reselects, so carry the resume pointer onto the fresh id
918
- -- ourselves when this slot was the one "Continue" would resume.
919
- if wasLastActive then
920
- self._lastActiveSlotId = newSlotId
921
- self.LastActiveSlotId.Value = newSlotId
922
- end
923
-
924
- return newSlotId
925
- end)
926
- end)
459
+ return self._slotsDataStore:PromiseResetSlot(slotId)
927
460
  end
928
461
 
929
462
  --[=[
930
- Resets the active slot to a fresh empty one -- see [HasSaveSlots.PromiseResetSlot]. The slot
931
- keeps its index and name; its saved data and metadata (timestamps) start fresh, and the fresh
932
- slot stays selected. Resolves to the new slot id, or nil when no slot is active.
463
+ Resets the active slot to a fresh empty one -- see [HasSaveSlots.PromiseResetSlot]. Resolves to the
464
+ new slot id, or nil when no slot is active.
933
465
  ]=]
934
466
  function HasSaveSlots.PromiseResetActiveSlot(self: HasSaveSlots): Promise.Promise<SaveSlotData.SlotId?>
935
- return (self._loadPromise :: any):Then(function(): any
936
- local slotId = self.ActiveSlotId.Value
937
- if not slotId then
938
- return nil -- Nothing selected to reset
939
- end
940
-
941
- return self:PromiseResetSlot(slotId)
942
- end)
467
+ return self._slotsDataStore:PromiseResetActiveSlot()
943
468
  end
944
469
 
945
470
  --[=[
@@ -950,20 +475,7 @@ function HasSaveSlots.PromiseSetSlotMetadata(
950
475
  slotId: SaveSlotData.SlotId,
951
476
  data: SaveSlotData.SaveSlotMetadata
952
477
  ): Promise.Promise<any>
953
- if data.SlotId and (data.SlotId ~= slotId) then
954
- return (Promise :: any).rejected("SlotId is locked")
955
- end
956
-
957
- return (self._loadPromise :: any):Then(function()
958
- local slot = self._slotMap[slotId]
959
-
960
- -- Routing depends on immutable indices to distinguish the default slot
961
- if data.SlotIndex and (data.SlotIndex ~= SaveSlotData.SlotIndex:Get(slot)) then
962
- return (Promise :: any).rejected("SlotIndex is locked")
963
- end
964
-
965
- SaveSlotData:Set(slot, data)
966
- end)
478
+ return self._slotsDataStore:PromiseSetSlotMetadata(slotId, data)
967
479
  end
968
480
 
969
481
  --[=[
@@ -973,10 +485,7 @@ function HasSaveSlots.PromiseGetSlotMetadata(
973
485
  self: HasSaveSlots,
974
486
  slotId: SaveSlotData.SlotId
975
487
  ): Promise.Promise<SaveSlotData.SaveSlotMetadata?>
976
- return (self._loadPromise :: any):Then(function()
977
- local slot = self._slotMap[slotId]
978
- return (Promise :: any).resolved(slot and SaveSlotData:Get(slot))
979
- end)
488
+ return self._slotsDataStore:PromiseGetSlotMetadata(slotId)
980
489
  end
981
490
 
982
491
  --[=[
@@ -986,26 +495,14 @@ function HasSaveSlots.PromiseSlotIdFromIndex(
986
495
  self: HasSaveSlots,
987
496
  slotIndex: number
988
497
  ): Promise.Promise<SaveSlotData.SlotId?>
989
- return (self._loadPromise :: any):Then(function()
990
- for slotId, slot in self._slotMap do
991
- if self:_isEphemeral(slotId) then
992
- continue -- ephemeral slots are never addressable by index
993
- end
994
- if slotIndex == SaveSlotData.SlotIndex:Get(slot) then
995
- return (Promise :: any).resolved(slotId)
996
- end
997
- end
998
- return (Promise :: any).resolved(nil)
999
- end)
498
+ return self._slotsDataStore:PromiseSlotIdFromIndex(slotIndex)
1000
499
  end
1001
500
 
1002
501
  --[=[
1003
502
  Gets the last active slot ID
1004
503
  ]=]
1005
504
  function HasSaveSlots.PromiseLastActiveSlotId(self: HasSaveSlots): Promise.Promise<SaveSlotData.SlotId?>
1006
- return (self._loadPromise :: any):Then(function()
1007
- return self.ActiveSlotId.Value or self._lastActiveSlotId
1008
- end)
505
+ return self._slotsDataStore:PromiseLastActiveSlotId()
1009
506
  end
1010
507
 
1011
508
  --[=[
@@ -1014,21 +511,7 @@ end
1014
511
  "Continue" affordance that every save-slot consumer tends to need.
1015
512
  ]=]
1016
513
  function HasSaveSlots.PromiseSelectLastSaveSlot(self: HasSaveSlots): Promise.Promise<SaveSlotData.SlotId?>
1017
- return self:PromiseLastActiveSlotId():Then(function(lastActiveSlotId: SaveSlotData.SlotId?)
1018
- if not lastActiveSlotId then
1019
- return nil
1020
- end
1021
-
1022
- return self:PromiseHasSlot(lastActiveSlotId):Then(function(hasLastSlot: boolean)
1023
- if not hasLastSlot then
1024
- return nil
1025
- end
1026
-
1027
- return self:PromiseSelectSlot(lastActiveSlotId):Then(function()
1028
- return lastActiveSlotId
1029
- end)
1030
- end)
1031
- end)
514
+ return self._slotsDataStore:PromiseSelectLastSaveSlot()
1032
515
  end
1033
516
 
1034
517
  --[=[
@@ -1037,45 +520,12 @@ end
1037
520
  affordance.
1038
521
  ]=]
1039
522
  function HasSaveSlots.PromiseSelectNewSaveSlot(self: HasSaveSlots): Promise.Promise<SaveSlotData.SlotId?>
1040
- return (self._loadPromise :: any):Then(function(): any
1041
- local usedIndices = {}
1042
- for existingSlotId, slot in self._slotMap do
1043
- if not self:_isEphemeral(existingSlotId) then
1044
- usedIndices[SaveSlotData.SlotIndex:Get(slot)] = true
1045
- end
1046
- end
1047
-
1048
- -- Lowest free positive index. Fills gaps left by deletions (delete slot 2 of
1049
- -- [1,2,3] and the next new slot reuses index 2). With a finite MaxSlotCount this
1050
- -- returns nil once [1, MaxSlotCount] is full; with an unbounded count (math.huge)
1051
- -- there is always a next integer, so it never returns nil.
1052
- local freeIndex = 1
1053
- while usedIndices[freeIndex] do
1054
- freeIndex += 1
1055
- end
1056
-
1057
- if freeIndex > self.MaxSlotCount.Value then
1058
- return nil
1059
- end
1060
-
1061
- return self:PromiseCreateSlot(freeIndex):Then(function(slotId: SaveSlotData.SlotId)
1062
- return self:PromiseSelectSlot(slotId):Then(function()
1063
- return slotId
1064
- end)
1065
- end)
1066
- end)
523
+ return self._slotsDataStore:PromiseSelectNewSaveSlot()
1067
524
  end
1068
525
 
1069
526
  --[=[
1070
- Creates a fresh ephemeral slot and selects it, resolving to its id. An ephemeral slot is selectable and
1071
- active exactly like a real one -- it drives [HasSaveSlots.ObserveActiveSlotStoreBrio], summaries, and
1072
- playtime the same way, and its metadata replicates to the client like any other slot's, so UI can render
1073
- the active session's name and summary -- but it is never persisted: no metadata is written, its data store
1074
- is in-memory, and it is torn down the moment it stops being the active slot. It is also excluded from the
1075
- save list ([SaveSlotDataService.GetSlotList] / [SaveSlotDataService.ObserveSlotList]), so it never shows up
1076
- as something the player can return to. Selecting it never disturbs the persisted active-slot pointer or the
1077
- "Continue" target, so the real slot the player came from resumes untouched afterward. Backs a throwaway
1078
- session (e.g. exploring a lobby) that must leave no trace on save data.
527
+ Creates a fresh ephemeral slot and selects it, resolving to its id. See
528
+ [HasSaveSlotsDataStore.PromiseSelectEphemeralSlot].
1079
529
 
1080
530
  @param metadata SaveSlotCreateMetadata? -- optional SlotName/Summary for the in-memory slot
1081
531
  @return Promise<SlotId>
@@ -1084,22 +534,7 @@ function HasSaveSlots.PromiseSelectEphemeralSlot(
1084
534
  self: HasSaveSlots,
1085
535
  metadata: SaveSlotCreateMetadata?
1086
536
  ): Promise.Promise<SaveSlotData.SlotId>
1087
- return (self._loadPromise :: any):Then(function()
1088
- local slotId = HttpService:GenerateGUID(false)
1089
- local data = {
1090
- SlotId = slotId,
1091
- SlotIndex = SaveSlotConstants.EPHEMERAL_SLOT_INDEX,
1092
- SlotName = (metadata and metadata.SlotName) or "Ephemeral",
1093
- CreatedTime = os.time(),
1094
- Summary = metadata and metadata.Summary,
1095
- }
1096
-
1097
- self:_buildSlot(slotId, data, true, true)
1098
-
1099
- return self:PromiseSelectSlot(slotId):Then(function()
1100
- return slotId
1101
- end)
1102
- end)
537
+ return self._slotsDataStore:PromiseSelectEphemeralSlot(metadata)
1103
538
  end
1104
539
 
1105
540
  --[=[
@@ -1135,198 +570,6 @@ function HasSaveSlots.PromiseIncomingSlotId(self: HasSaveSlots): Promise.Promise
1135
570
  end)
1136
571
  end
1137
572
 
1138
- -- Maid-owning every hop is what makes this safe, for the same reason as the selection chain in
1139
- -- SaveSlotService: a session-locked or retrying read settles long after the player left, and Promise has no
1140
- -- cancellation, so owning only the outermost promise detaches nothing upstream. Calling into this destroyed
1141
- -- (metatable-stripped) object -- or into its destroyed stores -- throws, and because a datastore load
1142
- -- resolves inside its UpdateAsync transform, that throw surfaces as a "Transform function error" and takes
1143
- -- the transform's write down with it. The liveness checks cover a settle that lands mid-teardown, before
1144
- -- this promise's own maid task was reached. See SaveSlotLateSettle.spec.
1145
- function HasSaveSlots._promiseLoadSlots(self: HasSaveSlots): Promise.Promise<{}>
1146
- return self._maid:GivePromise(self._playerDataStoreService:PromiseDataStore(self._obj)):Then(function(dataStore)
1147
- if not self.Destroy then
1148
- return nil -- Destroyed
1149
- end
1150
-
1151
- self._dataStore = dataStore
1152
- self._systemStore = dataStore:GetSubStore(SaveSlotConstants.SYSTEM_STORE_KEY)
1153
- self._metadataStore = self._systemStore:GetSubStore(SaveSlotConstants.METADATA_STORE_KEY)
1154
-
1155
- return self._maid:GivePromise(self._metadataStore:LoadAll({})):Then(function(metadata)
1156
- if not self.Destroy then
1157
- return nil -- Destroyed
1158
- end
1159
-
1160
- for slotId, data in metadata do
1161
- self:_buildSlot(slotId, data)
1162
- end
1163
-
1164
- return self._maid
1165
- :GivePromise(self._systemStore:Load("activeSlotId"))
1166
- :Then(function(activeId: SaveSlotData.SlotId?)
1167
- if not self.Destroy then
1168
- return nil -- Destroyed
1169
- end
1170
-
1171
- self._lastActiveSlotId = activeId
1172
- self.LastActiveSlotId.Value = activeId
1173
-
1174
- -- The persisted active-slot pointer and the replicated "Continue" target only ever track real
1175
- -- slots. This replaces StoreOnValueChange so an ephemeral selection is invisible to both:
1176
- -- entering one leaves them pinned to the real slot, and the ephemeral slot is torn down the
1177
- -- moment it stops being active. We track the id we are leaving to know which of those to do.
1178
- local previousActiveSlotId: SaveSlotData.SlotId? = activeId
1179
-
1180
- self._maid:GiveTask(self.ActiveSlotId.Changed:Connect(function()
1181
- local active = self.ActiveSlotId.Value
1182
-
1183
- -- Replicate the active transferable-ephemeral slot's shared-store key (nil otherwise) so a
1184
- -- client-initiated teleport can carry it forward (SaveSlotServiceClient's provider reads this).
1185
- self.ActiveTransferableEphemeralKey.Value = if active
1186
- then self._transferableEphemeralKeys[active]
1187
- else nil
1188
-
1189
- local leftSlotId = previousActiveSlotId
1190
- -- Read before the retire below, while the outgoing slot is still in the map.
1191
- local leavingEphemeral = self:_isEphemeral(leftSlotId)
1192
- previousActiveSlotId = active
1193
-
1194
- -- Persist the pointer + remember the Continue target only for real-slot transitions
1195
- -- (real -> real, real -> nil deselect, nil -> real). Skip both ephemeral cases: entering an
1196
- -- ephemeral slot must stay invisible to persistence, and leaving one back to no slot must
1197
- -- leave the real pointer pinned where it was.
1198
- local enteringEphemeral = self:_isEphemeral(active)
1199
- local leavingEphemeralToMenu = leavingEphemeral and active == nil
1200
- if not (enteringEphemeral or leavingEphemeralToMenu) then
1201
- self._systemStore:Store("activeSlotId", active)
1202
- if active ~= nil then
1203
- self._lastActiveSlotId = active
1204
- self.LastActiveSlotId.Value = active
1205
- end
1206
- end
1207
-
1208
- -- An ephemeral slot exists only while it is the active slot; retire the one we just left.
1209
- if leavingEphemeral and leftSlotId ~= active then
1210
- self:_destroyEphemeralSlot(leftSlotId :: SaveSlotData.SlotId)
1211
- end
1212
- end))
1213
-
1214
- -- Matches the liveness-guard returns above, which make this callback's inferred return
1215
- -- type nil; falling off the end instead returns no values at all.
1216
- return nil
1217
- end)
1218
- end)
1219
- end)
1220
- end
1221
-
1222
- function HasSaveSlots._getSlotStore(self: HasSaveSlots, slotId: SaveSlotData.SlotId): DataStoreStage.DataStoreStage
1223
- local ephemeralStore = self._ephemeralStores[slotId]
1224
- if ephemeralStore then
1225
- return ephemeralStore
1226
- end
1227
-
1228
- local slot = self._slotMap[slotId]
1229
- if slot and (SaveSlotData.SlotIndex:Get(slot) == SaveSlotConstants.DEFAULT_SLOT_INDEX) then
1230
- return self._dataStore
1231
- end
1232
- return self._systemStore:GetSubStore(SaveSlotConstants.SLOT_STORE_KEY):GetSubStore(slotId)
1233
- end
1234
-
1235
- local MUTABLE_METADATA_KEYS =
1236
- { "SlotName", "CreatedTime", "LastPlayedTime", "Summary", "TimePlayed", "PlayCount", "LastSessionLength" }
1237
-
1238
- function HasSaveSlots._buildSlot(
1239
- self: HasSaveSlots,
1240
- slotId: SaveSlotData.SlotId,
1241
- data: SaveSlotData.SaveSlotMetadata,
1242
- isNew: boolean?,
1243
- isEphemeral: boolean?
1244
- ): ()
1245
- local maid = Maid.new()
1246
- self._maid[slotId] = maid
1247
-
1248
- local slot = maid:Add(Instance.new("Folder"))
1249
- slot.Name = slotId
1250
- slot.Archivable = false
1251
-
1252
- local attributes = SaveSlotData:Create(slot)
1253
- attributes.SlotId.Value = slotId
1254
- attributes.SlotIndex.Value = data.SlotIndex
1255
-
1256
- if isEphemeral then
1257
- -- Ephemeral: seed the metadata in memory with no write-back wiring, and back the slot with an in-memory
1258
- -- store. The folder still joins the replicated container so the client can read the active slot's
1259
- -- metadata (name, summary, playtime) the same way it reads a real slot's -- what makes the slot
1260
- -- ephemeral is that nothing is persisted, not that it is invisible. The IsEphemeral attribute is what
1261
- -- keeps it out of the save list; SaveSlotDataService's list reads filter on it.
1262
- --
1263
- -- The in-memory store's lifetime is owned by this slot's maid (which is in turn owned by self._maid),
1264
- -- so it is Destroyed -- and becomes GC-eligible -- the instant the slot is retired (_destroyEphemeralSlot)
1265
- -- or the player unbinds. Nothing outside this object holds a lasting reference: while the slot is active
1266
- -- ObserveActiveSlotStoreBrio hands it out inside a Brio that dies when the slot deselects, releasing it.
1267
- attributes.IsEphemeral.Value = true
1268
- self._ephemeralStores[slotId] = maid:Add(InMemoryDataStore.new(slotId))
1269
-
1270
- for _, key in MUTABLE_METADATA_KEYS do
1271
- attributes[key].Value = data[key]
1272
- end
1273
-
1274
- -- Parent last, so the folder replicates carrying IsEphemeral -- a client that saw it land without the
1275
- -- flag would briefly list a throwaway slot as a save.
1276
- slot.Parent = self._slotContainer
1277
-
1278
- self._slotMap[slotId] = slot
1279
- maid:GiveTask(function()
1280
- self._slotMap[slotId] = nil
1281
- self._ephemeralStores[slotId] = nil
1282
- self._transferableEphemeralKeys[slotId] = nil
1283
- end)
1284
- return
1285
- end
1286
-
1287
- local metadataStore = self._metadataStore:GetSubStore(slotId)
1288
-
1289
- -- Store immutable SlotIndex once on creation
1290
- if isNew then
1291
- metadataStore:Store("SlotIndex", data.SlotIndex)
1292
- end
1293
-
1294
- -- Store mutable metadata on change
1295
- for _, key in MUTABLE_METADATA_KEYS do
1296
- attributes[key].Value = data[key]
1297
- maid:GiveTask(metadataStore:StoreOnValueChange(key, attributes[key]))
1298
-
1299
- if isNew then
1300
- metadataStore:Store(key, attributes[key].Value)
1301
- end
1302
- end
1303
-
1304
- slot.Parent = self._slotContainer
1305
-
1306
- self._slotMap[slotId] = slot
1307
-
1308
- maid:GiveTask(function()
1309
- self._slotMap[slotId] = nil
1310
- end)
1311
- end
1312
-
1313
- -- Whether the slot is an ephemeral (session-only, never-persisted) slot. The slot's own IsEphemeral property
1314
- -- is the single source of truth (set once at creation in _buildSlot); nil-safe so callers can pass a possibly
1315
- -- nil active-slot id directly.
1316
- function HasSaveSlots._isEphemeral(self: HasSaveSlots, slotId: SaveSlotData.SlotId?): boolean
1317
- if slotId == nil then
1318
- return false
1319
- end
1320
- local slot = self._slotMap[slotId] :: Folder?
1321
- return slot ~= nil and SaveSlotData.IsEphemeral:Get(slot) == true
1322
- end
1323
-
1324
- -- Tears down the ephemeral slot's maid (folder, in-memory store, and every map entry via the teardown task
1325
- -- registered in _buildSlot). Idempotent -- clearing an already-cleared maid key is a no-op.
1326
- function HasSaveSlots._destroyEphemeralSlot(self: HasSaveSlots, slotId: SaveSlotData.SlotId): ()
1327
- self._maid[slotId] = nil
1328
- end
1329
-
1330
573
  function HasSaveSlots._setupSummary(self: HasSaveSlots): ()
1331
574
  self._maid:GiveTask(
1332
575
  self:ObserveActiveSlotStoreBrio():Subscribe(function(brio: Brio.Brio<DataStoreStage.DataStoreStage>)
@@ -1334,8 +577,7 @@ function HasSaveSlots._setupSummary(self: HasSaveSlots): ()
1334
577
  return
1335
578
  end
1336
579
 
1337
- local activeSlotId = self.ActiveSlotId.Value
1338
- local activeSlot = activeSlotId and self._slotMap[activeSlotId]
580
+ local activeSlot = self._slotsDataStore:GetSlotFolder(self.ActiveSlotId.Value)
1339
581
  if not activeSlot then
1340
582
  return
1341
583
  end
@@ -1419,91 +661,8 @@ function HasSaveSlots._observeProviderValue(
1419
661
  }) :: any
1420
662
  end
1421
663
 
1422
- --[=[
1423
- Accrues per-slot playtime automatically. A "session" spans the time a slot is the active slot:
1424
- selecting a slot begins one (bumping PlayCount), and deselecting, switching, or unbinding ends
1425
- it. Elapsed wall time is folded into the slot's TimePlayed from a datastore saving callback, so
1426
- it persists on exactly the cadence the data is written -- always fresh at save time, with no
1427
- separate timer -- and again at each session boundary.
1428
- ]=]
1429
- function HasSaveSlots._setupPlaytimeTracking(self: HasSaveSlots): ()
1430
- self._playSessionSlotId = nil
1431
- self._playSessionStart = nil
1432
- self._playSessionLastFlush = nil
1433
-
1434
- -- The active slot bounds the session: end the previous one (if any) and begin the new one.
1435
- self._maid:GiveTask(self.ActiveSlotId.Changed:Connect(function()
1436
- self:_endPlaySession()
1437
-
1438
- local activeSlotId = self.ActiveSlotId.Value
1439
- if activeSlotId ~= nil then
1440
- self:_beginPlaySession(activeSlotId)
1441
- end
1442
- end))
1443
-
1444
- -- Fold accrued time into TimePlayed just before every save so the written value is current. The
1445
- -- callback runs before the save serializes staged data (see DataStore._syncData), so the flush is
1446
- -- captured by that same save -- including the final save-on-leave.
1447
- self._maid:GivePromise(self._loadPromise):Then(function()
1448
- self._maid:GiveTask(self._dataStore:AddSavingCallback(function()
1449
- self:_flushPlaytime()
1450
- end))
1451
- end)
1452
-
1453
- -- Best-effort flush on unbind for the case where the binder tears down before that final save.
1454
- self._maid:GiveTask(function()
1455
- self:_endPlaySession()
1456
- end)
1457
- end
1458
-
1459
- function HasSaveSlots._beginPlaySession(self: HasSaveSlots, slotId: SaveSlotData.SlotId): ()
1460
- local now = os.time()
1461
- self._playSessionSlotId = slotId
1462
- self._playSessionStart = now
1463
- self._playSessionLastFlush = now
1464
-
1465
- local slot = self._slotMap[slotId]
1466
- if slot then
1467
- SaveSlotData.PlayCount:Set(slot, (SaveSlotData.PlayCount:Get(slot) or 0) + 1)
1468
- end
1469
- end
1470
-
1471
- function HasSaveSlots._flushPlaytime(self: HasSaveSlots): ()
1472
- local slotId = self._playSessionSlotId
1473
- if slotId == nil then
1474
- return
1475
- end
1476
-
1477
- local slot = self._slotMap[slotId]
1478
- if not slot then
1479
- return
1480
- end
1481
-
1482
- local now = os.time()
1483
-
1484
- -- Add only the time since the last flush so repeated flushes within a session never double count.
1485
- local sinceFlush = now - (self._playSessionLastFlush or now)
1486
- if sinceFlush > 0 then
1487
- SaveSlotData.TimePlayed:Set(slot, (SaveSlotData.TimePlayed:Get(slot) or 0) + sinceFlush)
1488
- self._playSessionLastFlush = now
1489
- end
1490
-
1491
- SaveSlotData.LastSessionLength:Set(slot, now - (self._playSessionStart or now))
1492
- end
1493
-
1494
- function HasSaveSlots._endPlaySession(self: HasSaveSlots): ()
1495
- if self._playSessionSlotId == nil then
1496
- return
1497
- end
1498
-
1499
- self:_flushPlaytime()
1500
- self._playSessionSlotId = nil
1501
- self._playSessionStart = nil
1502
- self._playSessionLastFlush = nil
1503
- end
1504
-
1505
664
  function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1506
- self._maid:GiveTask(self._remoting.PromiseHasSlot:Bind(function(remotePlayer, ...)
665
+ self._maid:GiveTask(self._remoting.PromiseHasSlot:Bind(function(remotePlayer: Player, ...)
1507
666
  if remotePlayer == self._obj then
1508
667
  return self:PromiseHasSlot(...)
1509
668
  else
@@ -1511,7 +670,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1511
670
  end
1512
671
  end))
1513
672
 
1514
- self._maid:GiveTask(self._remoting.PromiseSelectSlot:Bind(function(remotePlayer, ...)
673
+ self._maid:GiveTask(self._remoting.PromiseSelectSlot:Bind(function(remotePlayer: Player, ...)
1515
674
  if remotePlayer == self._obj then
1516
675
  return self:PromiseSelectSlot(...)
1517
676
  else
@@ -1519,7 +678,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1519
678
  end
1520
679
  end))
1521
680
 
1522
- self._maid:GiveTask(self._remoting.PromiseCreateSlot:Bind(function(remotePlayer, ...)
681
+ self._maid:GiveTask(self._remoting.PromiseCreateSlot:Bind(function(remotePlayer: Player, ...)
1523
682
  if remotePlayer == self._obj then
1524
683
  return self:PromiseCreateSlot(...)
1525
684
  else
@@ -1527,7 +686,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1527
686
  end
1528
687
  end))
1529
688
 
1530
- self._maid:GiveTask(self._remoting.PromiseDeleteSlot:Bind(function(remotePlayer, ...)
689
+ self._maid:GiveTask(self._remoting.PromiseDeleteSlot:Bind(function(remotePlayer: Player, ...)
1531
690
  if remotePlayer == self._obj then
1532
691
  return self:PromiseDeleteSlot(...)
1533
692
  else
@@ -1535,7 +694,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1535
694
  end
1536
695
  end))
1537
696
 
1538
- self._maid:GiveTask(self._remoting.PromiseSetSlotMetadata:Bind(function(remotePlayer, ...)
697
+ self._maid:GiveTask(self._remoting.PromiseSetSlotMetadata:Bind(function(remotePlayer: Player, ...)
1539
698
  if remotePlayer == self._obj then
1540
699
  return self:PromiseSetSlotMetadata(...)
1541
700
  else
@@ -1543,7 +702,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1543
702
  end
1544
703
  end))
1545
704
 
1546
- self._maid:GiveTask(self._remoting.PromiseGetSlotMetadata:Bind(function(remotePlayer, ...)
705
+ self._maid:GiveTask(self._remoting.PromiseGetSlotMetadata:Bind(function(remotePlayer: Player, ...)
1547
706
  if remotePlayer == self._obj then
1548
707
  return self:PromiseGetSlotMetadata(...)
1549
708
  else
@@ -1551,7 +710,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1551
710
  end
1552
711
  end))
1553
712
 
1554
- self._maid:GiveTask(self._remoting.PromiseSlotIdFromIndex:Bind(function(remotePlayer, ...)
713
+ self._maid:GiveTask(self._remoting.PromiseSlotIdFromIndex:Bind(function(remotePlayer: Player, ...)
1555
714
  if remotePlayer == self._obj then
1556
715
  return self:PromiseSlotIdFromIndex(...)
1557
716
  else
@@ -1559,7 +718,7 @@ function HasSaveSlots._setupRemotes(self: HasSaveSlots): ()
1559
718
  end
1560
719
  end))
1561
720
 
1562
- self._maid:GiveTask(self._remoting.PromiseLastActiveSlotId:Bind(function(remotePlayer)
721
+ self._maid:GiveTask(self._remoting.PromiseLastActiveSlotId:Bind(function(remotePlayer: Player)
1563
722
  if remotePlayer == self._obj then
1564
723
  return self:PromiseLastActiveSlotId()
1565
724
  else