@inglorious/store 12.7.0 → 12.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/store",
3
- "version": "12.7.0",
3
+ "version": "12.9.0",
4
4
  "description": "A state manager for real-time, collaborative apps, inspired by game development patterns and compatible with Redux.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
@@ -88,7 +88,7 @@
88
88
  "@inglorious/eslint-config": "1.2.0",
89
89
  "@inglorious/utils": "5.4.0",
90
90
  "@reduxjs/toolkit": "^2.14.0",
91
- "prettier": "^3.9.10",
91
+ "prettier": "^3.10.0",
92
92
  "typescript": "~7.0.2",
93
93
  "vite": "^8.3.8",
94
94
  "vitest": "^5.1.0"
@@ -22,9 +22,11 @@ export function fsm(states) {
22
22
 
23
23
  const handler = states[entity.state]?.[eventName] ?? type[eventName]
24
24
 
25
- handler?.(entity, event, api)
25
+ const result = handler?.(entity, event, api)
26
26
 
27
27
  announce(entity, from, api)
28
+
29
+ return result
28
30
  },
29
31
  }),
30
32
  {},
package/src/store.js CHANGED
@@ -9,6 +9,7 @@ import { createApi } from "./api.js"
9
9
  import { augmentEntities, augmentEntity } from "./entities.js"
10
10
  import { EventMap, parseEvent } from "./event-map.js"
11
11
  import { applyMiddlewares } from "./middlewares.js"
12
+ import { compute, createSelector } from "./select.js"
12
13
  import { augmentType, augmentTypes } from "./types.js"
13
14
 
14
15
  /** Copies only the entities that change, through a draft proxy. */
@@ -19,6 +20,12 @@ const COPY_ON_DISPATCH = "copy-on-dispatch"
19
20
 
20
21
  const UPDATE_STRATEGIES = [STRUCTURAL_SHARING, COPY_ON_DISPATCH]
21
22
 
23
+ /** Every engine's message for touching a revoked proxy says "revoked". */
24
+ const REVOKED = /revoked/i
25
+
26
+ /** What engines say when code writes to a frozen object. */
27
+ const FROZEN = /read[- ]only|not extensible|cannot (assign|delete|define)/i
28
+
22
29
  /** Events every entity gets, whether or not its type answers them. */
23
30
  const LIFECYCLE_EVENTS = ["create", "destroy"]
24
31
 
@@ -49,10 +56,12 @@ const LIFECYCLE_EVENTS = ["create", "destroy"]
49
56
  * @param {boolean} [config.autoCreateEntities=false] - Creates an entity for each type that has none.
50
57
  * @param {"auto" | "manual"} [config.updateMode="auto"] - Whether each event triggers an update, or updates are batched until `update()` is called.
51
58
  * @param {UpdateStrategy} [config.updateStrategy="structural-sharing"] - How an event's changes are copied.
52
- * @param {boolean} [config.devMode=false] - Freezes the state after each event under structural sharing, so a write outside a handler throws.
59
+ * @param {boolean} [config.devMode=false] - Freezes the state, so a write to an entity a handler was not given, or one after an await, throws an error that says so.
53
60
  * @returns {Store} The store with methods to interact with state and events.
54
61
  * @throws {TypeError} If `updateStrategy` is not a supported strategy.
55
62
  */
