@olovyannikov/effector-models 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,98 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1
4
+
5
+ ### Added
6
+
7
+ - **React**: `useModel(model, id, related?)` — one hook for one instance:
8
+ `state`, `exists`, the real `id`, bound `events`, `update` and `remove`,
9
+ plus the values requested from relations under your own keys. A relation
10
+ gives the ids of the children; `childrenOf(relation, selector?, isEqual?)`
11
+ gives the children or a value selected from them. The existing hooks stay
12
+ as its building blocks.
13
+
14
+ ## 0.1.0
15
+
16
+ The first release on the `latest` dist-tag. The code is the same as in
17
+ `1.0.0-alpha.3`.
18
+
19
+ Versioning moves to `0.x`: the API may still change, and a breaking change
20
+ bumps the minor version (`0.2.0`), so `^0.1.0` only receives compatible
21
+ updates. The `1.0.0-alpha.*` versions are superseded by this one, even
22
+ though they sort higher — install `@olovyannikov/effector-models` without a
23
+ tag.
24
+
25
+ ## 1.0.0-alpha.3
26
+
27
+ ### Added
28
+
29
+ - **Aliases in the core.** Every model has `$aliases`, `alias` and `unalias`.
30
+ `update`, `upsert`, `delete`, `rename` and instance events accept an alias
31
+ wherever they accept an id; so do `useInstance`, `useInstanceEvents`,
32
+ `useChildIds`, `useChildren` and `useUnionInstance`.
33
+ - **Facts**: `model.deleted` (real ids of the deleted instances followed by
34
+ their aliases) and `model.renamed` (`{ from, to }` with the real `from`).
35
+ They fire only when something was actually deleted or moved.
36
+ - Relations see through aliases: a child or a reference that stores an alias
37
+ of its target is cascaded and cleaned up like one that stores the real id.
38
+ `$idsByParent` is always keyed by the real parent id.
39
+ - `union.$aliases`; `Child` has a `parent` field.
40
+
41
+ ### Changed
42
+
43
+ - `upsert` with an alias id extends the aliased instance instead of creating
44
+ a new one. `create` still displaces the alias.
45
+ - `rename` to the instance's own id is a no-op. It used to delete the
46
+ instance.
47
+ - `ModelLike` also requires `$aliases`, `deleted` and `renamed`.
48
+ - `useUnionInstance` returns the real id when the reference holds an alias.
49
+
50
+ ### Deprecated
51
+
52
+ - `aliases(model)` is a thin wrapper over the model now: `add` is
53
+ `model.alias`, `remove` is `model.unalias`, `resolved(event)` returns the
54
+ event itself. The sid of the alias store did not change, so serialized
55
+ state from alpha.2 hydrates as is.
56
+
57
+ ## 1.0.0-alpha.2
58
+
59
+ ### Added
60
+
61
+ - **Aliases**: `aliases(model)` — one instance reachable by several ids:
62
+ `$aliases`, `add`, `remove`, and `resolved(event)` to write through an
63
+ alias. Aliases follow `delete`, `clear` and `rename` of the instances.
64
+ `resolveAlias(aliases, id)` is exported for use in `sample`.
65
+ - **React**: `useResolvedId(aliases, id)` — the real id for an id that may
66
+ be an alias.
67
+
68
+ ## 1.0.0-alpha.1
69
+
70
+ ### Added
71
+
72
+ - **Relations** between models. A reference is an ordinary field with an id;
73
+ a relation keeps such fields consistent.
74
+ - `child({ parent, model, key })` — children are deleted together with the
75
+ parent and follow its `rename`; `$idsByParent` index.
76
+ - Trees: a model can be a `child` of itself with a nullable key. Deleting a
77
+ node deletes its whole branch.
78
+ - `ref({ from, field, to })` — a field with one id or a list. Deleted
79
+ targets disappear from references, renamed ones are renamed.
80
+ - `union({ ... })` — several models as one collection addressed by
81
+ `{ kind, id }`, with `create`, `upsert` and `delete` routed to the model
82
+ of the kind. `ref` accepts a union as a target.
83
+ - **React hooks**: `useChildIds`, `useChildren` (the children of one parent
84
+ or an aggregate over them) and `useUnionInstance`.
85
+
86
+ ### Changed
87
+
88
+ - `exports` provide separate type declarations for ESM and CJS consumers.
89
+ - `engines.node` is declared: `>=18`.
90
+ - Peer ranges are bounded: `effector >=23.4.4 <24`,
91
+ `effector-react >=23.3.0 <24`.
92
+
93
+ ## 1.0.0-alpha.0
94
+
95
+ Initial release: `model` with immutable instances and synchronous reducers,
96
+ `create` / `upsert` / `update` / `delete` / `rename` / `clear`, the `missed`
97
+ event, and the React hooks `useInstance`, `useInstanceIds`,
98
+ `useInstanceEvents`.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 movpushmov
4
+ Copyright (c) 2026 Ilya Olovyannikov
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,318 @@
1
- # Temporary Holding Version
1
+ # @olovyannikov/effector-models
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Keyed models for [Effector](https://effector.dev): a collection of instances addressed by id, where every instance is plain immutable data and instance events are pure reducers.
4
+
5
+ Fork of [`@effector-kit/models`](https://github.com/movpushmov/effector-kit) by movpushmov, redesigned around one goal: **behave like ordinary Effector units**.
6
+
7
+ | | `@effector-kit/models` 0.4 | this package |
8
+ | --------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------- |
9
+ | Write through instance event | async effect, lands after `sample` of the same tick | synchronous, visible in the same tick |
10
+ | Instance data | mutated in place, `$instances` keeps its reference | immutable; untouched instances keep their reference |
11
+ | `map` / `combine` / `useStoreMap` over `$instances` | miss writes | just work |
12
+ | Runtime | global context, writes into `scope.reg` | public Effector API only |
13
+ | `fork({ values })` / `serialize` | `$instances` read-only in types, instance stores `serialize: 'ignore'` | one `$instances` store with sid `effector-models:<name>` |
14
+ | Contract defaults on `create` | not applied | applied |
15
+ | `create` over existing id | silently replaces | `create` replaces, `upsert` merges |
16
+ | Write to missing instance | silent `Promise.reject` | ignored and reported via `missed` |
17
+ | React `useModel(lens)` | re-renders on any instance change, new object every render | subscribed to its own instance, stable reference, selector |
18
+
19
+ `child`, `ref` and `union` are available as [relations](#relations) between models: plain data plus integrity rules. Aliases are built into the model: see [aliases](#aliases--one-instance-several-ids). Not carried over: `fn` with arbitrary graphs inside an instance — side effects stay outside, as usual in Effector.
20
+
21
+ Documentation, a step-by-step tutorial and live examples: <https://olovyannikov.github.io/effector-kit/guide/keyed-models> (also in Russian).
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ pnpm add @olovyannikov/effector-models effector
27
+ # React bindings
28
+ pnpm add effector-react react
29
+ ```
30
+
31
+ ## Model
32
+
33
+ ```ts
34
+ import { model } from '@olovyannikov/effector-models';
35
+
36
+ interface Document {
37
+ documentId: string | null;
38
+ pending: Patch | null;
39
+ failed: boolean;
40
+ }
41
+
42
+ const defaults: Document = { documentId: null, pending: null, failed: false };
43
+
44
+ export const DocumentModel = model({
45
+ name: 'document', // unique: sid of $instances is `effector-models:document`
46
+ defaults,
47
+ events: {
48
+ patched: (doc, patch: Patch) => ({
49
+ ...doc,
50
+ pending: merge(doc.pending, patch),
51
+ failed: false,
52
+ }),
53
+ sent: doc => ({ ...doc, pending: null }),
54
+ },
55
+ });
56
+ ```
57
+
58
+ A reducer returning the same object means "nothing changed": no store update, no re-render.
59
+
60
+ ## API
61
+
62
+ | Unit | Payload | Behaviour |
63
+ | --------------- | -------------------------------------------------- | --------------------------------------------------------------------------------- |
64
+ | `$instances` | — | `Record<id, State>`, writable, has sid |
65
+ | `$ids` | — | `string[]` |
66
+ | `create` | `{ id, data? }` or array | creates with defaults; replaces existing id |
67
+ | `upsert` | `{ id, data? }` or array | merges into existing or creates with defaults |
68
+ | `update` | `{ id, data: Partial<State> \| (state) => State }` | existing only |
69
+ | `delete` | `id` or `id[]` | |
70
+ | `rename` | `{ from, to }` | moves instance in one step (e.g. draft → created document) |
71
+ | `clear` | — | |
72
+ | `events.<name>` | `{ id \| id[], payload }` | applies reducer synchronously |
73
+ | `missed` | `{ action, ids }` | writes addressed to instances that do not exist |
74
+ | `deleted` | `string[]` | fact: real ids of deleted instances, then their aliases |
75
+ | `renamed` | `{ from, to }` | fact: the instance moved, `from` is the real id |
76
+ | `$aliases` | — | `Record<alias, id>`, has a sid; see [aliases](#aliases--one-instance-several-ids) |
77
+ | `alias` | `{ alias, id }` or an array | adds aliases to existing instances |
78
+ | `unalias` | `alias` or `alias[]` | removes aliases, instances stay |
79
+
80
+ ```ts
81
+ sample({
82
+ clock: saved,
83
+ fn: patch => ({ id: documentId, payload: patch }),
84
+ target: DocumentModel.events.patched,
85
+ });
86
+
87
+ // same tick: this sample already sees the patched instance
88
+ sample({
89
+ clock: saved,
90
+ source: DocumentModel.$instances,
91
+ fn: instances => instances[documentId]?.pending,
92
+ target: $pending,
93
+ });
94
+ ```
95
+
96
+ Tests seed instances like any store: `fork({ values: [[DocumentModel.$instances, { a: { ... } }]] })`.
97
+
98
+ ## Relations
99
+
100
+ Relations connect models without changing what an instance is: a reference is an ordinary field with an id, and a relation only keeps those fields consistent.
101
+
102
+ ### `child` — owned instances
103
+
104
+ Children store the id of their parent in a field and are deleted together with it.
105
+
106
+ ```ts
107
+ import { child, model } from '@olovyannikov/effector-models';
108
+
109
+ const Todos = model({ name: 'todos', defaults: { title: '' } });
110
+ const Subtasks = model({
111
+ name: 'subtasks',
112
+ defaults: { todoId: '', title: '', done: false },
113
+ events: {
114
+ toggled: subtask => ({ ...subtask, done: !subtask.done }),
115
+ },
116
+ });
117
+
118
+ const subtasks = child({ parent: Todos, model: Subtasks, key: 'todoId' });
119
+
120
+ subtasks.$idsByParent; // Store<Record<todoId, subtaskId[]>>, in creation order
121
+ ```
122
+
123
+ - `parent.delete` / `parent.clear` delete the children
124
+ - `parent.rename` moves the children to the new parent id
125
+ - children are created like any other instance: `Subtasks.create({ id, data: { todoId } })`
126
+
127
+ A model can be a child of itself — that is a tree of any depth. The key is
128
+ `null` for a root, and deleting a node deletes its whole branch:
129
+
130
+ ```ts
131
+ const Nodes = model({
132
+ name: 'nodes',
133
+ defaults: { parentId: null as string | null, title: '' },
134
+ });
135
+
136
+ const nodes = child({ parent: Nodes, model: Nodes, key: 'parentId' });
137
+ ```
138
+
139
+ ### `ref` — tracked instances
140
+
141
+ A field that points to instances living in another model: one id (`string | null`) or a list (`string[]`).
142
+
143
+ ```ts
144
+ import { ref } from '@olovyannikov/effector-models';
145
+
146
+ const Dashboards = model({
147
+ name: 'dashboards',
148
+ defaults: { selected: [] as string[], pinned: null as string | null },
149
+ });
150
+
151
+ ref({ from: Dashboards, field: 'selected', to: Counters });
152
+ ref({ from: Dashboards, field: 'pinned', to: Counters });
153
+ ```
154
+
155
+ - a deleted instance disappears from lists, a single reference becomes `null`
156
+ - a renamed instance is renamed in references
157
+ - instances that did not reference it keep their object reference
158
+
159
+ ### `union` — several models as one collection
160
+
161
+ An instance is addressed by `{ kind, id }`.
162
+
163
+ ```ts
164
+ import { ref, union } from '@olovyannikov/effector-models';
165
+
166
+ const passengers = union({ adult: Adults, kid: Kids });
167
+
168
+ passengers.$instances; // Store<{ adult: Record<id, Adult>; kid: Record<id, Kid> }>
169
+ passengers.create({ kind: 'adult', id: 'p2', data: { name: 'Ann' } }); // routed to Adults.create
170
+ passengers.delete({ kind: 'kid', id: 'p1' }); // routed to Kids.delete
171
+
172
+ type Passenger = { kind: 'adult'; id: string } | { kind: 'kid'; id: string };
173
+
174
+ const Bookings = model({
175
+ name: 'bookings',
176
+ defaults: { passengers: [] as Passenger[] },
177
+ });
178
+
179
+ // References to a union are kept consistent the same way.
180
+ ref({ from: Bookings, field: 'passengers', to: passengers });
181
+ ```
182
+
183
+ ### Aliases — one instance, several ids
184
+
185
+ One instance reachable by several ids — a route id next to the server id.
186
+ The instance is still stored once; aliases live in the model, in `$aliases`,
187
+ and follow the life of instances.
188
+
189
+ ```ts
190
+ Chats.alias({ alias: 'route-id', id: 'server-id' });
191
+ Chats.$aliases; // Store<Record<alias, id>>, has a sid
192
+
193
+ // Everything that takes an id takes an alias.
194
+ Chats.events.renamed({ id: 'route-id', payload: 'New title' });
195
+ Chats.update({ id: 'route-id', data: { title: 'New title' } });
196
+ Chats.delete('route-id');
197
+
198
+ Chats.unalias('route-id'); // the instance stays
199
+ ```
200
+
201
+ ```tsx
202
+ const chat = useInstance(Chats, routeId);
203
+ const { renamed } = useInstanceEvents(Chats, routeId);
204
+ const messageIds = useChildIds(messages, routeId);
205
+ ```
206
+
207
+ - `update`, `upsert`, `delete`, `rename`, instance events and all hooks
208
+ resolve aliases; `create` does not — an instance created with the id of an
209
+ alias displaces the alias, a real id always wins
210
+ - deleting or clearing instances removes their aliases, `rename` moves them
211
+ - an alias to a missing instance, or with the id of an existing one, is not
212
+ created
213
+ - relations see through aliases: a child or a reference may store an alias
214
+ of its target and is still cascaded and cleaned up
215
+ - `unalias` does not touch references that store the alias — keep real ids
216
+ in data when you can; `useResolvedId(model, id)` and
217
+ `resolveAlias(aliases, id)` give the real id
218
+
219
+ To react to changes, subscribe to the facts instead of the commands:
220
+ `model.deleted` carries the real ids of deleted instances followed by their
221
+ aliases, `model.renamed` carries `{ from, to }` with the real `from`.
222
+
223
+ Use `rename` when an instance simply moves to a new id, and aliases when
224
+ both ids must keep working.
225
+
226
+ ## React
227
+
228
+ `useModel` gathers everything a component needs about one instance:
229
+
230
+ ```tsx
231
+ import {
232
+ childrenOf,
233
+ useInstanceIds,
234
+ useModel,
235
+ } from '@olovyannikov/effector-models/react';
236
+
237
+ function TodoItem({ id }: { id: string }) {
238
+ // One hook for one instance: state, events, writes and its children.
239
+ const todo = useModel(Todos, id, {
240
+ subtaskIds: subtasks,
241
+ done: childrenOf(subtasks, countCompleted),
242
+ });
243
+
244
+ if (!todo.state) return null;
245
+
246
+ return (
247
+ <li>
248
+ <label>
249
+ <input
250
+ type="checkbox"
251
+ checked={todo.state.completed}
252
+ onChange={() => todo.events.toggled()}
253
+ />
254
+ {todo.state.title} ({todo.done}/{todo.subtaskIds.length})
255
+ </label>
256
+ <button onClick={() => todo.remove()}>×</button>
257
+ </li>
258
+ );
259
+ }
260
+
261
+ function TodoList() {
262
+ return useInstanceIds(Todos).map(id => <TodoItem key={id} id={id} />);
263
+ }
264
+ ```
265
+
266
+ | Field | Value |
267
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
268
+ | `state` | the instance or `undefined` |
269
+ | `exists` | whether the instance exists |
270
+ | `id` | the real id, also when an alias was passed |
271
+ | `events.<name>(payload)` | instance events bound to the id and the scope |
272
+ | `update(data)` | a patch or a function, as in `model.update` |
273
+ | `remove()` | deletes the instance |
274
+ | your keys | a relation gives the ids of the children, `childrenOf(relation)` the children, `childrenOf(relation, selector, isEqual?)` a value selected from them |
275
+
276
+ The component rerenders when the instance changes or when a requested value
277
+ changes — an aggregate only when its result does. The actions keep their
278
+ references while the id is the same. Keep the set of keys constant between
279
+ renders, and pass a stable selector to `childrenOf` to avoid re-subscribing.
280
+
281
+ The hooks below are the parts `useModel` is made of. Use them when a
282
+ component needs one thing only — for example `useInstance` with a selector to
283
+ subscribe to a single field.
284
+
285
+ ```tsx
286
+ import {
287
+ useInstance,
288
+ useInstanceEvents,
289
+ useInstanceIds,
290
+ } from '@olovyannikov/effector-models/react';
291
+
292
+ const Slide = ({ id }: { id: string }) => {
293
+ const title = useInstance(SlideModel, id, slide => slide?.title);
294
+ const { focused } = useInstanceEvents(SlideModel, id);
295
+ // re-renders only when this slide's title changes
296
+ };
297
+
298
+ const Slides = () =>
299
+ useInstanceIds(SlideModel).map(id => <Slide key={id} id={id} />);
300
+ ```
301
+
302
+ - `useInstance(model, id)` — instance or `undefined`, `id` may be an alias; `useInstance(model, id, selector, isEqual?)` — selected value. Pass a stable selector to avoid re-subscribing.
303
+ - `useInstanceIds(model)` — re-renders only when the set or order of ids changes.
304
+ - `useInstanceEvents(model, id)` — instance events bound to the id and to the scope from `Provider`.
305
+ - `useChildIds(relation, parentId)` — ids of the children of one parent; re-renders only when their set or order changes.
306
+ - `useChildren(relation, parentId)` — the children themselves; `useChildren(relation, parentId, selector, isEqual?)` — an aggregate over them (a total, a counter) that re-renders only when the selected value changes.
307
+ - `useResolvedId(model, id)` — the real id for an id that may be an alias. The other hooks resolve aliases themselves; use it when the real id is needed as data, for example as a `key`.
308
+ - `useUnionInstance(union, { kind, id })` — `{ kind, id, state }` or `undefined`; `kind` narrows the type of `state`.
309
+
310
+ ## Releasing
311
+
312
+ Bump `version` in `package.json`, describe the changes in `CHANGELOG.md` and merge into `main`. The `models-next` 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`.
313
+
314
+ While the package is on `0.x`, a breaking change bumps the minor version and everything else bumps the patch.
315
+
316
+ ## License
317
+
318
+ MIT. Original work © movpushmov.
package/dist/index.cjs ADDED
@@ -0,0 +1,197 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_model = require("./model-iPgSwajA.cjs");
3
+ let effector = require("effector");
4
+ // lib/aliases.ts
5
+ /**
6
+ * @deprecated Алиасы встроены в модель: `model.$aliases`, `model.alias`, `model.unalias`,
7
+ * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.
8
+ */ function aliases(model) {
9
+ return {
10
+ $aliases: model.$aliases,
11
+ add: model.alias,
12
+ remove: model.unalias,
13
+ resolved: (target) => target
14
+ };
15
+ }
16
+ // lib/relations.ts
17
+ /** Несколько моделей как одна коллекция: экземпляр адресуется парой `{ kind, id }`. */ function union(models) {
18
+ const stores = {};
19
+ const aliasStores = {};
20
+ for (const [kind, member] of Object.entries(models)) {
21
+ stores[kind] = member.$instances;
22
+ aliasStores[kind] = member.$aliases;
23
+ }
24
+ const $aliases = (0, effector.combine)(aliasStores);
25
+ const $instances = (0, effector.combine)(stores);
26
+ const remove = (0, effector.createEvent)();
27
+ const create = (0, effector.createEvent)();
28
+ const upsert = (0, effector.createEvent)();
29
+ const paramsOf = (params, kind) => (Array.isArray(params) ? params : [params]).filter((item) => item.kind === kind).map(({ id, data }) => data === void 0 ? { id } : {
30
+ id,
31
+ data
32
+ });
33
+ for (const [kind, member] of Object.entries(models)) {
34
+ (0, effector.sample)({
35
+ clock: create,
36
+ filter: (params) => paramsOf(params, kind).length > 0,
37
+ fn: (params) => paramsOf(params, kind),
38
+ target: member.create
39
+ });
40
+ (0, effector.sample)({
41
+ clock: upsert,
42
+ filter: (params) => paramsOf(params, kind).length > 0,
43
+ fn: (params) => paramsOf(params, kind),
44
+ target: member.upsert
45
+ });
46
+ (0, effector.sample)({
47
+ clock: remove,
48
+ filter: (refs) => (Array.isArray(refs) ? refs : [refs]).some((ref) => ref.kind === kind),
49
+ fn: (refs) => (Array.isArray(refs) ? refs : [refs]).filter((ref) => ref.kind === kind).map((ref) => ref.id),
50
+ target: member.delete
51
+ });
52
+ }
53
+ return {
54
+ "~kind": "union",
55
+ models,
56
+ $instances,
57
+ $aliases,
58
+ create,
59
+ upsert,
60
+ delete: remove
61
+ };
62
+ }
63
+ function isUnion(value) {
64
+ return "~kind" in value && value["~kind"] === "union";
65
+ }
66
+ /**
67
+ * Дочерние экземпляры принадлежат родителю: хранят его id в поле `key`
68
+ * и удаляются вместе с ним. Переименование родителя переносит детей.
69
+ */ function child(config) {
70
+ const { parent, model, key } = config;
71
+ const parentOf = (state) => state[key];
72
+ const $idsByParent = (0, effector.combine)(model.$instances, parent.$aliases, (instances, aliases) => {
73
+ const index = {};
74
+ for (const [id, state] of Object.entries(instances)) {
75
+ const parentId = parentOf(state);
76
+ if (typeof parentId === "string") (index[require_model.resolveAlias(aliases, parentId)] ??= []).push(id);
77
+ }
78
+ return index;
79
+ });
80
+ const childrenOf = (instances, match) => Object.entries(instances).filter(([, state]) => {
81
+ const parentId = parentOf(state);
82
+ return typeof parentId === "string" && match(parentId);
83
+ }).map(([id]) => id);
84
+ const isTree = parent.$instances === model.$instances;
85
+ const descendantsOf = (instances, ids) => {
86
+ const found = /* @__PURE__ */ new Set();
87
+ let level = new Set(ids);
88
+ while (level.size > 0) {
89
+ const next = /* @__PURE__ */ new Set();
90
+ for (const id of childrenOf(instances, (parentId) => level.has(parentId))) if (!found.has(id)) {
91
+ found.add(id);
92
+ next.add(id);
93
+ }
94
+ level = isTree ? next : /* @__PURE__ */ new Set();
95
+ }
96
+ return [...found];
97
+ };
98
+ (0, effector.sample)({
99
+ clock: parent.deleted,
100
+ source: model.$instances,
101
+ filter: (instances, ids) => descendantsOf(instances, ids).length > 0,
102
+ fn: (instances, ids) => descendantsOf(instances, ids),
103
+ target: model.delete
104
+ });
105
+ if (!isTree) (0, effector.sample)({
106
+ clock: parent.clear,
107
+ source: model.$instances,
108
+ filter: (instances) => childrenOf(instances, () => true).length > 0,
109
+ fn: (instances) => childrenOf(instances, () => true),
110
+ target: model.delete
111
+ });
112
+ (0, effector.sample)({
113
+ clock: parent.renamed,
114
+ source: model.$instances,
115
+ filter: (instances, { from }) => childrenOf(instances, (parentId) => parentId === from).length > 0,
116
+ fn: (instances, { from, to }) => ({
117
+ id: childrenOf(instances, (parentId) => parentId === from),
118
+ data: { [key]: to }
119
+ }),
120
+ target: model.update
121
+ });
122
+ return {
123
+ model,
124
+ parent: { $aliases: parent.$aliases },
125
+ $idsByParent
126
+ };
127
+ }
128
+ function modelSignals(target, wrap, read) {
129
+ return {
130
+ removed: (0, effector.merge)([target.deleted.map((deleted) => (item) => {
131
+ const id = read(item);
132
+ return id !== void 0 && deleted.includes(id);
133
+ }), target.clear.map(() => (item) => read(item) !== void 0)]),
134
+ replaced: target.renamed.map(({ from, to }) => (item) => read(item) === from ? wrap(to) : item)
135
+ };
136
+ }
137
+ function targetSignals(target) {
138
+ if (!isUnion(target)) return modelSignals(target, (id) => id, (item) => typeof item === "string" ? item : void 0);
139
+ const members = Object.entries(target.models).map(([kind, member]) => modelSignals(member, (id) => ({
140
+ kind,
141
+ id
142
+ }), (item) => typeof item === "object" && item !== null && item.kind === kind ? item.id : void 0));
143
+ return {
144
+ removed: (0, effector.merge)(members.map((member) => member.removed)),
145
+ replaced: (0, effector.merge)(members.map((member) => member.replaced))
146
+ };
147
+ }
148
+ /**
149
+ * Ссылка на экземпляры, которые живут в другой модели (или объединении).
150
+ * Поле остаётся обычными данными; связь лишь поддерживает его целостность:
151
+ * удалённые экземпляры пропадают из ссылок, переименованные — переносятся.
152
+ */ function ref(config) {
153
+ const { from, field } = config;
154
+ const signals = targetSignals(config.to);
155
+ const rewrite = (instances, change) => {
156
+ let next = instances;
157
+ for (const [id, state] of Object.entries(instances)) {
158
+ const current = state[field];
159
+ const updated = change(current);
160
+ if (updated !== current) {
161
+ if (next === instances) next = { ...instances };
162
+ next[id] = {
163
+ ...state,
164
+ [field]: updated
165
+ };
166
+ }
167
+ }
168
+ return next;
169
+ };
170
+ (0, effector.sample)({
171
+ clock: signals.removed,
172
+ source: from.$instances,
173
+ fn: (instances, isRemoved) => rewrite(instances, (value) => {
174
+ if (Array.isArray(value)) return value.some(isRemoved) ? value.filter((item) => !isRemoved(item)) : value;
175
+ return value !== null && isRemoved(value) ? null : value;
176
+ }),
177
+ target: from.$instances
178
+ });
179
+ (0, effector.sample)({
180
+ clock: signals.replaced,
181
+ source: from.$instances,
182
+ fn: (instances, replace) => rewrite(instances, (value) => {
183
+ if (Array.isArray(value)) {
184
+ const replaced = value.map(replace);
185
+ return replaced.some((item, index) => item !== value[index]) ? replaced : value;
186
+ }
187
+ return value === null ? value : replace(value);
188
+ }),
189
+ target: from.$instances
190
+ });
191
+ }
192
+ exports.aliases = aliases;
193
+ exports.child = child;
194
+ exports.model = require_model.model;
195
+ exports.ref = ref;
196
+ exports.resolveAlias = require_model.resolveAlias;
197
+ exports.union = union;
@@ -0,0 +1,21 @@
1
+ import { EventCallable, Store } from "effector";
2
+ import { C as RenameParams, E as resolveAlias, S as Reducers, T as model, _ as Instances, a as Union, b as ModelConfig, c as UnionModels, d as ref, f as union, g as InstanceEventParams, h as Ids, i as RefConfig, l as UnionRef, m as CreateParams, n as ChildConfig, o as UnionCreateParams, p as AliasParams, r as ModelLike, s as UnionInstances, t as Child, u as child, v as Missed, w as UpdateParams, x as Reducer, y as Model } from "./relations-DXJ6slzh.cjs";
3
+ /** Часть модели, нужная алиасам. */
4
+ type AliasTarget = Pick<Model<object, Record<never, unknown>>, "$aliases" | "alias" | "unalias">;
5
+ interface Aliases {
6
+ /** Алиас → настоящий id экземпляра. */
7
+ readonly $aliases: Store<Record<string, string>>;
8
+ readonly add: EventCallable<AliasParams | AliasParams[]>;
9
+ readonly remove: EventCallable<Ids>;
10
+ /** Возвращает то же событие: события модели сами принимают алиасы. */
11
+ readonly resolved: <Params extends {
12
+ id: Ids;
13
+ }>(target: EventCallable<Params>) => EventCallable<Params>;
14
+ }
15
+ /**
16
+ * @deprecated Алиасы встроены в модель: `model.$aliases`, `model.alias`, `model.unalias`,
17
+ * а события и хуки принимают алиас вместо id. Обёртка оставлена для кода, написанного под alpha.2.
18
+ */
19
+ export declare function aliases(model: AliasTarget): Aliases;
20
+ export { type AliasParams, type AliasTarget, type Aliases, type Child, type ChildConfig, type CreateParams, type Ids, type InstanceEventParams, type Instances, type Missed, type Model, type ModelConfig, type ModelLike, type Reducer, type Reducers, type RefConfig, type RenameParams, type Union, type UnionCreateParams, type UnionInstances, type UnionModels, type UnionRef, type UpdateParams, child, model, ref, resolveAlias, union };
21
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../lib/aliases.ts"],"mappings":";;;KAKY,cAAc,KACxB,cAAc;UAIC;;WAEN,UAAU,MAAM;WAChB,KAAK,cAAc,cAAc;WACjC,QAAQ,cAAc;;WAEtB,WAAW;IAAiB,IAAI;KACvC,QAAQ,cAAc,YACnB,cAAc;;;;;;wBAOL,QAAQ,OAAO,cAAc"}