@olovyannikov/effector-models 0.2.0 → 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 +29 -0
- package/README.md +2 -0
- package/dist/index.cjs +53 -44
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +54 -45
- package/dist/index.mjs.map +1 -1
- package/dist/{model-BNsi5pxp.mjs → model-CLRG64G8.mjs} +108 -43
- package/dist/model-CLRG64G8.mjs.map +1 -0
- package/dist/{model-Cav66tnw.cjs → model-Ds45KAy9.cjs} +112 -41
- package/dist/react.cjs +1 -1
- package/dist/react.d.cts +1 -1
- package/dist/react.d.mts +1 -1
- package/dist/react.mjs +1 -1
- package/dist/{relations-CpExzbHu.d.mts → relations-BnHiRhRy.d.mts} +11 -2
- package/dist/relations-BnHiRhRy.d.mts.map +1 -0
- package/dist/{relations-pJXSBtRd.d.cts → relations-NBj9Om01.d.cts} +11 -2
- package/dist/relations-NBj9Om01.d.cts.map +1 -0
- package/package.json +1 -1
- package/dist/model-BNsi5pxp.mjs.map +0 -1
- package/dist/relations-CpExzbHu.d.mts.map +0 -1
- package/dist/relations-pJXSBtRd.d.cts.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
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
|
+
|
|
3
32
|
## 0.2.0
|
|
4
33
|
|
|
5
34
|
A review of the core found that writes could be lost or reordered. The model
|
package/README.md
CHANGED
|
@@ -100,6 +100,8 @@ Tests seed a model like any store: `fork({ values: [[DocumentModel.$state, model
|
|
|
100
100
|
|
|
101
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.
|
|
102
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
|
+
|
|
103
105
|
### `child` — owned instances
|
|
104
106
|
|
|
105
107
|
Children store the id of their parent in a field and are deleted together with it.
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_model = require("./model-
|
|
2
|
+
const require_model = require("./model-Ds45KAy9.cjs");
|
|
3
3
|
let effector = require("effector");
|
|
4
4
|
// lib/aliases.ts
|
|
5
5
|
/**
|
|
@@ -78,27 +78,31 @@ function isUnion(value) {
|
|
|
78
78
|
for (const id of ids) {
|
|
79
79
|
const state = instances[id];
|
|
80
80
|
const parentId = state === void 0 ? void 0 : parentOf(state);
|
|
81
|
-
if (typeof parentId === "string")
|
|
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
|
+
}
|
|
82
86
|
}
|
|
83
87
|
return index;
|
|
84
88
|
});
|
|
85
|
-
model["~
|
|
89
|
+
model["~react"](parent, "deleted", {
|
|
86
90
|
to: "deleteWhere",
|
|
87
91
|
fn: (ids) => (state) => {
|
|
88
92
|
const parentId = parentOf(state);
|
|
89
93
|
return typeof parentId === "string" && ids.includes(parentId);
|
|
90
94
|
}
|
|
91
95
|
});
|
|
92
|
-
model["~
|
|
96
|
+
model["~react"](parent, "renamed", {
|
|
93
97
|
to: "patch",
|
|
94
98
|
fn: ({ from, to }) => (instances) => {
|
|
95
99
|
let next = instances;
|
|
96
100
|
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from) {
|
|
97
101
|
if (next === instances) next = { ...instances };
|
|
98
|
-
next
|
|
102
|
+
require_model.setOwn(next, id, {
|
|
99
103
|
...state,
|
|
100
104
|
[key]: to
|
|
101
|
-
};
|
|
105
|
+
});
|
|
102
106
|
}
|
|
103
107
|
return next;
|
|
104
108
|
}
|
|
@@ -109,25 +113,20 @@ function isUnion(value) {
|
|
|
109
113
|
$idsByParent
|
|
110
114
|
};
|
|
111
115
|
}
|
|
112
|
-
function
|
|
113
|
-
return {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}), (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0));
|
|
127
|
-
return {
|
|
128
|
-
removed: (0, effector.merge)(members.map((member) => member.removed)),
|
|
129
|
-
replaced: (0, effector.merge)(members.map((member) => member.replaced))
|
|
130
|
-
};
|
|
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
|
+
}));
|
|
131
130
|
}
|
|
132
131
|
/**
|
|
133
132
|
* Ссылка на экземпляры, которые живут в другой модели (или объединении).
|
|
@@ -135,7 +134,6 @@ function targetSignals(target) {
|
|
|
135
134
|
* удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
|
|
136
135
|
*/ function ref(config) {
|
|
137
136
|
const { from, field } = config;
|
|
138
|
-
const signals = targetSignals(config.to);
|
|
139
137
|
const rewrite = (instances, change) => {
|
|
140
138
|
let next = instances;
|
|
141
139
|
for (const [id, state] of Object.entries(instances)) {
|
|
@@ -143,31 +141,42 @@ function targetSignals(target) {
|
|
|
143
141
|
const updated = change(current);
|
|
144
142
|
if (updated !== current) {
|
|
145
143
|
if (next === instances) next = { ...instances };
|
|
146
|
-
next
|
|
144
|
+
require_model.setOwn(next, id, {
|
|
147
145
|
...state,
|
|
148
146
|
[field]: updated
|
|
149
|
-
};
|
|
147
|
+
});
|
|
150
148
|
}
|
|
151
149
|
}
|
|
152
150
|
return next;
|
|
153
151
|
};
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
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
|
+
});
|
|
167
164
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
+
}
|
|
171
180
|
}
|
|
172
181
|
exports.aliases = aliases;
|
|
173
182
|
exports.child = child;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventCallable, Store } from "effector";
|
|
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-
|
|
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 {
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EventCallable, Store } from "effector";
|
|
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-
|
|
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 {
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as modelState, r as resolveAlias, t as model } from "./model-
|
|
2
|
-
import { combine, createEvent
|
|
1
|
+
import { i as setOwn, n as modelState, r as resolveAlias, t as model } from "./model-CLRG64G8.mjs";
|
|
2
|
+
import { combine, createEvent } from "effector";
|
|
3
3
|
// lib/aliases.ts
|
|
4
4
|
/**
|
|
5
5
|
* @deprecated Алиасы встроены в модель: `model.$aliases`, `model.alias`, `model.unalias`,
|
|
@@ -77,27 +77,31 @@ function isUnion(value) {
|
|
|
77
77
|
for (const id of ids) {
|
|
78
78
|
const state = instances[id];
|
|
79
79
|
const parentId = state === void 0 ? void 0 : parentOf(state);
|
|
80
|
-
if (typeof parentId === "string")
|
|
80
|
+
if (typeof parentId === "string") {
|
|
81
|
+
const real = resolveAlias(aliases, parentId);
|
|
82
|
+
if (!Object.hasOwn(index, real)) setOwn(index, real, []);
|
|
83
|
+
index[real].push(id);
|
|
84
|
+
}
|
|
81
85
|
}
|
|
82
86
|
return index;
|
|
83
87
|
});
|
|
84
|
-
model["~
|
|
88
|
+
model["~react"](parent, "deleted", {
|
|
85
89
|
to: "deleteWhere",
|
|
86
90
|
fn: (ids) => (state) => {
|
|
87
91
|
const parentId = parentOf(state);
|
|
88
92
|
return typeof parentId === "string" && ids.includes(parentId);
|
|
89
93
|
}
|
|
90
94
|
});
|
|
91
|
-
model["~
|
|
95
|
+
model["~react"](parent, "renamed", {
|
|
92
96
|
to: "patch",
|
|
93
97
|
fn: ({ from, to }) => (instances) => {
|
|
94
98
|
let next = instances;
|
|
95
99
|
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from) {
|
|
96
100
|
if (next === instances) next = { ...instances };
|
|
97
|
-
next
|
|
101
|
+
setOwn(next, id, {
|
|
98
102
|
...state,
|
|
99
103
|
[key]: to
|
|
100
|
-
};
|
|
104
|
+
});
|
|
101
105
|
}
|
|
102
106
|
return next;
|
|
103
107
|
}
|
|
@@ -108,25 +112,20 @@ function isUnion(value) {
|
|
|
108
112
|
$idsByParent
|
|
109
113
|
};
|
|
110
114
|
}
|
|
111
|
-
function
|
|
112
|
-
return {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}), (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0));
|
|
126
|
-
return {
|
|
127
|
-
removed: merge(members.map((member) => member.removed)),
|
|
128
|
-
replaced: merge(members.map((member) => member.replaced))
|
|
129
|
-
};
|
|
115
|
+
function refTargets(target) {
|
|
116
|
+
if (!isUnion(target)) return [{
|
|
117
|
+
model: target,
|
|
118
|
+
read: (item) => typeof item === "string" ? item : void 0,
|
|
119
|
+
move: (_, to) => to
|
|
120
|
+
}];
|
|
121
|
+
return Object.entries(target.models).map(([kind, member]) => ({
|
|
122
|
+
model: member,
|
|
123
|
+
read: (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0,
|
|
124
|
+
move: (item, to) => ({
|
|
125
|
+
...item,
|
|
126
|
+
id: to
|
|
127
|
+
})
|
|
128
|
+
}));
|
|
130
129
|
}
|
|
131
130
|
/**
|
|
132
131
|
* Ссылка на экземпляры, которые живут в другой модели (или объединении).
|
|
@@ -134,7 +133,6 @@ function targetSignals(target) {
|
|
|
134
133
|
* удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
|
|
135
134
|
*/ function ref(config) {
|
|
136
135
|
const { from, field } = config;
|
|
137
|
-
const signals = targetSignals(config.to);
|
|
138
136
|
const rewrite = (instances, change) => {
|
|
139
137
|
let next = instances;
|
|
140
138
|
for (const [id, state] of Object.entries(instances)) {
|
|
@@ -142,31 +140,42 @@ function targetSignals(target) {
|
|
|
142
140
|
const updated = change(current);
|
|
143
141
|
if (updated !== current) {
|
|
144
142
|
if (next === instances) next = { ...instances };
|
|
145
|
-
next
|
|
143
|
+
setOwn(next, id, {
|
|
146
144
|
...state,
|
|
147
145
|
[field]: updated
|
|
148
|
-
};
|
|
146
|
+
});
|
|
149
147
|
}
|
|
150
148
|
}
|
|
151
149
|
return next;
|
|
152
150
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
151
|
+
for (const { model: target, read, move } of refTargets(config.to)) {
|
|
152
|
+
from["~react"](target, "deleted", {
|
|
153
|
+
to: "patch",
|
|
154
|
+
fn: (deleted) => (instances) => {
|
|
155
|
+
const isRemoved = (item) => {
|
|
156
|
+
const id = read(item);
|
|
157
|
+
return id !== void 0 && deleted.includes(id);
|
|
158
|
+
};
|
|
159
|
+
return rewrite(instances, (value) => {
|
|
160
|
+
if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
|
|
161
|
+
return value !== null && isRemoved(value) ? null : value;
|
|
162
|
+
});
|
|
166
163
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
164
|
+
});
|
|
165
|
+
from["~react"](target, "renamed", {
|
|
166
|
+
to: "patch",
|
|
167
|
+
fn: ({ from: before, to }) => (instances) => {
|
|
168
|
+
const replace = (item) => read(item) === before ? move(item, to) : item;
|
|
169
|
+
return rewrite(instances, (value) => {
|
|
170
|
+
if (Array.isArray(value)) {
|
|
171
|
+
const replaced = value.map(replace);
|
|
172
|
+
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
173
|
+
}
|
|
174
|
+
return value === null ? value : replace(value);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
170
179
|
}
|
|
171
180
|
export { aliases, child, model, modelState, ref, resolveAlias, union };
|
|
172
181
|
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["aliases","model","$aliases","add","alias","remove","unalias","resolved","target","combine","createEvent","merge","resolveAlias","union","models","stores","aliasStores","kind","member","Object","entries","$instances","$aliases","remove","create","upsert","paramsOf","params","Array","isArray","filter","item","map","id","data","undefined","refsOf","refs","to","fn","own","length","delete","isUnion","value","child","config","parent","model","key","parentOf","state","$idsByParent","$ids","ids","instances","aliases","index","parentId","push","deleted","includes","renamed","from","next","modelSignals","target","wrap","read","removed","replaced","targetSignals","members","ref","field","signals","rewrite","change","current","updated","isRemoved","some","replace"],"sources":["../lib/aliases.ts","../lib/relations.ts"],"sourcesContent":["import type { EventCallable, Store } from 'effector';\n\nimport type { AliasParams, Ids, Model } from './model';\n\n/** Часть модели, нужная алиасам. */\nexport type AliasTarget = Pick<\n Model<object, Record<never, unknown>>,\n '$aliases' | 'alias' | 'unalias'\n>;\n\nexport interface Aliases {\n /** Алиас → настоящий id экземпляра. */\n readonly $aliases: Store<Record<string, string>>;\n readonly add: EventCallable<AliasParams | AliasParams[]>;\n readonly remove: EventCallable<Ids>;\n /** Возвращает то же событие: события модели сами принимают алиасы. */\n readonly resolved: <Params extends { id: Ids }>(\n target: EventCallable<Params>,\n ) => EventCallable<Params>;\n}\n\n/**\n * @deprecated Алиасы встроены в модель: `model.$aliases`, `model.alias`, `model.unalias`,\n * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.\n */\nexport function aliases(model: AliasTarget): Aliases {\n return {\n $aliases: model.$aliases,\n add: model.alias,\n remove: model.unalias,\n resolved: target => target,\n };\n}\n","import {\n combine,\n createEvent,\n type Event,\n type EventCallable,\n merge,\n type Store,\n} from 'effector';\n\nimport { type Instances, type Model, resolveAlias } from './model';\n\n/** Часть модели, нужная связям: события экземпляров не участвуют, подходит любая модель с таким состоянием. */\nexport type ModelLike<State extends object> = Pick<\n Model<State, Record<never, unknown>>,\n | '$instances'\n | '$ids'\n | '$aliases'\n | 'create'\n | 'upsert'\n | 'delete'\n | 'deleted'\n | 'clear'\n | 'rename'\n | 'renamed'\n | 'update'\n | '~link'\n>;\n\ntype AnyModel = ModelLike<any>;\ntype StateOf<M> = M extends ModelLike<infer State> ? State : never;\n\n/** Ключи состояния, значение которых подходит под `Value`. */\ntype KeysOf<State, Value> = {\n [K in keyof State]-?: [State[K]] extends [Value] ? K : never;\n}[keyof State] &\n string;\n\n/**\n * Поля под ссылку: список или одна ссылка. Одиночное поле обязано допускать `null` —\n * им заменяется ссылка на удалённый экземпляр.\n */\ntype RefKeys<State, Item> = {\n [K in keyof State]-?: [State[K]] extends [readonly Item[]]\n ? K\n : null extends State[K]\n ? [State[K]] extends [Item | null]\n ? K\n : never\n : never;\n}[keyof State] &\n string;\n\n// --- union -------------------------------------------------------------------\n\nexport type UnionModels = Record<string, AnyModel>;\n\n/** Ссылка на экземпляр одной из моделей объединения. */\nexport type UnionRef<Models extends UnionModels> = {\n [K in keyof Models & string]: { kind: K; id: string };\n}[keyof Models & string];\n\nexport type UnionInstances<Models extends UnionModels> = {\n [K in keyof Models]: Instances<StateOf<Models[K]>>;\n};\n\n/** Параметры создания экземпляра одной из моделей объединения. */\nexport type UnionCreateParams<Models extends UnionModels> = {\n [K in keyof Models & string]: {\n kind: K;\n id: string;\n data?: Partial<StateOf<Models[K]>>;\n };\n}[keyof Models & string];\n\nexport interface Union<Models extends UnionModels> {\n readonly '~kind': 'union';\n readonly models: Models;\n /** Экземпляры всех моделей по ключам объединения. */\n readonly $instances: Store<UnionInstances<Models>>;\n /** Алиасы всех моделей по ключам объединения: в ссылке `{ kind, id }` id может быть алиасом. */\n readonly $aliases: Store<{ [K in keyof Models]: Record<string, string> }>;\n /** Создаёт экземпляры: каждый уходит в `create` своей модели. */\n readonly create: EventCallable<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >;\n /** Дополняет или создаёт экземпляры: каждый уходит в `upsert` своей модели. */\n readonly upsert: EventCallable<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >;\n /** Удаляет экземпляры по ссылкам: каждая уходит в свою модель. */\n readonly delete: EventCallable<UnionRef<Models> | UnionRef<Models>[]>;\n}\n\n/** Несколько моделей как одна коллекция: экземпляр адресуется парой `{ kind, id }`. */\nexport function union<Models extends UnionModels>(\n models: Models,\n): Union<Models> {\n const stores = {} as Record<string, Store<Instances<object>>>;\n\n const aliasStores = {} as Record<string, Store<Record<string, string>>>;\n\n for (const [kind, member] of Object.entries(models)) {\n stores[kind] = member.$instances;\n aliasStores[kind] = member.$aliases;\n }\n\n const $aliases = combine(aliasStores) as unknown as Union<Models>['$aliases'];\n\n const $instances = combine(stores) as unknown as Store<\n UnionInstances<Models>\n >;\n const remove = createEvent<UnionRef<Models> | UnionRef<Models>[]>();\n const create = createEvent<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >();\n const upsert = createEvent<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >();\n\n const paramsOf = (\n params: UnionCreateParams<Models> | UnionCreateParams<Models>[],\n kind: string,\n ) =>\n (Array.isArray(params) ? params : [params])\n .filter(item => item.kind === kind)\n .map(({ id, data }) => (data === undefined ? { id } : { id, data }));\n\n const refsOf = (refs: UnionRef<Models> | UnionRef<Models>[], kind: string) =>\n (Array.isArray(refs) ? refs : [refs])\n .filter(item => item.kind === kind)\n .map(item => item.id);\n\n // Модели подписаны на события объединения напрямую: вызовы подряд в одном такте не теряются.\n for (const [kind, member] of Object.entries(models)) {\n member['~link'](create, {\n to: 'create',\n fn: params => {\n const own = paramsOf(params, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n\n member['~link'](upsert, {\n to: 'upsert',\n fn: params => {\n const own = paramsOf(params, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n\n member['~link'](remove, {\n to: 'delete',\n fn: refs => {\n const own = refsOf(refs, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n }\n\n return {\n '~kind': 'union',\n models,\n $instances,\n $aliases,\n create,\n upsert,\n delete: remove,\n };\n}\n\nfunction isUnion(\n value: AnyModel | Union<UnionModels>,\n): value is Union<UnionModels> {\n return '~kind' in value && value['~kind'] === 'union';\n}\n\n// --- child -------------------------------------------------------------------\n\nexport interface ChildConfig<Parent extends object, State extends object> {\n parent: ModelLike<Parent>;\n model: ModelLike<State>;\n /** Поле дочернего экземпляра с id (или алиасом) родителя; `null` — у ребёнка нет родителя (корень дерева). */\n key: KeysOf<State, string | null>;\n}\n\nexport interface Child<State extends object = object> {\n /** Модель дочерних экземпляров. */\n readonly model: ModelLike<State>;\n /** Алиасы родителя: по ним хуки находят детей, когда родитель задан алиасом. */\n readonly parent: { readonly $aliases: Store<Record<string, string>> };\n /** Id дочерних экземпляров по настоящему id родителя, в порядке создания. */\n readonly $idsByParent: Store<Record<string, string[]>>;\n}\n\n/**\n * Дочерние экземпляры принадлежат родителю: хранят его id в поле `key`\n * и удаляются вместе с ним. Переименование родителя переносит детей.\n */\nexport function child<Parent extends object, State extends object>(\n config: ChildConfig<Parent, State>,\n): Child<State> {\n const { parent, model, key } = config;\n const parentOf = (state: State): unknown =>\n (state as Record<string, unknown>)[key];\n\n // Ребёнок может хранить алиас родителя — в индексе он лежит под настоящим id.\n const $idsByParent = combine(\n model.$ids,\n model.$instances,\n parent.$aliases,\n (ids, instances, aliases) => {\n const index: Record<string, string[]> = {};\n\n for (const id of ids) {\n const state = instances[id];\n const parentId = state === undefined ? undefined : parentOf(state);\n\n if (typeof parentId === 'string') {\n (index[resolveAlias(aliases, parentId)] ??= []).push(id);\n }\n }\n\n return index;\n },\n );\n\n // В `deleted` — настоящие id и их алиасы, так что ребёнок находится и по алиасу родителя.\n // В дереве удаление детей порождает новый факт, и ветка уходит уровень за уровнем;\n // когда удалять нечего, факта нет — каскад останавливается.\n model['~link'](parent.deleted, {\n to: 'deleteWhere',\n fn: ids => state => {\n const parentId = parentOf(state);\n\n return typeof parentId === 'string' && ids.includes(parentId);\n },\n });\n\n model['~link'](parent.renamed, {\n to: 'patch',\n fn:\n ({ from, to }) =>\n instances => {\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n if (parentOf(state) === from) {\n if (next === instances) {\n next = { ...instances };\n }\n\n next[id] = { ...state, [key]: to };\n }\n }\n\n return next;\n },\n });\n\n return { model, parent: { $aliases: parent.$aliases }, $idsByParent };\n}\n\n// --- ref ---------------------------------------------------------------------\n\ntype RefItem<Target> =\n Target extends Union<infer Models> ? UnionRef<Models> : string;\n\nexport interface RefConfig<\n State extends object,\n Target extends AnyModel | Union<any>,\n> {\n from: ModelLike<State>;\n /** Поле со ссылкой: одна (`item | null`) или список. */\n field: RefKeys<State, RefItem<Target>>;\n to: Target;\n}\n\ninterface TargetSignals {\n /** Ссылки, подходящие под предикат, должны исчезнуть. */\n removed: Event<(item: unknown) => boolean>;\n /** Ссылки заменяются: возвращается та же ссылка, если менять нечего. */\n replaced: Event<(item: unknown) => unknown>;\n}\n\nfunction modelSignals(\n target: AnyModel,\n wrap: (id: string) => unknown,\n read: (item: unknown) => string | undefined,\n): TargetSignals {\n return {\n // В списке и алиасы удалённых экземпляров: ссылка через алиас тоже пропадает.\n removed: target.deleted.map(deleted => (item: unknown) => {\n const id = read(item);\n\n return id !== undefined && deleted.includes(id);\n }),\n replaced: target.renamed.map(\n ({ from, to }) =>\n (item: unknown) =>\n read(item) === from ? wrap(to) : item,\n ),\n };\n}\n\nfunction targetSignals(target: AnyModel | Union<UnionModels>): TargetSignals {\n if (!isUnion(target)) {\n return modelSignals(\n target,\n id => id,\n item => (typeof item === 'string' ? item : undefined),\n );\n }\n\n const members = Object.entries(target.models).map(([kind, member]) =>\n modelSignals(\n member,\n id => ({ kind, id }),\n item =>\n typeof item === 'object' &&\n item !== null &&\n (item as { kind?: unknown }).kind === kind\n ? (item as { id: string }).id\n : undefined,\n ),\n );\n\n return {\n removed: merge(members.map(member => member.removed)),\n replaced: merge(members.map(member => member.replaced)),\n };\n}\n\n/**\n * Ссылка на экземпляры, которые живут в другой модели (или объединении).\n * Поле остаётся обычными данными; связь лишь поддерживает его целостность:\n * удалённые экземпляры пропадают из ссылок, переименованные — переносятся.\n */\nexport function ref<State extends object, Target extends AnyModel | Union<any>>(\n config: RefConfig<State, Target>,\n): void {\n const { from, field } = config;\n const signals = targetSignals(config.to as AnyModel | Union<UnionModels>);\n\n const rewrite = (\n instances: Instances<State>,\n change: (value: unknown) => unknown,\n ): Instances<State> => {\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n const current = (state as Record<string, unknown>)[field];\n const updated = change(current);\n\n if (updated !== current) {\n if (next === instances) {\n next = { ...instances };\n }\n\n next[id] = { ...state, [field]: updated };\n }\n }\n\n return next;\n };\n\n from['~link'](signals.removed, {\n to: 'patch',\n fn: isRemoved => instances =>\n rewrite(instances, value => {\n if (Array.isArray(value)) {\n return value.some(isRemoved)\n ? value.filter(item => !isRemoved(item))\n : value;\n }\n\n return value !== null && isRemoved(value) ? null : value;\n }),\n });\n\n from['~link'](signals.replaced, {\n to: 'patch',\n fn: replace => instances =>\n rewrite(instances, value => {\n if (Array.isArray(value)) {\n const replaced = value.map(replace);\n\n return replaced.some((item, index) => item !== value[index])\n ? replaced\n : value;\n }\n\n return value === null ? value : replace(value);\n }),\n });\n}\n"],"mappings":";;;;;;GAyBA,SAAgBA,QAAQC,OAAkB;CACxC,OAAO;EACLC,UAAUD,MAAMC;EAChBC,KAAKF,MAAMG;EACXC,QAAQJ,MAAMK;EACdC,WAAUC,WAAUA;CACtB;AACF;;wFC8DA,SAAgBK,MACdC,QAAc;CAEd,MAAMC,SAAS,CAAC;CAEhB,MAAMC,cAAc,CAAC;CAErB,KAAK,MAAM,CAACC,MAAMC,WAAWC,OAAOC,QAAQN,MAAAA,GAAS;EACnDC,OAAOE,QAAQC,OAAOG;EACtBL,YAAYC,QAAQC,OAAOI;CAC7B;CAEA,MAAMA,WAAWb,QAAQO,WAAAA;CAEzB,MAAMK,aAAaZ,QAAQM,MAAAA;CAG3B,MAAMQ,SAASb,YAAAA;CACf,MAAMc,SAASd,YAAAA;CAGf,MAAMe,SAASf,YAAAA;CAIf,MAAM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K,QAAQ,CAACY,QAAQN,SAAS;EAC7B/B,IAAI;EACJC,KAAIyC,eAAazB,cACfqB,QAAQrB,YAAWX,UAAAA;GACjB,IAAIhB,MAAMC,QAAQe,KAAAA,GAChB,OAAOA,MAAMqC,KAAKD,SAAAA,IACdpC,MAAMd,QAAOC,SAAQ,CAACiD,UAAUjD,IAAAA,CAAAA,IAChCa;GAGN,OAAOA,UAAU,QAAQoC,UAAUpC,KAAAA,IAAS,OAAOA;EACrD,CAAA;CACJ,CAAA;CAEAmB,KAAK,QAAQ,CAACY,QAAQL,UAAU;EAC9BhC,IAAI;EACJC,KAAI2C,aAAW3B,cACbqB,QAAQrB,YAAWX,UAAAA;GACjB,IAAIhB,MAAMC,QAAQe,KAAAA,GAAQ;IACxB,MAAM0B,WAAW1B,MAAMZ,IAAIkD,OAAAA;IAE3B,OAAOZ,SAASW,MAAMlD,MAAM0B,UAAU1B,SAASa,MAAMa,MAAM,IACvDa,WACA1B;GACN;GAEA,OAAOA,UAAU,OAAOA,QAAQsC,QAAQtC,KAAAA;EAC1C,CAAA;CACJ,CAAA;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["aliases","model","$aliases","add","alias","remove","unalias","resolved","target","combine","createEvent","resolveAlias","setOwn","union","models","stores","aliasStores","kind","member","Object","entries","$instances","$aliases","remove","create","upsert","paramsOf","params","Array","isArray","filter","item","map","id","data","undefined","refsOf","refs","to","fn","own","length","delete","isUnion","value","child","config","parent","model","key","parentOf","state","$idsByParent","$ids","ids","instances","aliases","index","parentId","real","hasOwn","push","includes","from","next","refTargets","target","read","move","_","ref","field","rewrite","change","current","updated","deleted","isRemoved","some","before","replace","replaced"],"sources":["../lib/aliases.ts","../lib/relations.ts"],"sourcesContent":["import type { EventCallable, Store } from 'effector';\n\nimport type { AliasParams, Ids, Model } from './model';\n\n/** Часть модели, нужная алиасам. */\nexport type AliasTarget = Pick<\n Model<object, Record<never, unknown>>,\n '$aliases' | 'alias' | 'unalias'\n>;\n\nexport interface Aliases {\n /** Алиас → настоящий id экземпляра. */\n readonly $aliases: Store<Record<string, string>>;\n readonly add: EventCallable<AliasParams | AliasParams[]>;\n readonly remove: EventCallable<Ids>;\n /** Возвращает то же событие: события модели сами принимают алиасы. */\n readonly resolved: <Params extends { id: Ids }>(\n target: EventCallable<Params>,\n ) => EventCallable<Params>;\n}\n\n/**\n * @deprecated Алиасы встроены в модель: `model.$aliases`, `model.alias`, `model.unalias`,\n * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.\n */\nexport function aliases(model: AliasTarget): Aliases {\n return {\n $aliases: model.$aliases,\n add: model.alias,\n remove: model.unalias,\n resolved: target => target,\n };\n}\n","import { combine, createEvent, type EventCallable, type Store } from 'effector';\n\nimport { type Instances, type Model, resolveAlias, setOwn } from './model';\n\n/** Часть модели, нужная связям: события экземпляров не участвуют, подходит любая модель с таким состоянием. */\nexport type ModelLike<State extends object> = Pick<\n Model<State, Record<never, unknown>>,\n | '$instances'\n | '$ids'\n | '$aliases'\n | 'create'\n | 'upsert'\n | 'delete'\n | 'deleted'\n | 'clear'\n | 'rename'\n | 'renamed'\n | 'update'\n | '~link'\n | '~react'\n>;\n\ntype AnyModel = ModelLike<any>;\ntype StateOf<M> = M extends ModelLike<infer State> ? State : never;\n\n/** Ключи состояния, значение которых подходит под `Value`. */\ntype KeysOf<State, Value> = {\n [K in keyof State]-?: [State[K]] extends [Value] ? K : never;\n}[keyof State] &\n string;\n\n/**\n * Поля под ссылку: список или одна ссылка. Одиночное поле обязано допускать `null` —\n * им заменяется ссылка на удалённый экземпляр.\n */\ntype RefKeys<State, Item> = {\n [K in keyof State]-?: [State[K]] extends [readonly Item[]]\n ? K\n : null extends State[K]\n ? [State[K]] extends [Item | null]\n ? K\n : never\n : never;\n}[keyof State] &\n string;\n\n// --- union -------------------------------------------------------------------\n\nexport type UnionModels = Record<string, AnyModel>;\n\n/** Ссылка на экземпляр одной из моделей объединения. */\nexport type UnionRef<Models extends UnionModels> = {\n [K in keyof Models & string]: { kind: K; id: string };\n}[keyof Models & string];\n\nexport type UnionInstances<Models extends UnionModels> = {\n [K in keyof Models]: Instances<StateOf<Models[K]>>;\n};\n\n/** Параметры создания экземпляра одной из моделей объединения. */\nexport type UnionCreateParams<Models extends UnionModels> = {\n [K in keyof Models & string]: {\n kind: K;\n id: string;\n data?: Partial<StateOf<Models[K]>>;\n };\n}[keyof Models & string];\n\nexport interface Union<Models extends UnionModels> {\n readonly '~kind': 'union';\n readonly models: Models;\n /** Экземпляры всех моделей по ключам объединения. */\n readonly $instances: Store<UnionInstances<Models>>;\n /** Алиасы всех моделей по ключам объединения: в ссылке `{ kind, id }` id может быть алиасом. */\n readonly $aliases: Store<{ [K in keyof Models]: Record<string, string> }>;\n /** Создаёт экземпляры: каждый уходит в `create` своей модели. */\n readonly create: EventCallable<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >;\n /** Дополняет или создаёт экземпляры: каждый уходит в `upsert` своей модели. */\n readonly upsert: EventCallable<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >;\n /** Удаляет экземпляры по ссылкам: каждая уходит в свою модель. */\n readonly delete: EventCallable<UnionRef<Models> | UnionRef<Models>[]>;\n}\n\n/** Несколько моделей как одна коллекция: экземпляр адресуется парой `{ kind, id }`. */\nexport function union<Models extends UnionModels>(\n models: Models,\n): Union<Models> {\n const stores = {} as Record<string, Store<Instances<object>>>;\n\n const aliasStores = {} as Record<string, Store<Record<string, string>>>;\n\n for (const [kind, member] of Object.entries(models)) {\n stores[kind] = member.$instances;\n aliasStores[kind] = member.$aliases;\n }\n\n const $aliases = combine(aliasStores) as unknown as Union<Models>['$aliases'];\n\n const $instances = combine(stores) as unknown as Store<\n UnionInstances<Models>\n >;\n const remove = createEvent<UnionRef<Models> | UnionRef<Models>[]>();\n const create = createEvent<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >();\n const upsert = createEvent<\n UnionCreateParams<Models> | UnionCreateParams<Models>[]\n >();\n\n const paramsOf = (\n params: UnionCreateParams<Models> | UnionCreateParams<Models>[],\n kind: string,\n ) =>\n (Array.isArray(params) ? params : [params])\n .filter(item => item.kind === kind)\n .map(({ id, data }) => (data === undefined ? { id } : { id, data }));\n\n const refsOf = (refs: UnionRef<Models> | UnionRef<Models>[], kind: string) =>\n (Array.isArray(refs) ? refs : [refs])\n .filter(item => item.kind === kind)\n .map(item => item.id);\n\n // Модели подписаны на события объединения напрямую: вызовы подряд в одном такте не теряются.\n for (const [kind, member] of Object.entries(models)) {\n member['~link'](create, {\n to: 'create',\n fn: params => {\n const own = paramsOf(params, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n\n member['~link'](upsert, {\n to: 'upsert',\n fn: params => {\n const own = paramsOf(params, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n\n member['~link'](remove, {\n to: 'delete',\n fn: refs => {\n const own = refsOf(refs, kind);\n\n return own.length > 0 ? own : undefined;\n },\n });\n }\n\n return {\n '~kind': 'union',\n models,\n $instances,\n $aliases,\n create,\n upsert,\n delete: remove,\n };\n}\n\nfunction isUnion(\n value: AnyModel | Union<UnionModels>,\n): value is Union<UnionModels> {\n return '~kind' in value && value['~kind'] === 'union';\n}\n\n// --- child -------------------------------------------------------------------\n\nexport interface ChildConfig<Parent extends object, State extends object> {\n parent: ModelLike<Parent>;\n model: ModelLike<State>;\n /** Поле дочернего экземпляра с id (или алиасом) родителя; `null` — у ребёнка нет родителя (корень дерева). */\n key: KeysOf<State, string | null>;\n}\n\nexport interface Child<State extends object = object> {\n /** Модель дочерних экземпляров. */\n readonly model: ModelLike<State>;\n /** Алиасы родителя: по ним хуки находят детей, когда родитель задан алиасом. */\n readonly parent: { readonly $aliases: Store<Record<string, string>> };\n /** Id дочерних экземпляров по настоящему id родителя, в порядке создания. */\n readonly $idsByParent: Store<Record<string, string[]>>;\n}\n\n/**\n * Дочерние экземпляры принадлежат родителю: хранят его id в поле `key`\n * и удаляются вместе с ним. Переименование родителя переносит детей.\n */\nexport function child<Parent extends object, State extends object>(\n config: ChildConfig<Parent, State>,\n): Child<State> {\n const { parent, model, key } = config;\n const parentOf = (state: State): unknown =>\n (state as Record<string, unknown>)[key];\n\n // Ребёнок может хранить алиас родителя — в индексе он лежит под настоящим id.\n const $idsByParent = combine(\n model.$ids,\n model.$instances,\n parent.$aliases,\n (ids, instances, aliases) => {\n const index: Record<string, string[]> = {};\n\n for (const id of ids) {\n const state = instances[id];\n const parentId = state === undefined ? undefined : parentOf(state);\n\n if (typeof parentId === 'string') {\n const real = resolveAlias(aliases, parentId);\n\n if (!Object.hasOwn(index, real)) {\n setOwn(index, real, []);\n }\n\n index[real]!.push(id);\n }\n }\n\n return index;\n },\n );\n\n // В `deleted` — настоящие id и их алиасы, так что ребёнок находится и по алиасу родителя.\n // В дереве удаление детей порождает новый факт, и ветка уходит уровень за уровнем;\n // когда удалять нечего, факта нет — каскад останавливается.\n model['~react'](parent, 'deleted', {\n to: 'deleteWhere',\n fn: ids => state => {\n const parentId = parentOf(state);\n\n return typeof parentId === 'string' && ids.includes(parentId);\n },\n });\n\n model['~react'](parent, 'renamed', {\n to: 'patch',\n fn:\n ({ from, to }) =>\n instances => {\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n if (parentOf(state) === from) {\n if (next === instances) {\n next = { ...instances };\n }\n\n setOwn<State>(next, id, { ...state, [key]: to });\n }\n }\n\n return next;\n },\n });\n\n return { model, parent: { $aliases: parent.$aliases }, $idsByParent };\n}\n\n// --- ref ---------------------------------------------------------------------\n\ntype RefItem<Target> =\n Target extends Union<infer Models> ? UnionRef<Models> : string;\n\nexport interface RefConfig<\n State extends object,\n Target extends AnyModel | Union<any>,\n> {\n from: ModelLike<State>;\n /** Поле со ссылкой: одна (`item | null`) или список. */\n field: RefKeys<State, RefItem<Target>>;\n to: Target;\n}\n\ninterface RefTarget {\n model: AnyModel;\n /** Id экземпляра этой модели в элементе ссылки; `undefined` — элемент не про неё. */\n read: (item: unknown) => string | undefined;\n /** Тот же элемент с новым id: остальные его поля сохраняются. */\n move: (item: unknown, to: string) => unknown;\n}\n\nfunction refTargets(target: AnyModel | Union<UnionModels>): RefTarget[] {\n if (!isUnion(target)) {\n return [\n {\n model: target,\n read: item => (typeof item === 'string' ? item : undefined),\n move: (_, to) => to,\n },\n ];\n }\n\n return Object.entries(target.models).map(([kind, member]) => ({\n model: member,\n read: item =>\n typeof item === 'object' &&\n item !== null &&\n (item as { kind?: unknown }).kind === kind\n ? (item as { id: string }).id\n : undefined,\n move: (item, to) => ({ ...(item as object), id: to }),\n }));\n}\n\n/**\n * Ссылка на экземпляры, которые живут в другой модели (или объединении).\n * Поле остаётся обычными данными; связь лишь поддерживает его целостность:\n * удалённые экземпляры пропадают из ссылок, переименованные — переносятся.\n */\nexport function ref<State extends object, Target extends AnyModel | Union<any>>(\n config: RefConfig<State, Target>,\n): void {\n const { from, field } = config;\n const rewrite = (\n instances: Instances<State>,\n change: (value: unknown) => unknown,\n ): Instances<State> => {\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n const current = (state as Record<string, unknown>)[field];\n const updated = change(current);\n\n if (updated !== current) {\n if (next === instances) {\n next = { ...instances };\n }\n\n setOwn<State>(next, id, { ...state, [field]: updated });\n }\n }\n\n return next;\n };\n\n for (const { model: target, read, move } of refTargets(\n config.to as AnyModel | Union<UnionModels>,\n )) {\n // В списке и алиасы удалённых экземпляров: ссылка через алиас тоже пропадает.\n from['~react'](target, 'deleted', {\n to: 'patch',\n fn: deleted => instances => {\n const isRemoved = (item: unknown) => {\n const id = read(item);\n\n return id !== undefined && deleted.includes(id);\n };\n\n return rewrite(instances, value => {\n if (Array.isArray(value)) {\n return value.some(isRemoved)\n ? value.filter(item => !isRemoved(item))\n : value;\n }\n\n return value !== null && isRemoved(value) ? null : value;\n });\n },\n });\n\n from['~react'](target, 'renamed', {\n to: 'patch',\n fn:\n ({ from: before, to }) =>\n instances => {\n const replace = (item: unknown) =>\n read(item) === before ? move(item, to) : item;\n\n return rewrite(instances, value => {\n if (Array.isArray(value)) {\n const replaced = value.map(replace);\n\n return replaced.some((item, index) => item !== value[index])\n ? replaced\n : value;\n }\n\n return value === null ? value : replace(value);\n });\n },\n });\n }\n}\n"],"mappings":";;;;;;GAyBA,SAAgBA,QAAQC,OAAkB;CACxC,OAAO;EACLC,UAAUD,MAAMC;EAChBC,KAAKF,MAAMG;EACXC,QAAQJ,MAAMK;EACdC,WAAUC,WAAUA;CACtB;AACF;;wFCwDA,SAAgBK,MACdC,QAAc;CAEd,MAAMC,SAAS,CAAC;CAEhB,MAAMC,cAAc,CAAC;CAErB,KAAK,MAAM,CAACC,MAAMC,WAAWC,OAAOC,QAAQN,MAAAA,GAAS;EACnDC,OAAOE,QAAQC,OAAOG;EACtBL,YAAYC,QAAQC,OAAOI;CAC7B;CAEA,MAAMA,WAAWb,QAAQO,WAAAA;CAEzB,MAAMK,aAAaZ,QAAQM,MAAAA;CAG3B,MAAMQ,SAASb,YAAAA;CACf,MAAMc,SAASd,YAAAA;CAGf,MAAMe,SAASf,YAAAA;CAIf,MAAMgB,YACJC,QACAV,UAECW,MAAMC,QAAQF,MAAAA,IAAUA,SAAS,CAACA,MAAO,EAAA,CACvCG,QAAOC,SAAQA,KAAKd,SAASA,IAAAA,CAAAA,CAC7Be,KAAK,EAAEC,IAAIC,WAAYA,SAASC,KAAAA,IAAY,EAAEF,GAAG,IAAI;EAAEA;EAAIC;CAAK,CAAA;CAErE,MAAME,UAAUC,MAA6CpB,UAC1DW,MAAMC,QAAQQ,IAAAA,IAAQA,OAAO,CAACA,IAAK,EAAA,CACjCP,QAAOC,SAAQA,KAAKd,SAASA,IAAAA,CAAAA,CAC7Be,KAAID,SAAQA,KAAKE,EAAE;CAGxB,KAAK,MAAM,CAAChB,MAAMC,WAAWC,OAAOC,QAAQN,MAAAA,GAAS;EACnDI,OAAO,QAAQ,CAACM,QAAQ;GACtBc,IAAI;GACJC,KAAIZ,WAAAA;IACF,MAAMa,MAAMd,SAASC,QAAQV,IAA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