63
+ export { compute, createSelector }
64
+
56
65
  export function createStore({
57
66
  types: originalTypes = {},
58
67
  entities: originalEntities = {},
@@ -128,19 +137,27 @@ export function createStore({
128
137
  isProcessing = true
129
138
  const processedEvents = []
130
139
 
131
- if (updateStrategy === STRUCTURAL_SHARING) {
132
- state = create(state, (root) => drain(writeThrough(root)), {
133
- enableAutoFreeze: devMode,
134
- })
135
- } else {
136
- const draft = copyOnDispatch(state)
137
- drain(draft)
138
- state = draft.entities
140
+ try {
141
+ if (updateStrategy === STRUCTURAL_SHARING) {
142
+ state = create(state, (root) => drain(writeThrough(root)), {
143
+ enableAutoFreeze: devMode,
144
+ })
145
+ } else {
146
+ const draft = copyOnDispatch(state)
147
+ drain(draft)
148
+ state = draft.entities
149
+ // Without a proxy, a late write would land on the state unseen.
150
+ if (devMode) draft.copied.forEach((id) => deepFreeze(state[id]))
151
+ }
152
+ } catch (error) {
153
+ // The update is rolled back whole, and the events still queued with it.
154
+ incomingEvents = []
155
+ throw error
156
+ } finally {
157
+ activeDraft = null
158
+ isProcessing = false
139
159
  }
140
160
 
141
- activeDraft = null
142
- isProcessing = false
143
-
144
161
  isNotifying = true
145
162
  listeners.forEach((onUpdate) => onUpdate())
146
163
  isNotifying = false
@@ -197,7 +214,14 @@ export function createStore({
197
214
  const entity = draft.entities[id]
198
215
  if (halted && !entity.updatesWhilePaused) continue
199
216
 
200
- types[entity.type][handlerName]?.(draft.take(id), event.payload, api)
217
+ const handler = types[entity.type][handlerName]
218
+ if (!handler) continue
219
+
220
+ const result = callHandler(
221
+ () => handler(draft.take(id), event.payload, api),
222
+ `${entity.type}.${handlerName}`,
223
+ )
224
+ explainLateAccess(result, entity.type, handlerName)
201
225
  }
202
226
 
203
227
  if (handlerName === "destroy" && targetId) {
@@ -209,7 +233,11 @@ export function createStore({
209
233
  }
210
234
 
211
235
  systems.forEach((system) => {
212
- system[handlerName]?.(draft.forSystems, event.payload, api)
236
+ if (!system[handlerName]) return
237
+ callHandler(
238
+ () => system[handlerName](draft.forSystems, event.payload, api),
239
+ `A system's ${handlerName}`,
240
+ )
213
241
  })
214
242
  }
215
243
 
@@ -227,6 +255,30 @@ export function createStore({
227
255
  * @param {any} payload - The event payload. Carries the least that can be had
228
256
  * about what happened.
229
257
  */
258
+ /**
259
+ * Calls a handler. In dev mode, where the state is frozen, a write to a
260
+ * frozen object can only be a write to an entity the handler was not given,
261
+ * such as one read through the api: say so.
262
+ * @param {() => unknown} call - The handler, called.
263
+ * @param {string} name - Who the handler is, for the message.
264
+ * @returns {unknown} What the handler returned.
265
+ */
266
+ function callHandler(call, name) {
267
+ if (!devMode) return call()
268
+
269
+ try {
270
+ return call()
271
+ } catch (error) {
272
+ if (!(error instanceof TypeError) || !FROZEN.test(error.message)) {
273
+ throw error
274
+ }
275
+ throw new TypeError(
276
+ `${name} wrote to an entity it was not given, such as one read with api.getEntity() or api.getEntities(). Those are the state as the previous event left it, and are read-only: notify an event to that entity instead.`,
277
+ { cause: error },
278
+ )
279
+ }
280
+ }
281
+
230
282
  function notify(type, payload) {
231
283
  // Through store.dispatch rather than dispatch, so that middlewares see it.
232
284
  store.dispatch({ type, payload })
@@ -338,7 +390,7 @@ export function createStore({
338
390
  oldEntityIds.has(id),
339
391
  )
340
392
 
341
- state = oldEntities
393
+ state = { ...oldEntities }
342
394
  eventMap = new EventMap(types, oldEntities)
343
395
  activeDraft = null
344
396
  incomingEvents = []
@@ -375,6 +427,8 @@ export function createStore({
375
427
  }
376
428
  }
377
429
  }
430
+
431
+ if (devMode) deepFreeze(state)
378
432
  }
379
433
 
380
434
  /**
@@ -629,6 +683,7 @@ function writeThrough(entities) {
629
683
  function copyOnDispatch(state) {
630
684
  const entities = { ...state }
631
685
  const before = new Map()
686
+ const copied = new Set()
632
687
  let all = null
633
688
 
634
689
  function remember(id) {
@@ -639,6 +694,7 @@ function copyOnDispatch(state) {
639
694
  if (!before.has(id) && Object.hasOwn(entities, id)) {
640
695
  before.set(id, entities[id])
641
696
  entities[id] = clone(entities[id])
697
+ copied.add(id)
642
698
  }
643
699
 
644
700
  return entities[id]
@@ -647,6 +703,7 @@ function copyOnDispatch(state) {
647
703
  function put(id, entity) {
648
704
  remember(id)
649
705
  entities[id] = entity
706
+ copied.add(id)
650
707
  }
651
708
 
652
709
  function remove(id) {
@@ -675,6 +732,7 @@ function copyOnDispatch(state) {
675
732
  return {
676
733
  entities,
677
734
  forSystems,
735
+ copied,
678
736
  take,
679
737
  put,
680
738
  remove,
@@ -716,6 +774,44 @@ function overlay(entities, before) {
716
774
  return all
717
775
  }
718
776
 
777
+ /**
778
+ * Freezes an object and everything it holds.
779
+ * @param {unknown} value
780
+ * @returns {unknown} The value.
781
+ */
782
+ function deepFreeze(value) {
783
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) {
784
+ return value
785
+ }
786
+ Object.freeze(value)
787
+ for (const child of Object.values(value)) deepFreeze(child)
788
+ return value
789
+ }
790
+
791
+ /**
792
+ * Gives a clearer error when an async handler touches its entity after an
793
+ * `await`: the entity is a draft of the update, revoked once the update ends.
794
+ * @param {unknown} result - What the handler returned.
795
+ * @param {string} typeName - The handler's type.
796
+ * @param {string} handlerName - The handler.
797
+ * @returns {void}
798
+ */
799
+ function explainLateAccess(result, typeName, handlerName) {
800
+ if (typeof result?.then !== "function") return
801
+
802
+ result.then(undefined, (error) => {
803
+ const isLate =
804
+ error instanceof TypeError &&
805
+ (REVOKED.test(error.message) || FROZEN.test(error.message))
806
+ if (!isLate) throw error
807
+
808
+ throw new TypeError(
809
+ `${typeName}.${handlerName} accessed its entity after an async operation, when the update it belonged to had ended. Read what you need from the entity into a variable before the first await, or notify a new event after it and let that event's handler change the entity.`,
810
+ { cause: error },
811
+ )
812
+ })
813
+ }
814
+
719
815
  /**
720
816
  * Validates the given update strategy.
721
817
  * @param {UpdateStrategy} updateStrategy - The update strategy to validate.