mobx-state-tree 3.12.2 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +103 -23
  2. package/dist/core/action.d.ts +50 -48
  3. package/dist/core/actionContext.d.ts +27 -0
  4. package/dist/core/flow.d.ts +14 -30
  5. package/dist/core/json-patch.d.ts +36 -36
  6. package/dist/core/mst-operations.d.ts +451 -444
  7. package/dist/core/node/BaseNode.d.ts +1 -1
  8. package/dist/core/node/Hook.d.ts +17 -1
  9. package/dist/core/node/create-node.d.ts +1 -1
  10. package/dist/core/node/identifier-cache.d.ts +1 -1
  11. package/dist/core/node/livelinessChecking.d.ts +37 -37
  12. package/dist/core/node/node-utils.d.ts +28 -28
  13. package/dist/core/node/object-node.d.ts +1 -1
  14. package/dist/core/node/scalar-node.d.ts +1 -1
  15. package/dist/core/process.d.ts +45 -45
  16. package/dist/core/type/type-checker.d.ts +30 -30
  17. package/dist/core/type/type.d.ts +162 -177
  18. package/dist/index.d.ts +3 -3
  19. package/dist/internal.d.ts +37 -35
  20. package/dist/middlewares/create-action-tracking-middleware.d.ts +24 -22
  21. package/dist/middlewares/createActionTrackingMiddleware2.d.ts +34 -0
  22. package/dist/middlewares/on-action.d.ts +87 -79
  23. package/dist/mobx-state-tree.js +6285 -5985
  24. package/dist/mobx-state-tree.min.js +16 -1
  25. package/dist/mobx-state-tree.module.js +6234 -5938
  26. package/dist/mobx-state-tree.umd.js +6263 -5985
  27. package/dist/mobx-state-tree.umd.min.js +16 -1
  28. package/dist/types/complex-types/array.d.ts +52 -51
  29. package/dist/types/complex-types/map.d.ts +80 -79
  30. package/dist/types/complex-types/model.d.ts +133 -125
  31. package/dist/types/index.d.ts +29 -29
  32. package/dist/types/primitives.d.ts +81 -81
  33. package/dist/types/utility-types/custom.d.ts +60 -60
  34. package/dist/types/utility-types/enumeration.d.ts +5 -5
  35. package/dist/types/utility-types/frozen.d.ts +11 -11
  36. package/dist/types/utility-types/identifier.d.ts +44 -44
  37. package/dist/types/utility-types/late.d.ts +10 -10
  38. package/dist/types/utility-types/literal.d.ts +25 -25
  39. package/dist/types/utility-types/maybe.d.ts +26 -26
  40. package/dist/types/utility-types/optional.d.ts +20 -20
  41. package/dist/types/utility-types/reference.d.ts +41 -47
  42. package/dist/types/utility-types/refinement.d.ts +10 -10
  43. package/dist/types/utility-types/snapshotProcessor.d.ts +61 -61
  44. package/dist/types/utility-types/union.d.ts +55 -55
  45. package/dist/utils.d.ts +4 -4
  46. package/package.json +16 -12
package/README.md CHANGED
@@ -64,6 +64,12 @@ Supported browsers:
64
64
  - MobX-state-tree runs on any ES5 environment
