@inglorious/store 12.7.0 → 12.8.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.8.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] - Under structural sharing, freezes the state, so a write to an entity a handler was not given 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,25 @@ 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
+ }
150
+ } catch (error) {
151
+ // The update is rolled back whole, and the events still queued with it.
152
+ incomingEvents = []
153
+ throw error
154
+ } finally {
155
+ activeDraft = null
156
+ isProcessing = false
139
157
  }
140
158
 
141
- activeDraft = null
142
- isProcessing = false
143
-
144
159
  isNotifying = true
145
160
  listeners.forEach((onUpdate) => onUpdate())
146
161
  isNotifying = false
@@ -197,7 +212,14 @@ export function createStore({
197
212
  const entity = draft.entities[id]
198
213
  if (halted && !entity.updatesWhilePaused) continue
199
214
 
200
- types[entity.type][handlerName]?.(draft.take(id), event.payload, api)
215
+ const handler = types[entity.type][handlerName]
216
+ if (!handler) continue
217
+
218
+ const result = callHandler(
219
+ () => handler(draft.take(id), event.payload, api),
220
+ `${entity.type}.${handlerName}`,
221
+ )
222
+ explainLateAccess(result, entity.type, handlerName)
201
223
  }
202
224
 
203
225
  if (handlerName === "destroy" && targetId) {
@@ -209,7 +231,11 @@ export function createStore({
209
231
  }
210
232
 
211
233
  systems.forEach((system) => {
212
- system[handlerName]?.(draft.forSystems, event.payload, api)
234
+ if (!system[handlerName]) return
235
+ callHandler(
236
+ () => system[handlerName](draft.forSystems, event.payload, api),
237
+ `A system's ${handlerName}`,
238
+ )
213
239
  })
214
240
  }
215
241
 
@@ -227,6 +253,30 @@ export function createStore({
227
253
  * @param {any} payload - The event payload. Carries the least that can be had
228
254
  * about what happened.
229
255
  */
256
+ /**
257
+ * Calls a handler. In dev mode, where the state is frozen, a write to a
258
+ * frozen object can only be a write to an entity the handler was not given,
259
+ * such as one read through the api: say so.
260
+ * @param {() => unknown} call - The handler, called.
261
+ * @param {string} name - Who the handler is, for the message.
262
+ * @returns {unknown} What the handler returned.
263
+ */
264
+ function callHandler(call, name) {
265
+ if (!devMode) return call()
266
+
267
+ try {
268
+ return call()
269
+ } catch (error) {
270
+ if (!(error instanceof TypeError) || !FROZEN.test(error.message)) {
271
+ throw error
272
+ }
273
+ throw new TypeError(
274
+ `${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.`,
275
+ { cause: error },
276
+ )
277
+ }
278
+ }
279
+
230
280
  function notify(type, payload) {
231
281
  // Through store.dispatch rather than dispatch, so that middlewares see it.
232
282
  store.dispatch({ type, payload })
@@ -338,7 +388,7 @@ export function createStore({
338
388
  oldEntityIds.has(id),
339
389
  )
340
390
 
341
- state = oldEntities
391
+ state = { ...oldEntities }
342
392
  eventMap = new EventMap(types, oldEntities)
343
393
  activeDraft = null
344
394
  incomingEvents = []
@@ -375,6 +425,8 @@ export function createStore({
375
425
  }
376
426
  }
377
427
  }
428
+
429
+ if (devMode && updateStrategy === STRUCTURAL_SHARING) deepFreeze(state)
378
430
  }
379
431
 
380
432
  /**
@@ -716,6 +768,43 @@ function overlay(entities, before) {
716
768
  return all
717
769
  }
718
770
 
771
+ /**
772
+ * Freezes an object and everything it holds.
773
+ * @param {unknown} value
774
+ * @returns {unknown} The value.
775
+ */
776
+ function deepFreeze(value) {
777
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) {
778
+ return value
779
+ }
780
+ Object.freeze(value)
781
+ for (const child of Object.values(value)) deepFreeze(child)
782
+ return value
783
+ }
784
+
785
+ /**
786
+ * Gives a clearer error when an async handler touches its entity after an
787
+ * `await`: the entity is a draft of the update, revoked once the update ends.
788
+ * @param {unknown} result - What the handler returned.
789
+ * @param {string} typeName - The handler's type.
790
+ * @param {string} handlerName - The handler.
791
+ * @returns {void}
792
+ */
793
+ function explainLateAccess(result, typeName, handlerName) {
794
+ if (typeof result?.then !== "function") return
795
+
796
+ result.then(undefined, (error) => {
797
+ if (!(error instanceof TypeError) || !REVOKED.test(error.message)) {
798
+ throw error
799
+ }
800
+
801
+ throw new TypeError(
802
+ `${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.`,
803
+ { cause: error },
804
+ )
805
+ })
806
+ }
807
+
719
808
  /**
720
809
  * Validates the given update strategy.
721
810
  * @param {UpdateStrategy} updateStrategy - The update strategy to validate.