@effector-tools/models 0.0.0-stage → 0.2.4

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.
@@ -0,0 +1,428 @@
1
+ let effector = require("effector");
2
+ // lib/model.ts
3
+ /** Настоящий id по алиасу; id без алиаса возвращается как есть. */ function resolveAlias(aliases, id) {
4
+ return Object.hasOwn(aliases, id) ? aliases[id] : id;
5
+ }
6
+ /**
7
+ * Записывает собственное свойство. Обычное присваивание для ключа `__proto__` меняет прототип,
8
+ * а не добавляет ключ, — id и алиасы приходят снаружи и могут быть любыми строками.
9
+ */ function setOwn(target, key, value) {
10
+ Object.defineProperty(target, key, {
11
+ value,
12
+ enumerable: true,
13
+ writable: true,
14
+ configurable: true
15
+ });
16
+ }
17
+ const toList = (ids) => typeof ids === "string" ? [ids] : ids;
18
+ const toArray = (value) => Array.isArray(value) ? value : [value];
19
+ const withoutAliases = (aliases, isRemoved) => {
20
+ let next = aliases;
21
+ for (const [alias, id] of Object.entries(aliases)) if (isRemoved(alias, id)) {
22
+ if (next === aliases) next = { ...aliases };
23
+ delete next[alias];
24
+ }
25
+ return next;
26
+ };
27
+ /**
28
+ * Состояние модели из словаря экземпляров — для засева `$state` в тестах и при гидрации.
29
+ * Порядок id берётся из порядка ключей.
30
+ */ function modelState(instances, aliases = {}) {
31
+ return {
32
+ ids: Object.keys(instances),
33
+ instances,
34
+ aliases
35
+ };
36
+ }
37
+ const factsOf = /* @__PURE__ */ new WeakMap();
38
+ function takeFacts(state) {
39
+ const facts = factsOf.get(state) ?? [];
40
+ factsOf.delete(state);
41
+ return facts;
42
+ }
43
+ function mergeFacts(facts) {
44
+ const merged = [];
45
+ const gone = facts.flatMap((fact) => fact.type === "deleted" ? fact.payload : []);
46
+ if (gone.length > 0) merged.push({
47
+ type: "deleted",
48
+ payload: [...new Set(gone)]
49
+ });
50
+ for (const type of [
51
+ "renamed",
52
+ "missed",
53
+ "applied"
54
+ ]) {
55
+ const found = facts.find((fact) => fact.type === type);
56
+ if (found) merged.push(found);
57
+ }
58
+ return merged;
59
+ }
60
+ function commit(state, next, facts = []) {
61
+ const ids = next.ids ?? state.ids;
62
+ const instances = next.instances ?? state.instances;
63
+ const aliases = next.aliases ?? state.aliases;
64
+ if (ids === state.ids && instances === state.instances && aliases === state.aliases && facts.length === 0) return state;
65
+ const result = {
66
+ ids,
67
+ instances,
68
+ aliases
69
+ };
70
+ if (facts.length > 0) factsOf.set(result, facts);
71
+ return result;
72
+ }
73
+ let now = 0;
74
+ const writtenAt = /* @__PURE__ */ new WeakMap();
75
+ const factAt = /* @__PURE__ */ new WeakMap();
76
+ /** Поле экземпляра записано после факта (payload события `deleted` или `renamed`). */ function writtenAfter(instance, field, fact) {
77
+ const at = factAt.get(fact);
78
+ return at !== void 0 && (writtenAt.get(instance)?.[field] ?? 0) > at;
79
+ }
80
+ function applyTo(state, action, ids, onWrite, defaults, fn) {
81
+ const { instances, aliases } = state;
82
+ let next = instances;
83
+ const missing = [];
84
+ const added = [];
85
+ const changes = [];
86
+ for (const id of new Set(toList(ids).map((item) => resolveAlias(aliases, item)))) {
87
+ const exists = Object.hasOwn(instances, id);
88
+ if (!exists && defaults === void 0) {
89
+ missing.push(id);
90
+ continue;
91
+ }
92
+ const current = exists ? instances[id] : defaults;
93
+ const updated = fn(current);
94
+ if (updated !== current) {
95
+ if (next === instances) next = { ...instances };
96
+ setOwn(next, id, updated);
97
+ onWrite(exists ? current : void 0, updated);
98
+ changes.push({
99
+ id,
100
+ prev: current,
101
+ next: updated
102
+ });
103
+ if (!exists) added.push(id);
104
+ }
105
+ }
106
+ const facts = [];
107
+ if (missing.length > 0) facts.push({
108
+ type: "missed",
109
+ payload: {
110
+ action,
111
+ ids: missing
112
+ }
113
+ });
114
+ if (changes.length > 0) facts.push({
115
+ type: "applied",
116
+ payload: {
117
+ action,
118
+ changes
119
+ }
120
+ });
121
+ return commit(state, {
122
+ ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
123
+ instances: next
124
+ }, facts);
125
+ }
126
+ function removeFrom(state, ids) {
127
+ const real = [...new Set(ids)].filter((id) => Object.hasOwn(state.instances, id));
128
+ if (real.length === 0) return state;
129
+ const instances = { ...state.instances };
130
+ for (const id of real) delete instances[id];
131
+ const names = Object.keys(state.aliases).filter((alias) => real.includes(state.aliases[alias]));
132
+ return commit(state, {
133
+ ids: state.ids.filter((id) => !real.includes(id)),
134
+ instances,
135
+ aliases: withoutAliases(state.aliases, (alias) => names.includes(alias))
136
+ }, [{
137
+ type: "deleted",
138
+ payload: [...real, ...names]
139
+ }]);
140
+ }
141
+ function model(config) {
142
+ const { name, defaults } = config;
143
+ const reducers = config.events ?? {};
144
+ const $state = (0, effector.createStore)({
145
+ ids: [],
146
+ instances: {},
147
+ aliases: {}
148
+ }, {
149
+ sid: `effector-models:${name}`,
150
+ name: `${name}/$state`
151
+ });
152
+ const $instances = $state.map((state) => state.instances);
153
+ const $aliases = $state.map((state) => state.aliases);
154
+ const $ids = $state.map((state) => state.ids);
155
+ const facts = $state.updates.filterMap((state) => {
156
+ const list = takeFacts(state);
157
+ return list.length > 0 ? list : void 0;
158
+ });
159
+ const factOf = (type) => facts.filterMap((list) => list.find((fact) => fact.type === type)?.payload);
160
+ const deleted = factOf("deleted");
161
+ const renamed = factOf("renamed");
162
+ const missed = factOf("missed");
163
+ const applied = factOf("applied");
164
+ const implicit = config.autoCreate ? defaults : void 0;
165
+ const hooks = {
166
+ deleted: [],
167
+ renamed: []
168
+ };
169
+ const settle = (before, after) => {
170
+ if (after === before) return before;
171
+ let current = after;
172
+ const queue = takeFacts(current);
173
+ const seen = [];
174
+ while (queue.length > 0) {
175
+ const fact = queue.shift();
176
+ seen.push(fact);
177
+ if (fact.type === "missed" || fact.type === "applied") continue;
178
+ for (const hook of hooks[fact.type]) {
179
+ const next = hook(current, fact.payload);
180
+ if (next !== current) {
181
+ queue.push(...takeFacts(next));
182
+ current = next;
183
+ }
184
+ }
185
+ }
186
+ if (seen.length > 0) {
187
+ const merged = mergeFacts(seen);
188
+ for (const fact of merged) if (fact.type === "deleted" || fact.type === "renamed") factAt.set(fact.payload, now);
189
+ factsOf.set(current, merged);
190
+ }
191
+ return current;
192
+ };
193
+ const on = (clock, reducer) => {
194
+ $state.on(clock, (state, payload) => {
195
+ now += 1;
196
+ return settle(state, reducer(state, payload));
197
+ });
198
+ };
199
+ const tracked = /* @__PURE__ */ new Set();
200
+ const stamp = (prev, next) => {
201
+ if (tracked.size === 0) return;
202
+ const before = prev === void 0 ? void 0 : writtenAt.get(prev);
203
+ const record = {};
204
+ for (const field of tracked) record[field] = prev !== void 0 && prev[field] === next[field] ? before?.[field] ?? 0 : now;
205
+ writtenAt.set(next, record);
206
+ };
207
+ const create = (0, effector.createEvent)({ name: `${name}/create` });
208
+ const reduceCreate = (state, params) => {
209
+ const items = toArray(params);
210
+ if (items.length === 0) return state;
211
+ const instances = { ...state.instances };
212
+ const added = [];
213
+ for (const { id, data } of items) {
214
+ if (!Object.hasOwn(instances, id)) added.push(id);
215
+ const instance = {
216
+ ...defaults,
217
+ ...data
218
+ };
219
+ setOwn(instances, id, instance);
220
+ stamp(void 0, instance);
221
+ }
222
+ return commit(state, {
223
+ ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
224
+ instances,
225
+ aliases: withoutAliases(state.aliases, (alias) => items.some((item) => item.id === alias))
226
+ });
227
+ };
228
+ on(create, reduceCreate);
229
+ const upsert = (0, effector.createEvent)({ name: `${name}/upsert` });
230
+ const reduceUpsert = (state, params) => {
231
+ const items = toArray(params);
232
+ if (items.length === 0) return state;
233
+ const instances = { ...state.instances };
234
+ const added = [];
235
+ for (const { id: given, data } of items) {
236
+ const id = resolveAlias(state.aliases, given);
237
+ const exists = Object.hasOwn(instances, id);
238
+ if (!exists) added.push(id);
239
+ const prev = exists ? instances[id] : void 0;
240
+ const instance = {
241
+ ...prev ?? defaults,
242
+ ...data
243
+ };
244
+ setOwn(instances, id, instance);
245
+ stamp(prev, instance);
246
+ }
247
+ return commit(state, {
248
+ ids: added.length > 0 ? [...state.ids, ...added] : state.ids,
249
+ instances
250
+ });
251
+ };
252
+ on(upsert, reduceUpsert);
253
+ const update = (0, effector.createEvent)({ name: `${name}/update` });
254
+ on(update, (state, { id, data }) => applyTo(state, "update", id, stamp, implicit, (instance) => typeof data === "function" ? data(instance) : {
255
+ ...instance,
256
+ ...data
257
+ }));
258
+ const remove = (0, effector.createEvent)({ name: `${name}/delete` });
259
+ const reduceDelete = (state, ids) => removeFrom(state, toList(ids).map((id) => resolveAlias(state.aliases, id)));
260
+ on(remove, reduceDelete);
261
+ const rename = (0, effector.createEvent)({ name: `${name}/rename` });
262
+ on(rename, (state, params) => {
263
+ const from = resolveAlias(state.aliases, params.from);
264
+ const { to } = params;
265
+ if (!Object.hasOwn(state.instances, from)) return commit(state, {}, [{
266
+ type: "missed",
267
+ payload: {
268
+ action: "rename",
269
+ ids: [from]
270
+ }
271
+ }]);
272
+ if (from === to) return state;
273
+ const instances = { ...state.instances };
274
+ setOwn(instances, to, state.instances[from]);
275
+ delete instances[from];
276
+ const ids = state.ids.filter((id) => id !== to).map((id) => id === from ? to : id);
277
+ let aliases = withoutAliases(state.aliases, (alias) => alias === to);
278
+ for (const [alias, id] of Object.entries(aliases)) if (id === from) {
279
+ if (aliases === state.aliases) aliases = { ...state.aliases };
280
+ setOwn(aliases, alias, to);
281
+ }
282
+ return commit(state, {
283
+ ids,
284
+ instances,
285
+ aliases
286
+ }, [{
287
+ type: "renamed",
288
+ payload: {
289
+ from,
290
+ to
291
+ }
292
+ }]);
293
+ });
294
+ const clear = (0, effector.createEvent)({ name: `${name}/clear` });
295
+ on(clear, (state) => {
296
+ const gone = [...state.ids, ...Object.keys(state.aliases)];
297
+ return gone.length === 0 ? state : commit(state, {
298
+ ids: [],
299
+ instances: {},
300
+ aliases: {}
301
+ }, [{
302
+ type: "deleted",
303
+ payload: gone
304
+ }]);
305
+ });
306
+ const alias = (0, effector.createEvent)({ name: `${name}/alias` });
307
+ on(alias, (state, params) => {
308
+ let aliases = state.aliases;
309
+ for (const { alias: given, id } of toArray(params)) {
310
+ const target = resolveAlias(aliases, id);
311
+ if (!Object.hasOwn(state.instances, target) || Object.hasOwn(state.instances, given) || Object.hasOwn(aliases, given) && aliases[given] === target) continue;
312
+ if (aliases === state.aliases) aliases = { ...state.aliases };
313
+ setOwn(aliases, given, target);
314
+ }
315
+ return commit(state, { aliases });
316
+ });
317
+ const unalias = (0, effector.createEvent)({ name: `${name}/unalias` });
318
+ on(unalias, (state, ids) => {
319
+ const removed = toList(ids);
320
+ return commit(state, { aliases: withoutAliases(state.aliases, (item) => removed.includes(item)) });
321
+ });
322
+ const applyLink = (state, target, payload) => {
323
+ switch (target.to) {
324
+ case "create":
325
+ case "upsert": {
326
+ const params = target.fn(payload);
327
+ if (params === void 0) return state;
328
+ return target.to === "create" ? reduceCreate(state, params) : reduceUpsert(state, params);
329
+ }
330
+ case "delete": {
331
+ const ids = target.fn(payload);
332
+ return ids === void 0 ? state : reduceDelete(state, ids);
333
+ }
334
+ case "deleteWhere": {
335
+ const isDeleted = target.fn(payload);
336
+ return removeFrom(state, state.ids.filter((id) => isDeleted(state.instances[id], id)));
337
+ }
338
+ case "deleteSelected": return removeFrom(state, target.fn(payload)(state));
339
+ case "applySelected": {
340
+ const { action, select, change } = target.fn(payload);
341
+ return applyTo(state, action, select(state), stamp, void 0, change);
342
+ }
343
+ case "patch": {
344
+ const instances = target.fn(payload)(state.instances);
345
+ if (instances !== state.instances) for (const id of state.ids) {
346
+ const prev = state.instances[id];
347
+ const next = instances[id];
348
+ if (next !== prev) {
349
+ const record = writtenAt.get(prev);
350
+ if (record) writtenAt.set(next, record);
351
+ }
352
+ }
353
+ return commit(state, { instances });
354
+ }
355
+ }
356
+ };
357
+ const link = (clock, target, own = false) => {
358
+ on(own ? clock : clock.map((payload) => payload), (state, payload) => applyLink(state, target, payload));
359
+ };
360
+ const react = (source, fact, target) => {
361
+ const own = fact === "deleted" ? deleted : renamed;
362
+ if (source[fact] === own) hooks[fact].push((state, payload) => applyLink(state, target, payload));
363
+ else link(source[fact], target);
364
+ };
365
+ const events = {};
366
+ for (const [action, reducer] of Object.entries(reducers)) {
367
+ const event = (0, effector.createEvent)({ name: `${name}/${action}` });
368
+ on(event, (state, { id, payload }) => applyTo(state, action, id, stamp, implicit, (instance) => reducer(instance, payload)));
369
+ events[action] = event;
370
+ }
371
+ return {
372
+ name,
373
+ defaults,
374
+ $state,
375
+ $instances,
376
+ $ids,
377
+ $aliases,
378
+ alias,
379
+ unalias,
380
+ create,
381
+ upsert,
382
+ update,
383
+ delete: remove,
384
+ deleted,
385
+ rename,
386
+ renamed,
387
+ clear,
388
+ events,
389
+ missed,
390
+ applied,
391
+ "~link": link,
392
+ "~react": react,
393
+ "~reducers": reducers,
394
+ "~track": (field) => {
395
+ tracked.add(field);
396
+ }
397
+ };
398
+ }
399
+ Object.defineProperty(exports, "model", {
400
+ enumerable: true,
401
+ get: function() {
402
+ return model;
403
+ }
404
+ });
405
+ Object.defineProperty(exports, "modelState", {
406
+ enumerable: true,
407
+ get: function() {
408
+ return modelState;
409
+ }
410
+ });
411
+ Object.defineProperty(exports, "resolveAlias", {
412
+ enumerable: true,
413
+ get: function() {
414
+ return resolveAlias;
415
+ }
416
+ });
417
+ Object.defineProperty(exports, "setOwn", {
418
+ enumerable: true,
419
+ get: function() {
420
+ return setOwn;
421
+ }
422
+ });
423
+ Object.defineProperty(exports, "writtenAfter", {
424
+ enumerable: true,
425
+ get: function() {
426
+ return writtenAfter;
427
+ }
428
+ });