65
65
  - However, for MobX version 4 or 5 can be used. MobX 4 will run on any environment, MobX 5 only on modern browsers. See for more details the [MobX readme](https://github.com/mobxjs/mobx#browser-support)
66
66
 
67
+ Supported devtools:
68
+
69
+ - [Reactotron](https://github.com/infinitered/reactotron)
70
+ - [MobX DevTools](https://chrome.google.com/webstore/detail/mobx-developer-tools/pfgnfdagidkfgccljigdamigbcnndkod)
71
+ - The Redux can be connected as well as demonstrated [here](https://github.com/mobxjs/mobx-state-tree/blob/1906a394906d2e8f2cc1c778e1e3228307c1b112/packages/mst-example-redux-todomvc/src/index.js#L6)
72
+
67
73
  # Getting started
68
74
 
69
75
  See the [Getting started](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/getting-started.md#getting-started) tutorial or follow the free [egghead.io course](https://egghead.io/courses/manage-application-state-with-mobx-state-tree) (note however that the course is for MST v2, so it might be a bit outdated).
@@ -153,7 +159,7 @@ Simply subscribing to the patch stream of a tree is another way to sync diffs wi
153
159
 
154
160
  Since MST uses MobX behind the scenes, it integrates seamlessly with [mobx](https://mobx.js.org) and [mobx-react](https://github.com/mobxjs/mobx-react). See also this [egghead.io lesson: Render mobx-state-tree Models in React](https://egghead.io/lessons/react-render-mobx-state-tree-models-in-react).
155
161
  Even cooler, because it supports snapshots, middleware and replayable actions out of the box, it is possible to replace a Redux store and reducer with a MobX state tree.
156
- This makes it possible to connect the Redux devtools to MST. See the [Redux / MST TodoMVC example](https://github.com/mobxjs/mobx-state-tree/blob/4c2b19ec4a6a8d74064e4b8a87c0f8b46e97e621/examples/redux-todomvc/src/index.js#L6).
162
+ This makes it possible to connect the Redux devtools to MST. See the [Redux / MST TodoMVC example](https://github.com/mobxjs/mobx-state-tree/blob/1906a394906d2e8f2cc1c778e1e3228307c1b112/packages/mst-example-redux-todomvc/src/index.js#L6).
157
163
 
158
164
  ---
159
165
 
@@ -674,7 +680,7 @@ const s = Store.create({
674
680
  })
675
681
  ```
676
682
 
677
- #### Reference validation: `isValidReference`, `tryReference`, `onInvalidate` hook and `types.safeReference`
683
+ #### Reference validation: `isValidReference`, `tryReference`, `onInvalidated` hook and `types.safeReference`
678
684
 
679
685
  Accessing an invalid reference (a reference to a dead/detached node) triggers an exception.
680
686
 
@@ -722,7 +728,10 @@ A default implementation of such `onInvalidated` hook is provided by the `types.
722
728
  - If its parent is an array: Remove itself from the array
723
729
  - If its parent is a map: Remove itself from the map
724
730
 
725
- Strictly speaking it is implemented as
731
+ In addition to the options possible for a plain reference type, the optional options parameter object also accepts a parameter named `acceptsUndefined`, which is set to true by default, so it is suitable for model properties.
732
+ When used inside collections (arrays/maps) it is recommended to set this option to false so it can't take undefined as value, which is usually the desired in those cases.
733
+
734
+ Strictly speaking, `safeReference` with `acceptsUndefined` set to true (the default) is implemented as
726
735
 
727
736
  ```js
728
737
  types.maybe(
@@ -735,15 +744,28 @@ types.maybe(
735
744
  )
736
745
  ```
737
746
 
747
+ and with `acceptsUndefined` set to false as
748
+
749
+ ```js
750
+ types.reference(Type, {
751
+ ...customGetSetIfAvailable,
752
+ onInvalidated(ev) {
753
+ ev.removeRef()
754
+ }
755
+ })
756
+ ```
757
+
738
758
  ```js
739
759
  const Todo = types.model({ id: types.identifier })
740
760
  const Store = types.model({
741
761
  todos: types.array(Todo),
742
- selectedTodo: types.safeReference(Todo)
762
+ selectedTodo: types.safeReference(Todo),
763
+ multipleSelectedTodos: types.array(types.safeReference(Todo, { acceptsUndefined: false }))
743
764
  })
744
765
 
745
766
  // given selectedTodo points to a valid Todo and that Todo is later removed from the todos
746
- // array, then selectedTodo will automatically become undefined
767
+ // array, then selectedTodo will automatically become undefined, and if it is included in multipleSelectedTodos
768
+ // then it will be removed from the array
747
769
  ```
748
770
 
749
771
  ### Listening to observables, snapshots, patches or actions
@@ -930,7 +952,7 @@ const Todo = types
930
952
 
931
953
  The object that is returned from the `volatile` initializer function can contain any piece of data and will result in an instance property with the same name. Volatile properties have the following characteristics:
932
954
 
933
- 1. The can be read from outside the model (if you want hidden volatile state, keep the state in your closure as shown in the previous section, and _only_ if it is not used on a view consider not making it observable)
955
+ 1. They can be read from outside the model (if you want hidden volatile state, keep the state in your closure as shown in the previous section, and _only_ if it is not used on a view consider not making it observable)
934
956
  2. The volatile properties will be only observable, see [observable _references_](https://mobx.js.org/refguide/modifiers.html). Values assigned to them will be unmodified and not automatically converted to deep observable structures.
935
957
  3. Like normal properties, they can only be modified through actions
936
958
  4. Volatile props will not show up in snapshots, and cannot be updated by applying snapshots
@@ -1012,7 +1034,7 @@ Note that since MST v3 `types.array` and `types.map` are wrapped in `types.optio
1012
1034
  ## Utility types
1013
1035
 
1014
1036
  - `types.union(options?: { dispatcher?: (snapshot) => Type, eager?: boolean }, types...)` create a union of multiple types. If the correct type cannot be inferred unambiguously from a snapshot, provide a dispatcher function to determine the type. When `eager` flag is set to `true` (default) - the first matching type will be used, if set to `false` the type check will pass only if exactly 1 type matches.
1015
- - `types.optional(type, defaultValue, optionalValues?)` marks an value as being optional (in e.g. a model). If a value is not provided/`undefined` (or set to any of the primitive values passed as an optional `optionalValues` array) the `defaultValue` will be used instead. If `defaultValue` is a function, it will be evaluated. This can be used to generate, for example, IDs or timestamps upon creation.
1037
+ - `types.optional(type, defaultValue, optionalValues?)` marks a value as being optional (in e.g. a model). If a value is not provided/`undefined` (or set to any of the primitive values passed as an optional `optionalValues` array) the `defaultValue` will be used instead. If `defaultValue` is a function, it will be evaluated. This can be used to generate, for example, IDs or timestamps upon creation.
1016
1038
  - `types.literal(value)` can be used to create a literal type, where the only possible value is specifically that value. This is very powerful in combination with `union`s. E.g. `temperature: types.union(types.literal("hot"), types.literal("cold"))`.
1017
1039
  - `types.enumeration(name?, options: string[])` creates an enumeration. This method is a shorthand for a union of string literals. If you are using typescript and want to create a type based on an string enum (e.g. `enum Color { ... }`) then use `types.enumeration<Color>("Color", Object.values(Color))`, where the `"Color"` name argument is optional.
1018
1040
  - `types.refinement(name?, baseType, (snapshot) => boolean)` creates a type that is more specific than the base type, e.g. `types.refinement(types.string, value => value.length > 5)` to create a type of strings that can only be longer then 5.
@@ -1105,6 +1127,21 @@ Note, except for `preProcessSnapshot` and `postProcessSnapshot`, all hooks shoul
1105
1127
 
1106
1128
  All hooks can be defined multiple times and can be composed automatically.
1107
1129
 
1130
+ ## LifeCycle hooks for `types.array`/`types.map`
1131
+
1132
+ Hooks for `types.array`/`types.map` can be defined by using the `.hooks(self => ({}))` method.
1133
+
1134
+ Calling `.hooks(...)` produces new type, same as calling `.actions()` for `types.model`.
1135
+
1136
+ Available hooks are:
1137
+
1138
+ | Hook | Meaning |
1139
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1140
+ | `afterCreate` | Immediately after an instance is initialized: right after `.create()` for root node or after the first access for the nested one. Children will fire this event before parents. You can't make assumptions about the parent safely, use `afterAttach` if you need to. |
1141
+ | `afterAttach` | As soon as the _direct_ parent is assigned (this node is attached to another node). If an element is created as part of a parent, `afterAttach` is also fired. Unlike `afterCreate`, `afterAttach` will fire breadth first. So, in `afterAttach` one can safely make assumptions about the parent, but in `afterCreate` not |
1142
+ | `beforeDetach` | As soon as the node is removed from the _direct_ parent, but only if the node is _not_ destroyed. In other words, when `detach(node)` is used |
1143
+ | `beforeDestroy` | Called before the node is destroyed, as a result of calling `destroy`, or by removing or replacing the node from the tree. Child destructors will fire before parents |
1144
+
1108
1145
  # Api overview
1109
1146
 
1110
1147
  See the [full API docs](docs/API/README.md) for more details.
@@ -1119,7 +1156,8 @@ See the [full API docs](docs/API/README.md) for more details.
1119
1156
  | [`cast(nodeOrSnapshot)`](docs/API/README.md#cast) | Cast a node instance or snapshot to a node instance so it can be used in assignment operations |
1120
1157
  | [`castToSnapshot(nodeOrSnapshot)`](docs/API/README.md#casttosnapshot) | Cast a node instance to a snapshot so it can be used inside create operations |
1121
1158
  | [`castToReferenceSnapshot(node)`](docs/API/README.md#casttoreferencesnapshot) | Cast a node instance to a reference snapshot so it can be used inside create operations |
1122
- | [`createActionTrackingMiddleware`](docs/API/README.md#createactiontrackingmiddleware) | Utility to make writing middleware that tracks async actions less cumbersome |
1159
+ | [`createActionTrackingMiddleware`](docs/API/README.md#createactiontrackingmiddleware) | Utility to make writing middleware that tracks async actions less cumbersome. Consider migrating to `createActionTrackingMiddleware2` |
1160
+ | [`createActionTrackingMiddleware2`](docs/API/README.md#createactiontrackingmiddleware) | Utility to make writing middleware that tracks async actions less cumbersome |
1123
1161
  | [`clone(node, keepEnvironment?: true \| false \| newEnvironment)`](docs/API/README.md#clone) | Creates a full clone of the given node. By default preserves the same environment |
1124
1162
  | [`decorate(handler, function)`](docs/API/README.md#decorate) | Attaches middleware to a specific action (or flow) |
1125
1163
  | [`destroy(node)`](docs/API/README.md#destroy) | Kills `node`, making it unusable. Removes it from any parent in the process |
@@ -1161,9 +1199,9 @@ See the [full API docs](docs/API/README.md) for more details.
1161
1199
  | [`setLivelinessChecking("warn" \| "ignore" \| "error")`](docs/API/README.md#setlivelinesschecking) | Defines what MST should do when running into reads / writes to objects that have died. By default it will print a warning. Use te `"error"` option to easy debugging to see where the error was thrown and when the offending read / write took place |
1162
1200
  | [`getLivelinessChecking()`](docs/API/README.md#getlivelinesschecking) | Returns the current liveliness checking mode. |
1163
1201
  | [`splitJsonPath(path)`](docs/API/README.md#splitjsonpath) | Splits and unescapes the given JSON `path` into path parts |
1164
- | [`typecheck(type, value)`](docs/API/README.md#typecheck) | Typechecks a value against a type. Throws on errors. Use this if you need typechecks even in a production build. |
1202
+ | [`typecheck(type, value)`](docs/API/README.md#typecheck) | Typechecks a value against a type. Throws on errors. Use this if you need typechecks even in a production build. NOTE: set process.env.ENABLE_TYPE_CHECK = "true" if you want to enable type checking in any environment |
1165
1203
  | [`tryResolve(node, path)`](docs/API/README.md#tryresolve) | Like `resolve`, but just returns `null` if resolving fails at any point in the path |
1166
- | [`tryReference(() => node | null | undefined, checkIfAlive = true)`](docs/API/README.md#tryreference) | Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if it the check passes, else it returns undefined. |
1204
+ | [`tryReference(() => node \| null \| undefined, checkIfAlive = true)`](docs/API/README.md#tryreference) | Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if it the check passes, else it returns undefined. |
1167
1205
  | [`unprotect(node)`](docs/API/README.md#unprotect) | Unprotects `node`, making it possible to directly modify any value in the subtree, without actions |
1168
1206
  | [`walk(startNode, (node) => void)`](docs/API/README.md#walk) | Performs a depth-first walk through a tree |
1169
1207
  | [`escapeJsonPath(path)`](docs/API/README.md#escapejsonpath) | escape special characters in an identifier, according to http://tools.ietf.org/html/rfc6901 |
@@ -1181,6 +1219,9 @@ See the [full API docs](docs/API/README.md) for more details.
1181
1219
  | [`isReferenceType(value)`](docs/API/README.md#isReferenceType) | Returns if a given value represents a reference type. |
1182
1220
  | [`isRefinementType(value)`](docs/API/README.md#isRefinementType) | Returns if a given value represents a refinement type. |
1183
1221
  | [`isUnionType(value)`](docs/API/README.md#isUnionType) | Returns if a given value represents a union type. |
1222
+ | [`getRunningActionContext()`](docs/API/README.md#getrunningactioncontext) | Returns the currently executing MST action context, or undefined if none. |
1223
+ | [`isActionContextChildOf(actionContext, parent)`](docs/API/README.md#isActionContextChildOf) | Returns if the given action context is a parent of this action context. |
1224
+ | [`isActionContextThisOrChildOf(actionContext, parentOrSame)`](docs/API/README.md#isActionContextThisOrChildOf) | Returns if the given action context is this or a parent of this action context. |
1184
1225
 
1185
1226
  A _disposer_ is a function that cancels the effect for which it was created.
1186
1227
 
@@ -1337,7 +1378,7 @@ MST doesn't offer an any type because it can't reason about it. For example, giv
1337
1378
  - If no identifier is specified, but the type of the snapshot is correct, MST will reconcile objects as well if they are stored in a specific model property or under the same map key.
1338
1379
  - In arrays, items without an identifier are never reconciled.
1339
1380
 
1340
- If an object is reconciled, the consequence is that localState is preserved and `postCreate` / `attach` life-cycle hooks are not fired because applying a snapshot results just in an existing tree node being updated.
1381
+ If an object is reconciled, the consequence is that localState is preserved and `afterCreate` / `attach` life-cycle hooks are not fired because applying a snapshot results just in an existing tree node being updated.
1341
1382
 
1342
1383
  ### Creating async flows
1343
1384
 
@@ -1364,9 +1405,30 @@ Yes, with MST it is pretty straight forward to setup hot reloading for your stor
1364
1405
  ### TypeScript and MST
1365
1406
 
1366
1407
  TypeScript support is best-effort as not all patterns can be expressed in TypeScript. Except for assigning snapshots to properties we get pretty close! As MST uses the latest fancy TypeScript features it is required to use TypeScript 3.0 or later with `noImplicitThis` and `strictNullChecks` enabled.
1367
- Actually, the more strict options that are enabled, the better the type system will behave.
1408
+ Actually, the more strict options that are enabled, the better the type system will behave.
1368
1409
 
1369
- We recommend using TypeScript together with MST, but since the type system of MST is more dynamic than the TypeScript system, there are cases that cannot be expressed neatly and occasionally you will need to fallback to `any` or manually adding type annotations.
1410
+ #### Recommend compiler flags
1411
+
1412
+ The recommended compiler flags (against which all our tests are written) are:
1413
+
1414
+ ```json
1415
+ {
1416
+ "strictNullChecks": true,
1417
+ "strictFunctionTypes": true,
1418
+ "noImplicitAny": true,
1419
+ "noImplicitReturns": true,
1420
+ "noImplicitThis": true
1421
+ }
1422
+ ```
1423
+
1424
+ Or shorter by leveraging `strict`:
1425
+
1426
+ ```json
1427
+ {
1428
+ "strict": true,
1429
+ "noImplicitReturns": true
1430
+ }
1431
+ ```
1370
1432
 
1371
1433
  Flow is not supported.
1372
1434
 
@@ -1404,7 +1466,8 @@ type ITodoSnapshotOut = SnapshotOut<typeof Todo> // => { title: string }
1404
1466
  ```
1405
1467
 
1406
1468
  Due to the way typeof operator works, when working with big and deep models trees, it might make your IDE/ts server takes a lot of CPU time and freeze vscode (or others).
1407
- A partial solution for this is to turn the types into interfaces.
1469
+ A solution for this is to turn the types into interfaces.
1470
+ This way of defining types enables TypeScript to better cope with circular type definitions as well.
1408
1471
 
1409
1472
  ```ts
1410
1473
  interface ITodo extends Instance<typeof Todo> {}
@@ -1680,16 +1743,33 @@ So far this might look a lot like an immutable state tree as found for example i
1680
1743
 
1681
1744
  ## Contributing
1682
1745
 
1746
+ Extensive pull requests are best discussed in an issue first.
1747
+
1748
+ Setting up the environment:
1749
+
1683
1750
  1. Clone this repository
1684
- 2. Yarn is the package manager of choice. Make sure to run Node 8 or higher.
1685
- 3. Run `yarn install && yarn run bootstrap`.
1686
- 4. Run `yarn build` at least once in `packages/mobx-state-tree`
1687
- 5. For MST changes: go to `packages/mobx-state-tree` and run `yarn watch` (the test runner is Jest)
1688
- 6. Editor settings are optimized for VS Code, so just run `code .` in the root folder. Debugger settings are included in the project.
1689
- 7. After updating jsdocs, best run `yarn build-docs`
1690
- 8. When creating PRs, make sure to check the travis build, it will run some tests which are by default not run locally
1691
- 9. Extensive pull requests are best discussed in an issue first
1692
- 10. Have fun!
1751
+ 2. `yarn` is the package manager of choice (with workspaces support enabled). Make sure to run Node 8 or higher.
1752
+ 3. Run `yarn install` on the root.
1753
+ 4. Editor settings are optimized for VS Code, so just run `code .` in the root folder. Debugger settings are included in the project.
1754
+
1755
+ For `mobx-state-tree`:
1756
+
1757
+ 1. Go to `packages/mobx-state-tree` and run `yarn jest` to ensure all tests pass.
1758
+ 2. After updating jsdocs, better run `yarn build-docs` in `packages/mobx-state-tree` to regenerate them.
1759
+
1760
+ For `mst-middlewares`:
1761
+
1762
+ 1. Go to `packages/mst-middlewares` and run `yarn jest` to ensure all tests pass.
1763
+ 2. If your changes depend on a change in `packages/mobx-state-tree` you will need to run `yarn buld` there first!
1764
+
1765
+ Once you think your PR is ready:
1766
+
1767
+ 1. Run on the root `yarn build` to ensure it all builds.
1768
+ 2. Run on the root `yarn test` to ensure all tests pass.
1769
+ 3. Create the PR on GitHub.
1770
+ 4. Check the CI build passes on the PR thread in GitHub.
1771
+
1772
+ Have fun!
1693
1773
 
1694
1774
  ## Thanks!
1695
1775
 
@@ -1,48 +1,50 @@
1
- import { IDisposer, IAnyStateTreeNode } from "../internal";
2
- export declare type IMiddlewareEventType = "action" | "flow_spawn" | "flow_resume" | "flow_resume_error" | "flow_return" | "flow_throw";
3
- export declare type IMiddlewareEvent = {
4
- type: IMiddlewareEventType;
5
- name: string;
6
- id: number;
7
- parentId: number;
8
- rootId: number;
9
- allParentIds: number[];
10
- context: IAnyStateTreeNode;
11
- tree: IAnyStateTreeNode;
12
- args: any[];
13
- };
14
- export declare type IMiddlewareHandler = (actionCall: IMiddlewareEvent, next: (actionCall: IMiddlewareEvent, callback?: (value: any) => any) => void, abort: (value: any) => void) => any;
15
- /**
16
- * Middleware can be used to intercept any action is invoked on the subtree where it is attached.
17
- * If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.
18
- *
19
- * For more details, see the [middleware docs](../middleware.md)
20
- *
21
- * @param target Node to apply the middleware to.
22
- * @param middleware Middleware to apply.
23
- * @returns A callable function to dispose the middleware.
24
- */
25
- export declare function addMiddleware(target: IAnyStateTreeNode, handler: IMiddlewareHandler, includeHooks?: boolean): IDisposer;
26
- /**
27
- * Binds middleware to a specific action.
28
- *
29
- * Example:
30
- * ```ts
31
- * type.actions(self => {
32
- * function takeA____() {
33
- * self.toilet.donate()
34
- * self.wipe()
35
- * self.wipe()
36
- * self.toilet.flush()
37
- * }
38
- * return {
39
- * takeA____: decorate(atomic, takeA____)
40
- * }
41
- * })
42
- * ```
43
- *
44
- * @param handler
45
- * @param fn
46
- * @returns The original function
47
- */
48
- export declare function decorate<T extends Function>(handler: IMiddlewareHandler, fn: T): T;
1
+ import { IDisposer, IAnyStateTreeNode, IActionContext } from "../internal";
2
+ export declare type IMiddlewareEventType = "action" | "flow_spawn" | "flow_resume" | "flow_resume_error" | "flow_return" | "flow_throw";
3
+ export interface IMiddlewareEvent extends IActionContext {
4
+ /** Event type */
5
+ readonly type: IMiddlewareEventType;
6
+ /** Parent event unique id */
7
+ readonly parentId: number;
8
+ /** Parent event object */
9
+ readonly parentEvent: IMiddlewareEvent | undefined;
10
+ /** Root event unique id */
11
+ readonly rootId: number;
12
+ /** Id of all events, from root until current (excluding current) */
13
+ readonly allParentIds: number[];
14
+ }
15
+ export declare type IMiddlewareHandler = (actionCall: IMiddlewareEvent, next: (actionCall: IMiddlewareEvent, callback?: (value: any) => any) => void, abort: (value: any) => void) => any;
16
+ /**
17
+ * Middleware can be used to intercept any action is invoked on the subtree where it is attached.
18
+ * If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.
19
+ *
20
+ * For more details, see the [middleware docs](../middleware.md)
21
+ *
22
+ * @param target Node to apply the middleware to.
23
+ * @param middleware Middleware to apply.
24
+ * @returns A callable function to dispose the middleware.
25
+ */
26
+ export declare function addMiddleware(target: IAnyStateTreeNode, handler: IMiddlewareHandler, includeHooks?: boolean): IDisposer;
27
+ /**
28
+ * Binds middleware to a specific action.
29
+ *
30
+ * Example:
31
+ * ```ts
32
+ * type.actions(self => {
33
+ * function takeA____() {
34
+ * self.toilet.donate()
35
+ * self.wipe()
36
+ * self.wipe()
37
+ * self.toilet.flush()
38
+ * }
39
+ * return {
40
+ * takeA____: decorate(atomic, takeA____)
41
+ * }
42
+ * })
43
+ * ```
44
+ *
45
+ * @param handler
46
+ * @param fn
47
+ * @param includeHooks
48
+ * @returns The original function
49
+ */
50
+ export declare function decorate<T extends Function>(handler: IMiddlewareHandler, fn: T, includeHooks?: boolean): T;
@@ -0,0 +1,27 @@
1
+ import { IAnyStateTreeNode, IMiddlewareEvent } from "../internal";
2
+ export interface IActionContext {
3
+ /** Event name (action name for actions) */
4
+ readonly name: string;
5
+ /** Event unique id */
6
+ readonly id: number;
7
+ /** Parent action event object */
8
+ readonly parentActionEvent: IMiddlewareEvent | undefined;
9
+ /** Event context (node where the action was invoked) */
10
+ readonly context: IAnyStateTreeNode;
11
+ /** Event tree (root node of the node where the action was invoked) */
12
+ readonly tree: IAnyStateTreeNode;
13
+ /** Event arguments in an array (action arguments for actions) */
14
+ readonly args: any[];
15
+ }
16
+ /**
17
+ * Returns the currently executing MST action context, or undefined if none.
18
+ */
19
+ export declare function getRunningActionContext(): IActionContext | undefined;
20
+ /**
21
+ * Returns if the given action context is a parent of this action context.
22
+ */
23
+ export declare function isActionContextChildOf(actionContext: IActionContext, parent: number | IActionContext | IMiddlewareEvent): boolean;
24
+ /**
25
+ * Returns if the given action context is this or a parent of this action context.
26
+ */
27
+ export declare function isActionContextThisOrChildOf(actionContext: IActionContext, parentOrThis: number | IActionContext | IMiddlewareEvent): boolean;
@@ -1,30 +1,14 @@
1
- /** @hidden */
2
- declare const $flowYield: unique symbol;
3
- /** @hidden */
4
- export interface FlowYield {
5
- [$flowYield]: undefined;
6
- }
7
- /** @hidden */
8
- declare const $flowReturn: unique symbol;
9
- /** @hidden */
10
- export interface FlowReturn<T> {
11
- [$flowReturn]: T;
12
- }
13
- /** @hidden */
14
- export declare type FlowReturnType<R> = IfAllAreFlowYieldThenVoid<R extends FlowReturn<infer FR> ? FR extends Promise<infer FRP> ? FRP : FR : R extends Promise<any> ? FlowYield : R>;
15
- /** @hidden */
16
- export declare type IfAllAreFlowYieldThenVoid<R> = Exclude<R, FlowYield> extends never ? void : Exclude<R, FlowYield>;
17
- /**
18
- * See [asynchronous actions](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md).
19
- *
20
- * @returns The flow as a promise.
21
- */
22
- export declare function flow<R, Args extends any[]>(generator: (...args: Args) => IterableIterator<R>): (...args: Args) => Promise<FlowReturnType<R>>;
23
- /**
24
- * Used for TypeScript to make flows that return a promise return the actual promise result.
25
- *
26
- * @param val
27
- * @returns
28
- */
29
- export declare function castFlowReturn<T>(val: T): FlowReturn<T>;
30
- export {};
1
+ /**
2
+ * See [asynchronous actions](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md).
3
+ *
4
+ * @returns The flow as a promise.
5
+ */
6
+ export declare function flow<R, Args extends any[]>(generator: (...args: Args) => Generator<any, R, any>): (...args: Args) => Promise<R>;
7
+ /**
8
+ * @deprecated Not needed since TS3.6.
9
+ * Used for TypeScript to make flows that return a promise return the actual promise result.
10
+ *
11
+ * @param val
12
+ * @returns
13
+ */
14
+ export declare function castFlowReturn<T>(val: T): T;
@@ -1,36 +1,36 @@
1
- /**
2
- * https://tools.ietf.org/html/rfc6902
3
- * http://jsonpatch.com/
4
- */
5
- export interface IJsonPatch {
6
- op: "replace" | "add" | "remove";
7
- path: string;
8
- value?: any;
9
- }
10
- export interface IReversibleJsonPatch extends IJsonPatch {
11
- oldValue: any;
12
- }
13
- /**
14
- * Escape slashes and backslashes.
15
- *
16
- * http://tools.ietf.org/html/rfc6901
17
- */
18
- export declare function escapeJsonPath(path: string): string;
19
- /**
20
- * Unescape slashes and backslashes.
21
- */
22
- export declare function unescapeJsonPath(path: string): string;
23
- /**
24
- * Generates a json-path compliant json path from path parts.
25
- *
26
- * @param path
27
- * @returns
28
- */
29
- export declare function joinJsonPath(path: string[]): string;
30
- /**
31
- * Splits and decodes a json path into several parts.
32
- *
33
- * @param path
34
- * @returns
35
- */
36
- export declare function splitJsonPath(path: string): string[];
1
+ /**
2
+ * https://tools.ietf.org/html/rfc6902
3
+ * http://jsonpatch.com/
4
+ */
5
+ export interface IJsonPatch {
6
+ readonly op: "replace" | "add" | "remove";
7
+ readonly path: string;
8
+ readonly value?: any;
9
+ }
10
+ export interface IReversibleJsonPatch extends IJsonPatch {
11
+ readonly oldValue: any;
12
+ }
13
+ /**
14
+ * Escape slashes and backslashes.
15
+ *
16
+ * http://tools.ietf.org/html/rfc6901
17
+ */
18
+ export declare function escapeJsonPath(path: string): string;
19
+ /**
20
+ * Unescape slashes and backslashes.
21
+ */
22
+ export declare function unescapeJsonPath(path: string): string;
23
+ /**
24
+ * Generates a json-path compliant json path from path parts.
25
+ *
26
+ * @param path
27
+ * @returns
28
+ */
29
+ export declare function joinJsonPath(path: string[]): string;
30
+ /**
31
+ * Splits and decodes a json path into several parts.
32
+ *
33
+ * @param path
34
+ * @returns
35
+ */
36
+ export declare function splitJsonPath(path: string): string[];