|
| 1 | +import type { Plugin, AnyFn, Ctx } from '../types'; |
| 2 | +import isPlainObject from 'lodash.isplainobject'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Check if a value can be serialized (e.g. using `JSON.stringify`). |
| 6 | + * Adapted from: https://stackoverflow.com/a/30712764/3829557 |
| 7 | + */ |
| 8 | +function isSerializable(value: any) { |
| 9 | + // Primitives are OK. |
| 10 | + if ( |
| 11 | + value === undefined || |
| 12 | + value === null || |
| 13 | + typeof value === 'boolean' || |
| 14 | + typeof value === 'number' || |
| 15 | + typeof value === 'string' |
| 16 | + ) { |
| 17 | + return true; |
| 18 | + } |
| 19 | + |
| 20 | + // A non-primitive value that is neither a POJO or an array cannot be serialized. |
| 21 | + if (!isPlainObject(value) && !Array.isArray(value)) { |
| 22 | + return false; |
| 23 | + } |
| 24 | + |
| 25 | + // Recurse entries if the value is an object or array. |
| 26 | + for (const key in value) { |
| 27 | + if (!isSerializable(value[key])) return false; |
| 28 | + } |
| 29 | + |
| 30 | + return true; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Plugin that checks whether state is serializable, in order to avoid |
| 35 | + * network serialization bugs. |
| 36 | + */ |
| 37 | +const SerializablePlugin: Plugin = { |
| 38 | + name: 'plugin-serializable', |
| 39 | + |
| 40 | + fnWrap: (move: AnyFn) => (G: unknown, ctx: Ctx, ...args: any[]) => { |
| 41 | + const result = move(G, ctx, ...args); |
| 42 | + // Check state in non-production environments. |
| 43 | + if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) { |
| 44 | + throw new Error( |
| 45 | + 'Move state is not JSON-serialiazable.\n' + |
| 46 | + 'See https://boardgame.io/documentation/#/?id=state for more information.' |
| 47 | + ); |
| 48 | + } |
| 49 | + return result; |
| 50 | + }, |
| 51 | +}; |
| 52 | + |
| 53 | +export default SerializablePlugin; |
0 commit comments