@olovyannikov/effector-models 0.2.0 → 0.2.2
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 +52 -0
- package/README.md +5 -1
- package/dist/index.cjs +62 -48
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +63 -49
- package/dist/index.mjs.map +1 -1
- package/dist/{model-Cav66tnw.cjs → model-DajD90ci.cjs} +159 -40
- package/dist/{model-BNsi5pxp.mjs → model-kSnLIQTE.mjs} +149 -42
- package/dist/model-kSnLIQTE.mjs.map +1 -0
- 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-B6-d4bl0.d.mts} +13 -2
- package/dist/relations-B6-d4bl0.d.mts.map +1 -0
- package/dist/{relations-pJXSBtRd.d.cts → relations-E3doGM1h.d.cts} +13 -2
- package/dist/relations-E3doGM1h.d.cts.map +1 -0
- package/package.json +2 -2
- 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,57 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.2
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- **Relations between two models and commands of the same tick.** The
|
|
8
|
+
limitation from 0.2.1 is gone. A relation reacts to a `deleted` or
|
|
9
|
+
`renamed` fact after the commands already launched in that tick, so it used
|
|
10
|
+
to reach data written after the fact: reloading lists and their cards in
|
|
11
|
+
one `sample` (`clear`, `create`, `create`) deleted the new cards and
|
|
12
|
+
cleared the new references. The model now remembers when a field used by a
|
|
13
|
+
relation was written, and a relation skips what was written after the
|
|
14
|
+
fact.
|
|
15
|
+
|
|
16
|
+
### Known limitation
|
|
17
|
+
|
|
18
|
+
- A list of references rewritten after the fact is kept as a whole, also
|
|
19
|
+
when the new list still contains the deleted id.
|
|
20
|
+
|
|
21
|
+
### Internal
|
|
22
|
+
|
|
23
|
+
- The package folder is `packages/effector-models`; `repository.directory`
|
|
24
|
+
and the release workflow follow.
|
|
25
|
+
|
|
26
|
+
## 0.2.1
|
|
27
|
+
|
|
28
|
+
A second review of the rewritten core.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- **Trees and self-references.** A model's reaction to its own fact (the
|
|
33
|
+
cascade of a tree, a `ref` to itself) is applied inside the same write.
|
|
34
|
+
Before, it ran after the commands already launched in the same tick, so
|
|
35
|
+
`clear` followed by `create` of the same tree deleted the new nodes.
|
|
36
|
+
- Writing a previously seen state object back into `$state` (restoring a
|
|
37
|
+
snapshot) no longer re-emits its old `deleted` / `renamed` / `missed`.
|
|
38
|
+
- The id or alias `'__proto__'` is stored as an ordinary key. It used to
|
|
39
|
+
change the prototype of the dictionary and leave `ids` and `instances`
|
|
40
|
+
out of sync.
|
|
41
|
+
- `ref` to a `union`: renaming a target keeps the other fields of the
|
|
42
|
+
reference (`{ kind, id, seat }` used to become `{ kind, id }`).
|
|
43
|
+
|
|
44
|
+
### Changed
|
|
45
|
+
|
|
46
|
+
- Deleting a branch of a tree emits one `deleted` fact with every deleted id
|
|
47
|
+
instead of one fact per level.
|
|
48
|
+
|
|
49
|
+
### Known limitation
|
|
50
|
+
|
|
51
|
+
- A relation between two models still reacts after the commands already
|
|
52
|
+
launched in the same tick. See
|
|
53
|
+
[Relations](https://olovyannikov.github.io/effector-kit/guide/keyed-models#relations).
|
|
54
|
+
|
|
3
55
|
## 0.2.0
|
|
4
56
|
|
|
5
57
|
A review of the core found that writes could be lost or reordered. The model
|
package/README.md
CHANGED
|
@@ -100,6 +100,10 @@ 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 reacts to data as it was at the moment of the fact. If one `sample` deletes a list and creates it again with new cards — reloading data from a server, for example — the cascade removes the old cards and leaves the new ones, although it runs after both commands. The same holds for references: a reference written after its target was deleted points to the new instance with that id and is kept.
|
|
104
|
+
|
|
105
|
+
One case is approximate: a list of references rewritten after the fact is kept as a whole, also when the new list still contains the deleted id.
|
|
106
|
+
|
|
103
107
|
### `child` — owned instances
|
|
104
108
|
|
|
105
109
|
Children store the id of their parent in a field and are deleted together with it.
|
|
@@ -328,7 +332,7 @@ An [agent skill](https://github.com/Olovyannikov/effector-kit/tree/main/skills/e
|
|
|
328
332
|
|
|
329
333
|
## Releasing
|
|
330
334
|
|
|
331
|
-
Bump `version` in `package.json`, describe the changes in `CHANGELOG.md` and merge into `main`. The `
|
|
335
|
+
Bump `version` in `package.json`, describe the changes in `CHANGELOG.md` and merge into `main`. The `package` workflow checks the package, installs the packed tarball into an empty project and publishes the version if it is not on npm yet: a prerelease gets the dist-tag `next`, a stable version gets `latest`.
|
|
332
336
|
|
|
333
337
|
While the package is on `0.x`, a breaking change bumps the minor version and everything else bumps the patch.
|
|
334
338
|
|
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-DajD90ci.cjs");
|
|
3
3
|
let effector = require("effector");
|
|
4
4
|
// lib/aliases.ts
|
|
5
5
|
/**
|
|
@@ -78,27 +78,33 @@ 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["~track"](key);
|
|
90
|
+
model["~react"](parent, "deleted", {
|
|
86
91
|
to: "deleteWhere",
|
|
87
92
|
fn: (ids) => (state) => {
|
|
88
93
|
const parentId = parentOf(state);
|
|
89
|
-
return typeof parentId === "string" && ids.includes(parentId);
|
|
94
|
+
return typeof parentId === "string" && ids.includes(parentId) && !require_model.writtenAfter(state, key, ids);
|
|
90
95
|
}
|
|
91
96
|
});
|
|
92
|
-
model["~
|
|
97
|
+
model["~react"](parent, "renamed", {
|
|
93
98
|
to: "patch",
|
|
94
|
-
fn: (
|
|
99
|
+
fn: (fact) => (instances) => {
|
|
100
|
+
const { from, to } = fact;
|
|
95
101
|
let next = instances;
|
|
96
|
-
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from) {
|
|
102
|
+
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from && !require_model.writtenAfter(state, key, fact)) {
|
|
97
103
|
if (next === instances) next = { ...instances };
|
|
98
|
-
next
|
|
104
|
+
require_model.setOwn(next, id, {
|
|
99
105
|
...state,
|
|
100
106
|
[key]: to
|
|
101
|
-
};
|
|
107
|
+
});
|
|
102
108
|
}
|
|
103
109
|
return next;
|
|
104
110
|
}
|
|
@@ -109,25 +115,20 @@ function isUnion(value) {
|
|
|
109
115
|
$idsByParent
|
|
110
116
|
};
|
|
111
117
|
}
|
|
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
|
-
};
|
|
118
|
+
function refTargets(target) {
|
|
119
|
+
if (!isUnion(target)) return [{
|
|
120
|
+
model: target,
|
|
121
|
+
read: (item) => typeof item === "string" ? item : void 0,
|
|
122
|
+
move: (_, to) => to
|
|
123
|
+
}];
|
|
124
|
+
return Object.entries(target.models).map(([kind, member]) => ({
|
|
125
|
+
model: member,
|
|
126
|
+
read: (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0,
|
|
127
|
+
move: (item, to) => ({
|
|
128
|
+
...item,
|
|
129
|
+
id: to
|
|
130
|
+
})
|
|
131
|
+
}));
|
|
131
132
|
}
|
|
132
133
|
/**
|
|
133
134
|
* Ссылка на экземпляры, которые живут в другой модели (или объединении).
|
|
@@ -135,39 +136,52 @@ function targetSignals(target) {
|
|
|
135
136
|
* удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
|
|
136
137
|
*/ function ref(config) {
|
|
137
138
|
const { from, field } = config;
|
|
138
|
-
|
|
139
|
-
const rewrite = (instances, change) => {
|
|
139
|
+
from["~track"](field);
|
|
140
|
+
const rewrite = (instances, fact, change) => {
|
|
140
141
|
let next = instances;
|
|
141
142
|
for (const [id, state] of Object.entries(instances)) {
|
|
143
|
+
if (require_model.writtenAfter(state, field, fact)) continue;
|
|
142
144
|
const current = state[field];
|
|
143
145
|
const updated = change(current);
|
|
144
146
|
if (updated !== current) {
|
|
145
147
|
if (next === instances) next = { ...instances };
|
|
146
|
-
next
|
|
148
|
+
require_model.setOwn(next, id, {
|
|
147
149
|
...state,
|
|
148
150
|
[field]: updated
|
|
149
|
-
};
|
|
151
|
+
});
|
|
150
152
|
}
|
|
151
153
|
}
|
|
152
154
|
return next;
|
|
153
155
|
};
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
156
|
+
for (const { model: target, read, move } of refTargets(config.to)) {
|
|
157
|
+
from["~react"](target, "deleted", {
|
|
158
|
+
to: "patch",
|
|
159
|
+
fn: (deleted) => (instances) => {
|
|
160
|
+
const isRemoved = (item) => {
|
|
161
|
+
const id = read(item);
|
|
162
|
+
return id !== void 0 && deleted.includes(id);
|
|
163
|
+
};
|
|
164
|
+
return rewrite(instances, deleted, (value) => {
|
|
165
|
+
if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
|
|
166
|
+
return value !== null && isRemoved(value) ? null : value;
|
|
167
|
+
});
|
|
167
168
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
169
|
+
});
|
|
170
|
+
from["~react"](target, "renamed", {
|
|
171
|
+
to: "patch",
|
|
172
|
+
fn: (fact) => (instances) => {
|
|
173
|
+
const { from: before, to } = fact;
|
|
174
|
+
const replace = (item) => read(item) === before ? move(item, to) : item;
|
|
175
|
+
return rewrite(instances, fact, (value) => {
|
|
176
|
+
if (Array.isArray(value)) {
|
|
177
|
+
const replaced = value.map(replace);
|
|
178
|
+
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
179
|
+
}
|
|
180
|
+
return value === null ? value : replace(value);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
171
185
|
}
|
|
172
186
|
exports.aliases = aliases;
|
|
173
187
|
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-E3doGM1h.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-B6-d4bl0.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 { a as writtenAfter, i as setOwn, n as modelState, r as resolveAlias, t as model } from "./model-kSnLIQTE.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,33 @@ 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["~track"](key);
|
|
89
|
+
model["~react"](parent, "deleted", {
|
|
85
90
|
to: "deleteWhere",
|
|
86
91
|
fn: (ids) => (state) => {
|
|
87
92
|
const parentId = parentOf(state);
|
|
88
|
-
return typeof parentId === "string" && ids.includes(parentId);
|
|
93
|
+
return typeof parentId === "string" && ids.includes(parentId) && !writtenAfter(state, key, ids);
|
|
89
94
|
}
|
|
90
95
|
});
|
|
91
|
-
model["~
|
|
96
|
+
model["~react"](parent, "renamed", {
|
|
92
97
|
to: "patch",
|
|
93
|
-
fn: (
|
|
98
|
+
fn: (fact) => (instances) => {
|
|
99
|
+
const { from, to } = fact;
|
|
94
100
|
let next = instances;
|
|
95
|
-
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from) {
|
|
101
|
+
for (const [id, state] of Object.entries(instances)) if (parentOf(state) === from && !writtenAfter(state, key, fact)) {
|
|
96
102
|
if (next === instances) next = { ...instances };
|
|
97
|
-
next
|
|
103
|
+
setOwn(next, id, {
|
|
98
104
|
...state,
|
|
99
105
|
[key]: to
|
|
100
|
-
};
|
|
106
|
+
});
|
|
101
107
|
}
|
|
102
108
|
return next;
|
|
103
109
|
}
|
|
@@ -108,25 +114,20 @@ function isUnion(value) {
|
|
|
108
114
|
$idsByParent
|
|
109
115
|
};
|
|
110
116
|
}
|
|
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
|
-
};
|
|
117
|
+
function refTargets(target) {
|
|
118
|
+
if (!isUnion(target)) return [{
|
|
119
|
+
model: target,
|
|
120
|
+
read: (item) => typeof item === "string" ? item : void 0,
|
|
121
|
+
move: (_, to) => to
|
|
122
|
+
}];
|
|
123
|
+
return Object.entries(target.models).map(([kind, member]) => ({
|
|
124
|
+
model: member,
|
|
125
|
+
read: (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0,
|
|
126
|
+
move: (item, to) => ({
|
|
127
|
+
...item,
|
|
128
|
+
id: to
|
|
129
|
+
})
|
|
130
|
+
}));
|
|
130
131
|
}
|
|
131
132
|
/**
|
|
132
133
|
* Ссылка на экземпляры, которые живут в другой модели (или объединении).
|
|
@@ -134,39 +135,52 @@ function targetSignals(target) {
|
|
|
134
135
|
* удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
|
|
135
136
|
*/ function ref(config) {
|
|
136
137
|
const { from, field } = config;
|
|
137
|
-
|
|
138
|
-
const rewrite = (instances, change) => {
|
|
138
|
+
from["~track"](field);
|
|
139
|
+
const rewrite = (instances, fact, change) => {
|
|
139
140
|
let next = instances;
|
|
140
141
|
for (const [id, state] of Object.entries(instances)) {
|
|
142
|
+
if (writtenAfter(state, field, fact)) continue;
|
|
141
143
|
const current = state[field];
|
|
142
144
|
const updated = change(current);
|
|
143
145
|
if (updated !== current) {
|
|
144
146
|
if (next === instances) next = { ...instances };
|
|
145
|
-
next
|
|
147
|
+
setOwn(next, id, {
|
|
146
148
|
...state,
|
|
147
149
|
[field]: updated
|
|
148
|
-
};
|
|
150
|
+
});
|
|
149
151
|
}
|
|
150
152
|
}
|
|
151
153
|
return next;
|
|
152
154
|
};
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
155
|
+
for (const { model: target, read, move } of refTargets(config.to)) {
|
|
156
|
+
from["~react"](target, "deleted", {
|
|
157
|
+
to: "patch",
|
|
158
|
+
fn: (deleted) => (instances) => {
|
|
159
|
+
const isRemoved = (item) => {
|
|
160
|
+
const id = read(item);
|
|
161
|
+
return id !== void 0 && deleted.includes(id);
|
|
162
|
+
};
|
|
163
|
+
return rewrite(instances, deleted, (value) => {
|
|
164
|
+
if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
|
|
165
|
+
return value !== null && isRemoved(value) ? null : value;
|
|
166
|
+
});
|
|
166
167
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
168
|
+
});
|
|
169
|
+
from["~react"](target, "renamed", {
|
|
170
|
+
to: "patch",
|
|
171
|
+
fn: (fact) => (instances) => {
|
|
172
|
+
const { from: before, to } = fact;
|
|
173
|
+
const replace = (item) => read(item) === before ? move(item, to) : item;
|
|
174
|
+
return rewrite(instances, fact, (value) => {
|
|
175
|
+
if (Array.isArray(value)) {
|
|
176
|
+
const replaced = value.map(replace);
|
|
177
|
+
return replaced.some((item, index) => item !== value[index]) ? replaced : value;
|
|
178
|
+
}
|
|
179
|
+
return value === null ? value : replace(value);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
}
|
|
170
184
|
}
|
|
171
185
|
export { aliases, child, model, modelState, ref, resolveAlias, union };
|
|
172
186
|
|
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;C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,OAAOR,EAAE;CAEvC,MAAMsC,WACJrB,WACAsB,WAAAA;EAEA,IAAIb,OAAOT;EAEX,KAAK,MAAM,CAACtB,IAAIkB,UAAUhC,OAAOC,QAAQmC,SAAAA,GAAY;GACnD,MAAMuB,UAAU,MAAmCJ;GACnD,MAAMK,UAAUF,OAAOC,OAAAA;GAEvB,IAAIC,YAAYD,SAAS;IACvB,IAAId,SAAST,WACXS,OAAO,EAAE,GAAGT,UAAU;IAGxBS,KAAK/B,MAAM;KAAE,GAAGkB;MAAQuB,QAAQK;IAAQ;GAC1C;EACF;EAEA,OAAOf;CACT;CAEAD,KAAK,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","writtenAfter","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","fact","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 {\n type Instances,\n type Model,\n resolveAlias,\n setOwn,\n writtenAfter,\n} 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 | '~track'\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['~track'](key);\n\n model['~react'](parent, 'deleted', {\n to: 'deleteWhere',\n fn: ids => state => {\n const parentId = parentOf(state);\n\n return (\n typeof parentId === 'string' &&\n ids.includes(parentId) &&\n // Ребёнок, записанный уже после удаления, относится к новому родителю с тем же id.\n !writtenAfter(state, key, ids)\n );\n },\n });\n\n model['~react'](parent, 'renamed', {\n to: 'patch',\n fn: fact => instances => {\n const { from, to } = fact;\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n if (parentOf(state) === from && !writtenAfter(state, key, fact)) {\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 from['~track'](field);\n\n const rewrite = (\n instances: Instances<State>,\n fact: object,\n change: (value: unknown) => unknown,\n ): Instances<State> => {\n let next = instances;\n\n for (const [id, state] of Object.entries(instances)) {\n // Ссылка, записанная уже после факта, указывает на новый экземпляр с тем же id.\n if (writtenAfter(state, field, fact)) {\n continue;\n }\n\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, deleted, 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: fact => instances => {\n const { from: before, to } = fact;\n const replace = (item: unknown) =>\n read(item) === before ? move(item, to) : item;\n\n return rewrite(instances, fact, 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;;wFC+DA,SAAgBM,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,WAAWd,QAAQQ,WAAAA;CAEzB,MAAMK,aAAab,QAAQO,MAAAA;CAG3B,MAAMQ,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