@olovyannikov/effector-models 0.1.2 → 0.2.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,84 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ A second review of the rewritten core.
6
+
7
+ ### Fixed
8
+
9
+ - **Trees and self-references.** A model's reaction to its own fact (the
10
+ cascade of a tree, a `ref` to itself) is applied inside the same write.
11
+ Before, it ran after the commands already launched in the same tick, so
12
+ `clear` followed by `create` of the same tree deleted the new nodes.
13
+ - Writing a previously seen state object back into `$state` (restoring a
14
+ snapshot) no longer re-emits its old `deleted` / `renamed` / `missed`.
15
+ - The id or alias `'__proto__'` is stored as an ordinary key. It used to
16
+ change the prototype of the dictionary and leave `ids` and `instances`
17
+ out of sync.
18
+ - `ref` to a `union`: renaming a target keeps the other fields of the
19
+ reference (`{ kind, id, seat }` used to become `{ kind, id }`).
20
+
21
+ ### Changed
22
+
23
+ - Deleting a branch of a tree emits one `deleted` fact with every deleted id
24
+ instead of one fact per level.
25
+
26
+ ### Known limitation
27
+
28
+ - A relation between two models still reacts after the commands already
29
+ launched in the same tick. See
30
+ [Relations](https://olovyannikov.github.io/effector-kit/guide/keyed-models#relations).
31
+
32
+ ## 0.2.0
33
+
34
+ A review of the core found that writes could be lost or reordered. The model
35
+ is rebuilt on one store with reducers, which changes how it is seeded and
36
+ serialized.
37
+
38
+ ### Breaking
39
+
40
+ - **One writable store per model, `$state`**: `{ ids, instances, aliases }`
41
+ under the sid `effector-models:<name>`. `$instances`, `$ids` and `$aliases`
42
+ are derived from it and are no longer writable. The separate
43
+ `effector-models:<name>:aliases` sid is gone.
44
+ - Seed with `fork({ values: [[Model.$state, modelState({ ... })]] })`
45
+ instead of `[[Model.$instances, { ... }]]`.
46
+ - Serialized state has the new shape; state serialized by 0.1.x does not
47
+ hydrate.
48
+ - `clear` reports the deleted ids and aliases in `deleted`.
49
+ - `ref` requires a single-reference field to accept `null`
50
+ (`string | null`): that is what a deleted target is replaced with.
51
+ - `ModelLike` requires `$ids` and the internal `~link`.
52
+
53
+ ### Fixed
54
+
55
+ - **Lost writes.** Commands launched one after another in the same tick —
56
+ `target: [a, b]`, two prepends of one event — were coalesced: only the last
57
+ payload of an instance event survived, and `rename` → `update` or
58
+ `delete` → `create` ran in the wrong order. Every write is a reducer of
59
+ `$state` now and is applied in order.
60
+ - **Lost facts in relations.** When `deleted` or `renamed` fired twice in one
61
+ tick, `child` and `ref` saw only the last one: a tree with a `ref` to
62
+ itself kept links to a deleted root, a tree with a second `child` kept the
63
+ orphans, `union.delete` with mixed kinds cleaned only the last kind.
64
+ - **Order of ids.** `$ids` and `$idsByParent` follow creation order also for
65
+ ids that look like numbers (`'10'` before `'2'`), and `rename` keeps the
66
+ instance in its place instead of moving it to the end.
67
+ - Ids equal to `Object.prototype` property names (`'constructor'`,
68
+ `'toString'`) were treated as existing instances by `update`, `upsert` and
69
+ the hooks.
70
+ - `useChildren` and `useModel` threw when a request switched from a selector
71
+ that returned `null` to plain children.
72
+ - `clear` on an empty model no longer marks the store as changed; `$ids` no
73
+ longer updates when only a field of an instance changes.
74
+ - A reducer with an optional payload (`(state, by?: number) => ...`) no
75
+ longer requires `payload` in the event params and in the bound event.
76
+
77
+ ### Added
78
+
79
+ - `modelState(instances, aliases?)` — the value of `$state` for seeding.
80
+ - `ModelState` and `ModelLink` types.
81
+
3
82
  ## 0.1.2
4
83
 
5
84
  ### Added
package/README.md CHANGED
@@ -10,7 +10,7 @@ Fork of [`@effector-kit/models`](https://github.com/movpushmov/effector-kit) by
10
10
  | Instance data | mutated in place, `$instances` keeps its reference | immutable; untouched instances keep their reference |
11
11
  | `map` / `combine` / `useStoreMap` over `$instances` | miss writes | just work |
12
12
  | Runtime | global context, writes into `scope.reg` | public Effector API only |
13
- | `fork({ values })` / `serialize` | `$instances` read-only in types, instance stores `serialize: 'ignore'` | one `$instances` store with sid `effector-models:<name>` |
13
+ | `fork({ values })` / `serialize` | `$instances` read-only in types, instance stores `serialize: 'ignore'` | one `$state` store with sid `effector-models:<name>` |
14
14
  | Contract defaults on `create` | not applied | applied |
15
15
  | `create` over existing id | silently replaces | `create` replaces, `upsert` merges |
16
16
  | Write to missing instance | silent `Promise.reject` | ignored and reported via `missed` |
@@ -42,7 +42,7 @@ interface Document {
42
42
  const defaults: Document = { documentId: null, pending: null, failed: false };
43
43
 
44
44
  export const DocumentModel = model({
45
- name: 'document', // unique: sid of $instances is `effector-models:document`
45
+ name: 'document', // unique: sid of the state is `effector-models:document`
46
46
  defaults,
47
47
  events: {
48
48
  patched: (doc, patch: Patch) => ({
@@ -61,14 +61,15 @@ A reducer returning the same object means "nothing changed": no store update, no
61
61
 
62
62
  | Unit | Payload | Behaviour |
63
63
  | --------------- | -------------------------------------------------- | --------------------------------------------------------------------------------- |
64
- | `$instances` | — | `Record<id, State>`, writable, has sid |
65
- | `$ids` | — | `string[]` |
64
+ | `$state` | — | `{ ids, instances, aliases }`: the single writable store, has a sid |
65
+ | `$instances` | — | `Record<id, State>`, derived from `$state` |
66
+ | `$ids` | — | `string[]` in creation order; updates only when the set or the order changes |
66
67
  | `create` | `{ id, data? }` or array | creates with defaults; replaces existing id |
67
68
  | `upsert` | `{ id, data? }` or array | merges into existing or creates with defaults |
68
69
  | `update` | `{ id, data: Partial<State> \| (state) => State }` | existing only |
69
70
  | `delete` | `id` or `id[]` | |
70
71
  | `rename` | `{ from, to }` | moves instance in one step (e.g. draft → created document) |
71
- | `clear` | — | |
72
+ | `clear` | — | deletes everything; the ids are reported in `deleted` |
72
73
  | `events.<name>` | `{ id \| id[], payload }` | applies reducer synchronously |
73
74
  | `missed` | `{ action, ids }` | writes addressed to instances that do not exist |
74
75
  | `deleted` | `string[]` | fact: real ids of deleted instances, then their aliases |
@@ -93,12 +94,14 @@ sample({
93
94
  });
94
95
  ```
95
96
 
96
- Tests seed instances like any store: `fork({ values: [[DocumentModel.$instances, { a: { ... } }]] })`.
97
+ Tests seed a model like any store: `fork({ values: [[DocumentModel.$state, modelState({ a: { ... } })]] })`.
97
98
 
98
99
  ## Relations
99
100
 
100
101
  Relations connect models without changing what an instance is: a reference is an ordinary field with an id, and a relation only keeps those fields consistent.
101
102
 
103
+ A relation inside one model — a tree, a reference to itself — is applied as part of the same write. A relation between two models reacts to the fact of the other model, so it runs after the commands already launched in the same tick. This matters only when one `sample` deletes an instance and re-creates it with new children or references through `target: [...]`: the reaction to the delete would reach the new data. Launch such commands from separate `sample`s.
104
+
102
105
  ### `child` — owned instances
103
106
 
104
107
  Children store the id of their parent in a field and are deleted together with it.
@@ -188,7 +191,7 @@ and follow the life of instances.
188
191
 
189
192
  ```ts
190
193
  Chats.alias({ alias: 'route-id', id: 'server-id' });
191
- Chats.$aliases; // Store<Record<alias, id>>, has a sid
194
+ Chats.$aliases; // Store<Record<alias, id>>
192
195
 
193
196
  // Everything that takes an id takes an alias.
194
197
  Chats.events.renamed({ id: 'route-id', payload: 'New title' });
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_model = require("./model-iPgSwajA.cjs");
2
+ const require_model = require("./model-Ds45KAy9.cjs");
3
3
  let effector = require("effector");
4
4
  // lib/aliases.ts
5
5
  /**
@@ -30,24 +30,28 @@ let effector = require("effector");
30
30
  id,
31
31
  data
32
32
  });
33
+ const refsOf = (refs, kind) => (Array.isArray(refs) ? refs : [refs]).filter((item) => item.kind === kind).map((item) => item.id);
33
34
  for (const [kind, member] of Object.entries(models)) {
34
- (0, effector.sample)({
35
- clock: create,
36
- filter: (params) => paramsOf(params, kind).length > 0,
37
- fn: (params) => paramsOf(params, kind),
38
- target: member.create
35
+ member["~link"](create, {
36
+ to: "create",
37
+ fn: (params) => {
38
+ const own = paramsOf(params, kind);
39
+ return own.length > 0 ? own : void 0;
40
+ }
39
41
  });
40
- (0, effector.sample)({
41
- clock: upsert,
42
- filter: (params) => paramsOf(params, kind).length > 0,
43
- fn: (params) => paramsOf(params, kind),
44
- target: member.upsert
42
+ member["~link"](upsert, {
43
+ to: "upsert",
44
+ fn: (params) => {
45
+ const own = paramsOf(params, kind);
46
+ return own.length > 0 ? own : void 0;
47
+ }
45
48
  });
46
- (0, effector.sample)({
47
- clock: remove,
48
- filter: (refs) => (Array.isArray(refs) ? refs : [refs]).some((ref) => ref.kind === kind),
49
- fn: (refs) => (Array.isArray(refs) ? refs : [refs]).filter((ref) => ref.kind === kind).map((ref) => ref.id),
50
- target: member.delete
49
+ member["~link"](remove, {
50
+ to: "delete",
51
+ fn: (refs) => {
52
+ const own = refsOf(refs, kind);
53
+ return own.length > 0 ? own : void 0;
54
+ }
51
55
  });
52
56
  }
53
57
  return {
@@ -69,55 +73,39 @@ function isUnion(value) {
69
73
  */ function child(config) {
70
74
  const { parent, model, key } = config;
71
75
  const parentOf = (state) => state[key];
72
- const $idsByParent = (0, effector.combine)(model.$instances, parent.$aliases, (instances, aliases) => {
76
+ const $idsByParent = (0, effector.combine)(model.$ids, model.$instances, parent.$aliases, (ids, instances, aliases) => {
73
77
  const index = {};
74
- for (const [id, state] of Object.entries(instances)) {
75
- const parentId = parentOf(state);
76
- if (typeof parentId === "string") (index[require_model.resolveAlias(aliases, parentId)] ??= []).push(id);
78
+ for (const id of ids) {
79
+ const state = instances[id];
80
+ const parentId = state === void 0 ? void 0 : parentOf(state);
81
+ if (typeof parentId === "string") {
82
+ const real = require_model.resolveAlias(aliases, parentId);
83
+ if (!Object.hasOwn(index, real)) require_model.setOwn(index, real, []);
84
+ index[real].push(id);
85
+ }
77
86
  }
78
87
  return index;
79
88
  });
80
- const childrenOf = (instances, match) => Object.entries(instances).filter(([, state]) => {
81
- const parentId = parentOf(state);
82
- return typeof parentId === "string" && match(parentId);
83
- }).map(([id]) => id);
84
- const isTree = parent.$instances === model.$instances;
85
- const descendantsOf = (instances, ids) => {
86
- const found = /* @__PURE__ */ new Set();
87
- let level = new Set(ids);
88
- while (level.size > 0) {
89
- const next = /* @__PURE__ */ new Set();
90
- for (const id of childrenOf(instances, (parentId) => level.has(parentId))) if (!found.has(id)) {
91
- found.add(id);
92
- next.add(id);
93
- }
94
- level = isTree ? next : /* @__PURE__ */ new Set();
89
+ model["~react"](parent, "deleted", {
90
+ to: "deleteWhere",
91
+ fn: (ids) => (state) => {
92
+ const parentId = parentOf(state);
93
+ return typeof parentId === "string" && ids.includes(parentId);
95
94
  }
96
- return [...found];
97
- };
98
- (0, effector.sample)({
99
- clock: parent.deleted,
100
- source: model.$instances,
101
- filter: (instances, ids) => descendantsOf(instances, ids).length > 0,
102
- fn: (instances, ids) => descendantsOf(instances, ids),
103
- target: model.delete
104
95
  });
105
- if (!isTree) (0, effector.sample)({
106
- clock: parent.clear,
107
- source: model.$instances,
108
- filter: (instances) => childrenOf(instances, () => true).length > 0,
109
- fn: (instances) => childrenOf(instances, () => true),
110
- target: model.delete
111
- });
112
- (0, effector.sample)({
113
- clock: parent.renamed,
114
- source: model.$instances,
115
- filter: (instances, { from }) => childrenOf(instances, (parentId) => parentId === from).length > 0,
116
- fn: (instances, { from, to }) => ({
117
- id: childrenOf(instances, (parentId) => parentId === from),
118
- data: { [key]: to }
119
- }),
120
- target: model.update
96
+ model["~react"](parent, "renamed", {
97
+ to: "patch",
98
+ fn: ({ from, to }) => (instances) => {
99
+ let next = instances;
100
+ for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from) {
101
+ if (next === instances) next = { ...instances };
102
+ require_model.setOwn(next, id, {
103
+ ...state,
104
+ [key]: to
105
+ });
106
+ }
107
+ return next;
108
+ }
121
109
  });
122
110
  return {
123
111
  model,
@@ -125,25 +113,20 @@ function isUnion(value) {
125
113
  $idsByParent
126
114
  };
127
115
  }
128
- function modelSignals(target, wrap, read) {
129
- return {
130
- removed: (0, effector.merge)([target.deleted.map((deleted) => (item) => {
131
- const id = read(item);
132
- return id !== void 0 && deleted.includes(id);
133
- }), target.clear.map(() => (item) => read(item) !== void 0)]),
134
- replaced: target.renamed.map(({ from, to }) => (item) => read(item) === from ? wrap(to) : item)
135
- };
136
- }
137
- function targetSignals(target) {
138
- if (!isUnion(target)) return modelSignals(target, (id) => id, (item) => typeof item === "string" ? item : void 0);
139
- const members = Object.entries(target.models).map(([kind, member]) => modelSignals(member, (id) => ({
140
- kind,
141
- id
142
- }), (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0));
143
- return {
144
- removed: (0, effector.merge)(members.map((member) => member.removed)),
145
- replaced: (0, effector.merge)(members.map((member) => member.replaced))
146
- };
116
+ function refTargets(target) {
117
+ if (!isUnion(target)) return [{
118
+ model: target,
119
+ read: (item) => typeof item === "string" ? item : void 0,
120
+ move: (_, to) => to
121
+ }];
122
+ return Object.entries(target.models).map(([kind, member]) => ({
123
+ model: member,
124
+ read: (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0,
125
+ move: (item, to) => ({
126
+ ...item,
127
+ id: to
128
+ })
129
+ }));
147
130
  }
148
131
  /**
149
132
  * Ссылка на экземпляры, которые живут в другой модели (или объединении).
@@ -151,7 +134,6 @@ function targetSignals(target) {
151
134
  * удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
152
135
  */ function ref(config) {
153
136
  const { from, field } = config;
154
- const signals = targetSignals(config.to);
155
137
  const rewrite = (instances, change) => {
156
138
  let next = instances;
157
139
  for (const [id, state] of Object.entries(instances)) {
@@ -159,39 +141,47 @@ function targetSignals(target) {
159
141
  const updated = change(current);
160
142
  if (updated !== current) {
161
143
  if (next === instances) next = { ...instances };
162
- next[id] = {
144
+ require_model.setOwn(next, id, {
163
145
  ...state,
164
146
  [field]: updated
165
- };
147
+ });
166
148
  }
167
149
  }
168
150
  return next;
169
151
  };
170
- (0, effector.sample)({
171
- clock: signals.removed,
172
- source: from.$instances,
173
- fn: (instances, isRemoved) => rewrite(instances, (value) => {
174
- if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
175
- return value !== null && isRemoved(value) ? null : value;
176
- }),
177
- target: from.$instances
178
- });
179
- (0, effector.sample)({
180
- clock: signals.replaced,
181
- source: from.$instances,
182
- fn: (instances, replace) => rewrite(instances, (value) => {
183
- if (Array.isArray(value)) {
184
- const replaced = value.map(replace);
185
- return replaced.some((item, index) => item !== value[index]) ? replaced : value;
152
+ for (const { model: target, read, move } of refTargets(config.to)) {
153
+ from["~react"](target, "deleted", {
154
+ to: "patch",
155
+ fn: (deleted) => (instances) => {
156
+ const isRemoved = (item) => {
157
+ const id = read(item);
158
+ return id !== void 0 && deleted.includes(id);
159
+ };
160
+ return rewrite(instances, (value) => {
161
+ if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
162
+ return value !== null && isRemoved(value) ? null : value;
163
+ });
186
164
  }
187
- return value === null ? value : replace(value);
188
- }),
189
- target: from.$instances
190
- });
165
+ });
166
+ from["~react"](target, "renamed", {
167
+ to: "patch",
168
+ fn: ({ from: before, to }) => (instances) => {
169
+ const replace = (item) => read(item) === before ? move(item, to) : item;
170
+ return rewrite(instances, (value) => {
171
+ if (Array.isArray(value)) {
172
+ const replaced = value.map(replace);
173
+ return replaced.some((item, index) => item !== value[index]) ? replaced : value;
174
+ }
175
+ return value === null ? value : replace(value);
176
+ });
177
+ }
178
+ });
179
+ }
191
180
  }
192
181
  exports.aliases = aliases;
193
182
  exports.child = child;
194
183
  exports.model = require_model.model;
184
+ exports.modelState = require_model.modelState;
195
185
  exports.ref = ref;
196
186
  exports.resolveAlias = require_model.resolveAlias;
197
187
  exports.union = union;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EventCallable, Store } from "effector";
2
- import { C as RenameParams, E as resolveAlias, S as Reducers, T as model, _ as Instances, a as Union, b as ModelConfig, c as UnionModels, d as ref, f as union, g as InstanceEventParams, h as Ids, i as RefConfig, l as UnionRef, m as CreateParams, n as ChildConfig, o as UnionCreateParams, p as AliasParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Missed, w as UpdateParams, x as Reducer, y as Model } from "./relations-DXJ6slzh.cjs";
2
+ import { C as Reducers, D as modelState, E as model, O as resolveAlias, S as Reducer, T as UpdateParams, _ as Instances, a as Union, b as ModelConfig, c as UnionModels, d as ref, f as union, g as InstanceEventParams, h as Ids, i as RefConfig, l as UnionRef, m as CreateParams, n as ChildConfig, o as UnionCreateParams, p as AliasParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Missed, w as RenameParams, x as ModelState, y as Model } from "./relations-NBj9Om01.cjs";
3
3
  /** Часть модели, нужная алиасам. */
4
4
  type AliasTarget = Pick<Model<object, Record<never, unknown>>, "$aliases" | "alias" | "unalias">;
5
5
  interface Aliases {
@@ -17,5 +17,5 @@ interface Aliases {
17
17
  * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.
18
18
  */
19
19
  export declare function aliases(model: AliasTarget): Aliases;
20
- export { type AliasParams, type AliasTarget, type Aliases, type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, ref, resolveAlias, union };
20
+ export { type AliasParams, type AliasTarget, type Aliases, type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type ModelState, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, modelState, ref, resolveAlias, union };
21
21
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EventCallable, Store } from "effector";
2
- import { C as RenameParams, E as resolveAlias, S as Reducers, T as model, _ as Instances, a as Union, b as ModelConfig, c as UnionModels, d as ref, f as union, g as InstanceEventParams, h as Ids, i as RefConfig, l as UnionRef, m as CreateParams, n as ChildConfig, o as UnionCreateParams, p as AliasParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Missed, w as UpdateParams, x as Reducer, y as Model } from "./relations-Cc9Mv0m7.mjs";
2
+ import { C as Reducers, D as modelState, E as model, O as resolveAlias, S as Reducer, T as UpdateParams, _ as Instances, a as Union, b as ModelConfig, c as UnionModels, d as ref, f as union, g as InstanceEventParams, h as Ids, i as RefConfig, l as UnionRef, m as CreateParams, n as ChildConfig, o as UnionCreateParams, p as AliasParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Missed, w as RenameParams, x as ModelState, y as Model } from "./relations-BnHiRhRy.mjs";
3
3
  /** Часть модели, нужная алиасам. */
4
4
  type AliasTarget = Pick<Model<object, Record<never, unknown>>, "$aliases" | "alias" | "unalias">;
5
5
  interface Aliases {
@@ -17,5 +17,5 @@ interface Aliases {
17
17
  * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.
18
18
  */
19
19
  export declare function aliases(model: AliasTarget): Aliases;
20
- export { type AliasParams, type AliasTarget, type Aliases, type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, ref, resolveAlias, union };
20
+ export { type AliasParams, type AliasTarget, type Aliases, type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type ModelState, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, modelState, ref, resolveAlias, union };
21
21
  //# sourceMappingURL=index.d.mts.map