@aiao/rxdb-plugin-history 0.0.26 → 0.0.28

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/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { ENTITY_LOCAL_CREATE_EVENT as e, MergeBranchBeginEvent as t, MergeBranchCommitEvent as n, MergeBranchFailedEvent as r, REPOSITORY_SYNC_COMPLETE_EVENT as i, RxDBBranch as a, RxDBChange as o, RxDBError as s, RxDBPluginBase as c, RxDBSync as l, SwitchBranchBeginEvent as u, SwitchBranchCommitEvent as d, SwitchBranchRollbackEvent as f, TRANSACTION_BEGIN as p, TRANSACTION_COMMIT as m, TRANSACTION_ROLLBACK as h, buildPushableRepositoryRules as ee, getCurrentBranch as te, getEntityMetadata as g, getLocalSystemRepositories as ne, getRemoteSystemRepositories as re, getRxDBChangeKey as _, getRxDBEntityIdentityKey as v, isAdapterShutdownError as y, resolve_current_branch as ie } from "@aiao/rxdb";
2
- import { BehaviorSubject as b, EMPTY as ae, Observable as x, ReplaySubject as oe, Subject as se, catchError as ce, combineLatest as S, filter as C, firstValueFrom as w, map as T, shareReplay as E, switchMap as D, takeUntil as O } from "rxjs";
3
- import { isNil as k } from "@aiao/utils";
1
+ import { ENTITY_LOCAL_CREATE_EVENT as e, MAIN_BRANCH_ID as t, MergeBranchBeginEvent as n, MergeBranchCommitEvent as r, MergeBranchFailedEvent as i, REPOSITORY_SYNC_COMPLETE_EVENT as a, RxDBBranch as o, RxDBChange as s, RxDBError as c, RxDBPluginBase as l, RxDBSync as u, SKIP_BRANCH_SWITCH_PREPARE as d, SwitchBranchBeginEvent as f, SwitchBranchCommitEvent as p, SwitchBranchRollbackEvent as m, TRANSACTION_BEGIN as h, TRANSACTION_COMMIT as g, TRANSACTION_ROLLBACK as _, TrustedWriteIntent as v, assertUsableBranchId as ee, buildPushableRepositoryRules as te, declareTrustedWrite as y, getCurrentBranch as ne, getEntityMetadata as b, getLocalSystemRepositories as re, getRemoteSystemRepositories as ie, getRxDBChangeKey as x, getRxDBEntityIdentityKey as S, isAdapterShutdownError as C, resolve_current_branch as ae, takeDeclaredWrite as oe } from "@aiao/rxdb";
2
+ import { BehaviorSubject as w, EMPTY as se, NEVER as ce, Observable as le, ReplaySubject as ue, Subject as de, catchError as fe, combineLatest as T, filter as E, firstValueFrom as D, map as O, shareReplay as k, switchMap as A, takeUntil as j } from "rxjs";
3
+ import { isNil as M } from "@aiao/utils";
4
4
  //#region src/create-branch.ts
5
- var le = async (e, t, n) => {
5
+ var pe = async (e, t, n) => {
6
+ ee(t);
6
7
  let { branchRepository: r, adapter: i } = await e.getLocalRepositories();
7
8
  if ((await r.find({
8
9
  where: {
@@ -14,13 +15,13 @@ var le = async (e, t, n) => {
14
15
  }]
15
16
  },
16
17
  limit: 1
17
- })).length) throw new s(`Branch id (${t}) already exists`);
18
+ })).length) throw new c(`Branch id (${t}) already exists`);
18
19
  if (e.rxdb.config.sync?.remote?.adapter) {
19
20
  let { adapter: n } = await e.getRemoteRepositories();
20
- if (n.branchExists && await n.branchExists(t)) throw new s(`Branch id (${t}) already exists on remote`);
21
+ if (n.branchExists && await n.branchExists(t)) throw new c(`Branch id (${t}) already exists on remote`);
21
22
  }
22
- let c = await i.transaction(async (r) => {
23
- let i = r.getRepository(a), s = r.getRepository(o);
23
+ let a = await i.transaction(async (r) => {
24
+ let i = r.getRepository(o), a = r.getRepository(s);
24
25
  if ((await i.find({
25
26
  where: {
26
27
  combinator: "and",
@@ -34,7 +35,7 @@ var le = async (e, t, n) => {
34
35
  })).length) return `Branch id (${t}) already exists`;
35
36
  let c, l;
36
37
  if (n) {
37
- let e = (await s.find({
38
+ let e = (await a.find({
38
39
  where: {
39
40
  combinator: "and",
40
41
  rules: [{
@@ -57,14 +58,19 @@ var le = async (e, t, n) => {
57
58
  },
58
59
  limit: 1
59
60
  }))[0];
60
- } else c = await ie(i, e.rxdb), l = await ue(s, c.id);
61
+ } else c = await ae(i, e.rxdb), l = await me(a, c.id);
61
62
  if (!c) return "Source branch not found";
62
- let u = e.rxdb.entityManager.instantiate(a);
63
- return u.id = t, u.activated = !1, u.local = !0, u.remote = !1, u.fromChangeId = l?.id ?? null, u.parentId = c.id, await i.create(u), u;
63
+ let u = e.rxdb.entityManager.instantiate(o);
64
+ u.id = t, u.activated = !1, u.activeKey = null, u.local = !0, u.remote = !1, u.fromChangeId = l?.id ?? null, u.parentId = c.id, await i.create(u);
65
+ for (let n of e.rxdb.systemContributions) await n.writeBranchRows(e.rxdb.entityManager, {
66
+ executor: r,
67
+ branchId: t
68
+ });
69
+ return u;
64
70
  });
65
- if (typeof c == "string") throw new s(c);
66
- return c;
67
- }, ue = async (e, t) => (await e.find({
71
+ if (typeof a == "string") throw new c(a);
72
+ return a;
73
+ }, me = async (e, t) => (await e.find({
68
74
  where: {
69
75
  combinator: "and",
70
76
  rules: [t ? {
@@ -86,14 +92,14 @@ var le = async (e, t, n) => {
86
92
  sort: "desc"
87
93
  }],
88
94
  limit: 1
89
- }))[0], A = (e) => {
95
+ }))[0], N = (e) => {
90
96
  if (!e || typeof e != "object") return !1;
91
97
  let t = "name" in e ? String(e.name) : "";
92
- return ("errno" in e ? Number(e.errno) : void 0) === 44 || t === "AbortError" || y(e);
98
+ return ("errno" in e ? Number(e.errno) : void 0) === 44 || t === "AbortError" || C(e);
93
99
  };
94
100
  //#endregion
95
101
  //#region src/history-item-builder.ts
96
- function j(e) {
102
+ function P(e) {
97
103
  if (e.length === 1) {
98
104
  let t = e[0];
99
105
  return `${t.type === "INSERT" ? "创建" : t.type === "UPDATE" ? "更新" : "删除"} ${t.entity}`;
@@ -106,12 +112,12 @@ function j(e) {
106
112
  let n = [];
107
113
  return t.insert && n.push(`创建${t.insert}条`), t.update && n.push(`更新${t.update}条`), t.delete && n.push(`删除${t.delete}条`), `事务: ${n.join(", ")}`;
108
114
  }
109
- function M(e) {
115
+ function F(e) {
110
116
  let t = e[0], n = e.length, r = t.transactionId ?? null, i = t.createdAt, a = t.namespace, o = t.entity, s = r ? "TRANSACTION" : t.type, c = [
111
117
  s,
112
- v(t.entityId),
118
+ S(t.entityId),
113
119
  i.getTime()
114
- ].join(":"), l = e.some((e) => k(e.revertChangeId) === !1), u = e.some((e) => k(e.redoInvalidatedAt) === !1);
120
+ ].join(":"), l = e.some((e) => M(e.revertChangeId) === !1), u = e.some((e) => M(e.redoInvalidatedAt) === !1);
115
121
  return {
116
122
  transactionId: r,
117
123
  changeId: e.reduce((e, t) => t.id > e ? t.id : e, e[0].id),
@@ -120,57 +126,57 @@ function M(e) {
120
126
  type: s,
121
127
  count: n,
122
128
  createdAt: i,
123
- description: j(e),
129
+ description: P(e),
124
130
  namespace: a,
125
131
  entity: o,
126
132
  reverted: l,
127
133
  redoInvalidated: u
128
134
  };
129
135
  }
130
- function N(e) {
136
+ function I(e) {
131
137
  let t = [], n = [], r;
132
138
  return e.forEach((e) => {
133
- e.transactionId && e.transactionId === r ? n.push(e) : (r = e.transactionId, n.length &&= (t.push(M([...n])), 0), e.transactionId ? n.push(e) : t.push(M([e])));
134
- }), n.length && t.push(M([...n])), t;
139
+ e.transactionId && e.transactionId === r ? n.push(e) : (r = e.transactionId, n.length &&= (t.push(F([...n])), 0), e.transactionId ? n.push(e) : t.push(F([e])));
140
+ }), n.length && t.push(F([...n])), t;
135
141
  }
136
142
  //#endregion
137
143
  //#region src/history-filters.ts
138
- var P = (e) => `${e.namespace}:${e.entity}`;
139
- function F(e, t) {
144
+ var L = (e) => `${e.namespace}:${e.entity}`;
145
+ function R(e, t) {
140
146
  let n = new Map(t);
141
147
  for (let t of e) {
142
148
  if (t.lastPushedChangeId === null) continue;
143
- let e = P(t), r = n.get(e);
149
+ let e = L(t), r = n.get(e);
144
150
  r !== void 0 && r >= t.lastPushedChangeId || n.set(e, t.lastPushedChangeId);
145
151
  }
146
152
  return n;
147
153
  }
148
- function I(e, t) {
154
+ function z(e, t) {
149
155
  return t.type === "database" ? e : e.map((e) => {
150
156
  let n = e.changes.filter((e) => t.type === "repository" ? e.namespace === t.namespace && e.entity === t.entity : e.namespace === t.namespace && e.entity === t.entity && e.entityId === t.entityId);
151
157
  return n.length === 0 ? null : {
152
158
  ...e,
153
159
  changes: n,
154
160
  count: n.length,
155
- description: j(n)
161
+ description: P(n)
156
162
  };
157
163
  }).filter((e) => e !== null);
158
164
  }
159
- function L(e, t, n = 0, r = null) {
165
+ function B(e, t, n = 0, r = null) {
160
166
  return e.filter((e) => !e.reverted && e.changes.every((e) => {
161
- let i = e.remoteId == null, a = t.get(P(e)), o = a == null || e.id > a, s = e.id > n, c = r === null || e.createdAt.getTime() > r.getTime();
167
+ let i = e.remoteId == null, a = t.get(L(e)), o = a == null || e.id > a, s = e.id > n, c = r === null || e.createdAt.getTime() > r.getTime();
162
168
  return i && o && s && c;
163
169
  }));
164
170
  }
165
- function de(e) {
166
- return e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}:${v(e.entityId)}`;
171
+ function he(e) {
172
+ return e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}:${S(e.entityId)}`;
167
173
  }
168
174
  //#endregion
169
175
  //#region src/history-scope-api.ts
170
- function fe(e) {
176
+ function ge(e) {
171
177
  if (!e) return { type: "database" };
172
178
  if (Object.getPrototypeOf(e) === Object.prototype && "type" in e) return e;
173
- let t = g(e), n = "id" in e ? e.id : void 0, r = typeof n == "string" || typeof n == "number" || typeof n == "bigint" ? n : void 0;
179
+ let t = b(e), n = "id" in e ? e.id : void 0, r = typeof n == "string" || typeof n == "number" || typeof n == "bigint" ? n : void 0;
174
180
  return r === void 0 ? {
175
181
  type: "repository",
176
182
  namespace: t.namespace,
@@ -182,8 +188,8 @@ function fe(e) {
182
188
  entityId: r
183
189
  };
184
190
  }
185
- function pe(e, t) {
186
- let n = fe(t), r = de(n), i = e.history_cache.get(r);
191
+ function _e(e, t) {
192
+ let n = ge(t), r = he(n), i = e.history_cache.get(r);
187
193
  if (i) return i;
188
194
  let a = () => {
189
195
  let t = (e.history_ref_counts.get(r) || 0) - 1;
@@ -191,28 +197,28 @@ function pe(e, t) {
191
197
  }, o = () => {
192
198
  let t = (e.history_ref_counts.get(r) || 0) + 1;
193
199
  e.history_ref_counts.set(r, t), e.history_cache.set(r, h);
194
- }, s = (e) => new x((t) => {
200
+ }, s = (e) => new le((t) => {
195
201
  o();
196
202
  let n = e.subscribe(t);
197
203
  return () => {
198
204
  n.unsubscribe(), a();
199
205
  };
200
- }), c = e.histories$.pipe(T((e) => I(e, n)), E({
206
+ }), c = e.histories$.pipe(O((e) => z(e, n)), k({
201
207
  bufferSize: 1,
202
208
  refCount: !0
203
- })), l = s(c), u = s(e.undoHistories$.pipe(T((e) => I(e, n)), E({
209
+ })), l = s(c), u = s(e.undoHistories$.pipe(O((e) => z(e, n)), k({
204
210
  bufferSize: 1,
205
211
  refCount: !0
206
- }))), d = s(e.redoHistories$.pipe(T((e) => I(e, n)), E({
212
+ }))), d = s(e.redoHistories$.pipe(O((e) => z(e, n)), k({
207
213
  bufferSize: 1,
208
214
  refCount: !0
209
- }))), f = s(c.pipe(T((e) => e.length), E({
215
+ }))), f = s(c.pipe(O((e) => e.length), k({
210
216
  bufferSize: 1,
211
217
  refCount: !0
212
- }))), p = s(u.pipe(T((e) => e.length), E({
218
+ }))), p = s(u.pipe(O((e) => e.length), k({
213
219
  bufferSize: 1,
214
220
  refCount: !0
215
- }))), m = s(d.pipe(T((e) => e.length), E({
221
+ }))), m = s(d.pipe(O((e) => e.length), k({
216
222
  bufferSize: 1,
217
223
  refCount: !0
218
224
  }))), h = {
@@ -228,11 +234,11 @@ function pe(e, t) {
228
234
  if (r.state === "cleared") return;
229
235
  let { histories: i, lastPushedMap: a } = await e.fetchLatestHistories(r.boundary);
230
236
  if (!e.isUndoSessionCurrent(r)) return;
231
- let o = L(i, a, r.boundary.changeId, r.boundary.createdAfter), s = e.selectWholeTransactions(o, n, t);
237
+ let o = B(i, a, r.boundary.changeId, r.boundary.createdAfter), s = e.selectWholeTransactions(o, n, t);
232
238
  s.length !== 0 && await e.applyUndoRedoHistories("undo", s, r);
233
239
  }),
234
240
  redo: (t = 1) => e.runSerialized(async () => {
235
- let r = await w(e.redoHistories$), i = e.selectWholeTransactions(r, n, t);
241
+ let r = await D(e.redoHistories$), i = e.selectWholeTransactions(r, n, t);
236
242
  i.length !== 0 && await e.applyUndoRedoHistories("redo", i);
237
243
  })
238
244
  };
@@ -240,22 +246,22 @@ function pe(e, t) {
240
246
  }
241
247
  //#endregion
242
248
  //#region src/history-undo-session.types.ts
243
- var R = {
249
+ var V = {
244
250
  changeId: 0,
245
251
  createdAfter: null
246
252
  };
247
253
  //#endregion
248
254
  //#region src/pullable-count.ts
249
- function z(e, t) {
255
+ function ve(e, t) {
250
256
  return e?.repositoryFilter !== void 0 && e.repositoryFilter.length > 0 ? !1 : !t.hasMore && t.failures.length === 0;
251
257
  }
252
- function B(e, t) {
258
+ function ye(e, t) {
253
259
  return t.complete && !t.concurrent ? 0 : Math.max(0, e - t.pulled);
254
260
  }
255
261
  //#endregion
256
262
  //#region src/redo-stack.ts
257
- var me = 1e3, he = class {
258
- #e = new b([]);
263
+ var be = 1e3, xe = class {
264
+ #e = new w([]);
259
265
  get items$() {
260
266
  return this.#e.asObservable();
261
267
  }
@@ -263,7 +269,7 @@ var me = 1e3, he = class {
263
269
  return this.#e.value;
264
270
  }
265
271
  push(e) {
266
- let t = [...e, ...this.#e.value], n = t.length > 1e3 ? t.slice(0, me) : t;
272
+ let t = [...e, ...this.#e.value], n = t.length > 1e3 ? t.slice(0, be) : t;
267
273
  this.#e.next(n);
268
274
  }
269
275
  remove(e) {
@@ -276,35 +282,44 @@ var me = 1e3, he = class {
276
282
  };
277
283
  //#endregion
278
284
  //#region src/scope-selection.ts
279
- function V(e, t) {
285
+ function H(e, t) {
280
286
  return t.type === "database" ? !0 : e.namespace !== t.namespace || e.entity !== t.entity ? !1 : t.type === "repository" || e.entityId === t.entityId;
281
287
  }
282
- function ge(e, t) {
283
- return e.changes.some((e) => V(e, t));
288
+ function Se(e, t) {
289
+ return e.changes.some((e) => H(e, t));
284
290
  }
285
- function _e(e, t) {
286
- return e.changes.every((e) => V(e, t));
291
+ function Ce(e, t) {
292
+ return e.changes.every((e) => H(e, t));
287
293
  }
288
- function ve(e, t, n) {
289
- let r = e.filter((e) => ge(e, t)).slice(0, Math.max(0, n)), i = [], a = [];
290
- for (let e of r) _e(e, t) ? a.push(e) : i.push(e);
294
+ function we(e, t, n) {
295
+ let r = e.filter((e) => Se(e, t)).slice(0, Math.max(0, n)), i = [], a = [];
296
+ for (let e of r) Ce(e, t) ? a.push(e) : i.push(e);
291
297
  return {
292
298
  crossScope: i,
293
299
  selected: a
294
300
  };
295
301
  }
296
- var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}#${String(e.entityId)}`, be = (e, t) => {
302
+ var Te = (e) => e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}#${String(e.entityId)}`, Ee = (e, t) => {
297
303
  let n = /* @__PURE__ */ new Set();
298
- for (let r of e) for (let e of r.changes) V(e, t) || n.add(t.type === "entity" ? `${e.namespace}:${e.entity}#${String(e.entityId)}` : `${e.namespace}:${e.entity}`);
304
+ for (let r of e) for (let e of r.changes) H(e, t) || n.add(t.type === "entity" ? `${e.namespace}:${e.entity}#${String(e.entityId)}` : `${e.namespace}:${e.entity}`);
299
305
  return [...n].join(", ");
300
- }, H = class e extends s {
306
+ }, U = class e extends c {
301
307
  scope;
302
308
  histories;
303
309
  constructor(t, n) {
304
- super(`Scoped history operation would split a transaction: scope ${ye(t)} also changes ${be(n, t)}. Use the database scope to apply the whole transaction.`), this.scope = t, this.histories = n, this.name = "RxDBCrossScopeTransactionError", Object.setPrototypeOf(this, e.prototype);
310
+ super(`Scoped history operation would split a transaction: scope ${Te(t)} also changes ${Ee(n, t)}. Use the database scope to apply the whole transaction.`), this.scope = t, this.histories = n, this.name = "RxDBCrossScopeTransactionError", Object.setPrototypeOf(this, e.prototype);
311
+ }
312
+ }, W = (e) => e.fromChangeId ?? 0, G = (e, t) => {
313
+ let n = [e], r = /* @__PURE__ */ new Set([e.id]), i = e;
314
+ for (; i.parentId;) {
315
+ if (r.has(i.parentId)) throw new c(`Branch history is corrupt: cycle detected at branch '${i.id}' (parentId '${i.parentId}' already visited)`);
316
+ let e = t.get(i.parentId);
317
+ if (!e) throw new c(`Branch history is corrupt: branch '${i.id}' references missing parent '${i.parentId}'`);
318
+ r.add(e.id), n.push(e), i = e;
305
319
  }
306
- }, U = (e) => e.fromChangeId ?? 0, xe = (e) => {
307
- let { branches: t, currentBranch: n, nextBranch: r } = e, i = e.currentChangeId ?? U(n), a = e.nextChangeId ?? U(r);
320
+ return n;
321
+ }, K = (e) => {
322
+ let { branches: t, currentBranch: n, nextBranch: r } = e, i = e.currentChangeId ?? W(n), a = e.nextChangeId ?? W(r);
308
323
  if (i === a) return [];
309
324
  if (n.id === r.id) return [{
310
325
  branch: n,
@@ -313,89 +328,80 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
313
328
  }];
314
329
  let o = /* @__PURE__ */ new Map();
315
330
  for (let e of t) o.set(e.id, e);
316
- let c = (e) => {
317
- let t = [e], n = /* @__PURE__ */ new Set([e.id]), r = e;
318
- for (; r.parentId;) {
319
- if (n.has(r.parentId)) throw new s(`Branch history is corrupt: cycle detected at branch '${r.id}' (parentId '${r.parentId}' already visited)`);
320
- let e = o.get(r.parentId);
321
- if (!e) throw new s(`Branch history is corrupt: branch '${r.id}' references missing parent '${r.parentId}'`);
322
- n.add(e.id), t.push(e), r = e;
323
- }
324
- return t;
325
- }, l = c(n), u = c(r), d = null, f = -1;
326
- for (let e = 0; e < l.length; e++) if (u.findIndex((t) => t.id === l[e].id) !== -1) {
327
- d = l[e], f = e;
331
+ let s = G(n, o), c = G(r, o), l = null, u = -1;
332
+ for (let e = 0; e < s.length; e++) if (c.findIndex((t) => t.id === s[e].id) !== -1) {
333
+ l = s[e], u = e;
328
334
  break;
329
335
  }
330
- let p = [];
331
- if (d) {
332
- for (let e = 0; e < f; e++) {
333
- let t = l[e], n = e === 0 ? i : U(l[e - 1]), r = U(t);
334
- n !== r && p.push({
336
+ let d = [];
337
+ if (l) {
338
+ for (let e = 0; e < u; e++) {
339
+ let t = s[e], n = e === 0 ? i : W(s[e - 1]), r = W(t);
340
+ n !== r && d.push({
335
341
  branch: t,
336
342
  fromChangeId: n,
337
343
  toChangeId: r
338
344
  });
339
345
  }
340
- let e = u.findIndex((e) => e.id === d.id);
346
+ let e = c.findIndex((e) => e.id === l.id);
341
347
  if (e === 0) {
342
- let e = f === 0 ? i : U(l[f - 1]), t = a;
343
- e !== t && p.push({
344
- branch: d,
348
+ let e = u === 0 ? i : W(s[u - 1]), t = a;
349
+ e !== t && d.push({
350
+ branch: l,
345
351
  fromChangeId: e,
346
352
  toChangeId: t
347
353
  });
348
354
  } else if (e > 0) {
349
- let t = f === 0 ? i : U(l[f - 1]), n = U(u[e - 1]);
350
- t !== n && p.push({
351
- branch: d,
355
+ let t = u === 0 ? i : W(s[u - 1]), n = W(c[e - 1]);
356
+ t !== n && d.push({
357
+ branch: l,
352
358
  fromChangeId: t,
353
359
  toChangeId: n
354
360
  });
355
361
  }
356
- let t = u.slice(0, e).reverse();
362
+ let t = c.slice(0, e).reverse();
357
363
  for (let e = 0; e < t.length; e++) {
358
- let n = t[e], r = U(n), i = e === t.length - 1 ? a : U(t[e + 1]);
359
- r !== i && p.push({
364
+ let n = t[e], r = W(n), i = e === t.length - 1 ? a : W(t[e + 1]);
365
+ r !== i && d.push({
360
366
  branch: n,
361
367
  fromChangeId: r,
362
368
  toChangeId: i
363
369
  });
364
370
  }
365
371
  } else {
366
- for (let e = 0; e < l.length; e++) {
367
- let t = l[e], n = e === 0 ? i : U(l[e - 1]), r = U(t);
368
- n !== r && p.push({
372
+ for (let e = 0; e < s.length; e++) {
373
+ let t = s[e], n = e === 0 ? i : W(s[e - 1]), r = W(t);
374
+ n !== r && d.push({
369
375
  branch: t,
370
376
  fromChangeId: n,
371
377
  toChangeId: r
372
378
  });
373
379
  }
374
- let e = l[l.length - 1], t = U(e);
375
- t !== 0 && p.push({
380
+ let e = s[s.length - 1], t = W(e);
381
+ t !== 0 && d.push({
376
382
  branch: e,
377
383
  fromChangeId: t,
378
384
  toChangeId: 0
379
385
  });
380
- let n = u[u.length - 1], r = u.length > 1 ? U(u[u.length - 2]) : a;
381
- r !== 0 && p.push({
386
+ let n = c[c.length - 1], r = c.length > 1 ? W(c[c.length - 2]) : a;
387
+ r !== 0 && d.push({
382
388
  branch: n,
383
389
  fromChangeId: 0,
384
390
  toChangeId: r
385
391
  });
386
- let o = u.slice(0, u.length - 1).reverse();
392
+ let o = c.slice(0, c.length - 1).reverse();
387
393
  for (let e = 0; e < o.length; e++) {
388
- let t = o[e], n = U(t), r = e === o.length - 1 ? a : U(o[e + 1]);
389
- n !== r && p.push({
394
+ let t = o[e], n = W(t), r = e === o.length - 1 ? a : W(o[e + 1]);
395
+ n !== r && d.push({
390
396
  branch: t,
391
397
  fromChangeId: n,
392
398
  toChangeId: r
393
399
  });
394
400
  }
395
401
  }
396
- return p;
397
- }, Se = async (e, t) => {
398
- let { branchRepository: n, changeRepository: r } = await e.getLocalRepositories(), i = (await n.find({
402
+ return d;
403
+ }, De = async (e, t) => q(await e.getLocalRepositories(), t), q = async (e, t) => {
404
+ let { branchRepository: n, changeRepository: r } = e, i = (await n.find({
399
405
  where: {
400
406
  combinator: "and",
401
407
  rules: [{
@@ -406,17 +412,17 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
406
412
  },
407
413
  limit: 1
408
414
  }))[0];
409
- if (!i) throw new s("Current branch not found");
415
+ if (!i) throw new c("Current branch not found");
410
416
  let a = await n.find({ where: {
411
417
  combinator: "and",
412
418
  rules: []
413
419
  } }), o = a.find((e) => e.id === t);
414
- if (!o) throw new s(`Branch (${t}) not found`);
415
- if (i.id === o.id) throw new s("Cannot switch to the same branch");
416
- let c = await G(r, i.id), l = await G(r, o.id), u = xe({
420
+ if (!o) throw new c(`Branch (${t}) not found`);
421
+ if (i.id === o.id) throw new c("Cannot switch to the same branch");
422
+ let s = await Y(r, i.id), l = await Y(r, o.id), u = K({
417
423
  branches: a,
418
424
  currentBranch: i,
419
- currentChangeId: c ? c.id : null,
425
+ currentChangeId: s ? s.id : null,
420
426
  nextBranch: o,
421
427
  nextChangeId: l ? l.id : null
422
428
  }), d = {
@@ -456,10 +462,10 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
456
462
  value: t.fromChangeId
457
463
  });
458
464
  let f = await r.find(l);
459
- o ? we(f, d) : a && Ce(f, d);
465
+ o ? ke(f, d) : a && Oe(f, d);
460
466
  }
461
467
  return d;
462
- }, Ce = (e, t) => W(e, !0, t), we = (e, t) => W(e, !1, t), W = (e, t, n = {
468
+ }, Oe = (e, t) => J(e, !0, t), ke = (e, t) => J(e, !1, t), J = (e, t, n = {
463
469
  deletes: /* @__PURE__ */ new Map(),
464
470
  updates: /* @__PURE__ */ new Map(),
465
471
  inserts: /* @__PURE__ */ new Map()
@@ -467,7 +473,7 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
467
473
  if (t) {
468
474
  let t = [...e].sort((e, t) => e.id - t.id);
469
475
  for (let e of t) {
470
- let t = _(e);
476
+ let t = x(e);
471
477
  switch (e.type) {
472
478
  case "INSERT":
473
479
  n.inserts.set(t, {
@@ -493,7 +499,7 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
493
499
  } else {
494
500
  let t = [...e].sort((e, t) => t.id - e.id);
495
501
  for (let e of t) {
496
- let t = _(e);
502
+ let t = x(e);
497
503
  switch (e.type) {
498
504
  case "INSERT":
499
505
  n.deletes.set(t, {
@@ -518,7 +524,7 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
518
524
  }
519
525
  }
520
526
  return n;
521
- }, G = async (e, t) => (await e.find({
527
+ }, Y = async (e, t) => (await e.find({
522
528
  where: {
523
529
  combinator: "and",
524
530
  rules: [{
@@ -536,8 +542,8 @@ var ye = (e) => e.type === "database" ? "database" : e.type === "repository" ? `
536
542
  sort: "desc"
537
543
  }],
538
544
  limit: 1
539
- }))[0], K = (e) => e.getRepository(l);
540
- async function Te(e, t) {
545
+ }))[0], X = (e) => e.getRepository(u);
546
+ async function Ae(e, t) {
541
547
  let { changeRepository: n, branchRepository: r } = await e.rxdb.versionManager.getLocalRepositories(), i = await r.find({ where: {
542
548
  combinator: "and",
543
549
  rules: [{
@@ -550,7 +556,7 @@ async function Te(e, t) {
550
556
  histories: [],
551
557
  lastPushedMap: /* @__PURE__ */ new Map()
552
558
  };
553
- let a = i[0], o = F(await K(await w(e.rxdb.localAdapter$)).find({ where: {
559
+ let a = i[0], o = R(await X(await D(e.rxdb.localAdapter$)).find({ where: {
554
560
  combinator: "and",
555
561
  rules: [{
556
562
  field: "branchId",
@@ -571,7 +577,7 @@ async function Te(e, t) {
571
577
  operator: ">",
572
578
  value: t.changeId
573
579
  }), {
574
- histories: N(await n.find({
580
+ histories: I(await n.find({
575
581
  where: {
576
582
  combinator: "and",
577
583
  rules: s
@@ -584,10 +590,10 @@ async function Te(e, t) {
584
590
  lastPushedMap: o
585
591
  };
586
592
  }
587
- async function Ee(e, t, n, r) {
593
+ async function je(e, t, n, r) {
588
594
  e.isUndoRedoInProgress = !0;
589
595
  try {
590
- let i = n.flatMap((e) => e.changes).sort((e, n) => t === "undo" ? n.id - e.id : e.id - n.id), a = W(i, t === "redo"), o = e.getNextRevertStateUpdatedAt(i);
596
+ let i = n.flatMap((e) => e.changes).sort((e, n) => t === "undo" ? n.id - e.id : e.id - n.id), a = J(i, t === "redo"), o = e.getNextRevertStateUpdatedAt(i);
591
597
  if (t === "undo") {
592
598
  let { adapter: t } = await e.rxdb.versionManager.getLocalRepositories(), n = await t.getRxDBChangeSequence(), r = /* @__PURE__ */ new Date();
593
599
  i.forEach((e, t) => {
@@ -621,21 +627,28 @@ async function Ee(e, t, n, r) {
621
627
  });
622
628
  let { adapter: s } = await e.rxdb.versionManager.getLocalRepositories();
623
629
  if (t === "undo" && (r === void 0 || !e.isUndoSessionCurrent(r))) return;
624
- await s.switchBranch({ actions: a }), e.pushableCountTrigger$.next(Date.now()), e.setRevertStateWatermarks(i, t === "undo", o), t === "undo" ? e.pushToRedoStack(n) : e.removeFromRedoStack(n);
630
+ y(s, {
631
+ file: "undo-redo-apply.ts",
632
+ symbol: "applyUndoRedoHistories",
633
+ intent: v.undo_redo
634
+ }), await s.switchBranch({
635
+ actions: a,
636
+ prepare: d
637
+ }), e.pushableCountTrigger$.next(Date.now()), e.setRevertStateWatermarks(i, t === "undo", o), t === "undo" ? e.pushToRedoStack(n) : e.removeFromRedoStack(n);
625
638
  } finally {
626
639
  e.isUndoRedoInProgress = !1;
627
640
  }
628
641
  }
629
- async function De(e) {
642
+ async function Me(e) {
630
643
  let t = ++e.pushableGeneration, n = (n) => {
631
644
  t === e.pushableGeneration && e.pushableCount$.next(n);
632
645
  };
633
646
  try {
634
- if (!await w(e.rxdb.connected$)) {
647
+ if (!await D(e.rxdb.connected$)) {
635
648
  n(0);
636
649
  return;
637
650
  }
638
- let t = K(await w(e.rxdb.localAdapter$)), r = e.rxdb.entityManager.getRepository(o), i = await w(e.rxdb.entityManager.getRepository(a).findOne({ where: {
651
+ let t = X(await D(e.rxdb.localAdapter$)), r = e.rxdb.entityManager.getRepository(s), i = await D(e.rxdb.entityManager.getRepository(o).findOne({ where: {
639
652
  combinator: "and",
640
653
  rules: [{
641
654
  field: "activated",
@@ -647,19 +660,19 @@ async function De(e) {
647
660
  n(0);
648
661
  return;
649
662
  }
650
- let s = await t.find({ where: {
663
+ let a = await t.find({ where: {
651
664
  combinator: "and",
652
665
  rules: [{
653
666
  field: "branchId",
654
667
  operator: "=",
655
668
  value: i.id
656
669
  }]
657
- } }), c = ee(e.rxdb.config.entities, e.rxdb.config.sync, s);
670
+ } }), c = te(e.rxdb.config.entities, e.rxdb.entitySync, a);
658
671
  if (c.length === 0) {
659
672
  n(0);
660
673
  return;
661
674
  }
662
- n(await w(r.count({ where: {
675
+ n(await D(r.count({ where: {
663
676
  combinator: "and",
664
677
  rules: [
665
678
  {
@@ -684,26 +697,26 @@ async function De(e) {
684
697
  ]
685
698
  } })));
686
699
  } catch (t) {
687
- !e.destroyed && !y(t) && (console.error("[#updatePushableCount] error", t), e.errors$.next(t instanceof Error ? t : Error(String(t)))), n(0);
700
+ !e.destroyed && !C(t) && (console.error("[#updatePushableCount] error", t), e.errors$.next(t instanceof Error ? t : Error(String(t)))), n(0);
688
701
  }
689
702
  }
690
703
  //#endregion
691
704
  //#region src/HistoryManager.ts
692
- var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
705
+ var Z = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), Ne = class {
693
706
  rxdb;
694
707
  #e = [];
695
708
  #t = !1;
696
709
  #n;
697
710
  #r;
698
- #i = new oe(1);
711
+ #i = new ue(1);
699
712
  #a = Promise.resolve();
700
- #o = new b(0);
713
+ #o = new w(0);
701
714
  #s = 0;
702
- #c = new b(0);
715
+ #c = new w(0);
703
716
  #l = 0;
704
- #u = new b(0);
717
+ #u = new w(0);
705
718
  #d = /* @__PURE__ */ new Map();
706
- #f = new b(0);
719
+ #f = new w(0);
707
720
  #p = 0;
708
721
  #m;
709
722
  #h = null;
@@ -712,15 +725,15 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
712
725
  #v = null;
713
726
  #y = 0;
714
727
  #b = null;
715
- #x = new b({
728
+ #x = new w({
716
729
  generation: 0,
717
730
  state: "active",
718
- boundary: R
731
+ boundary: V
719
732
  });
720
733
  isUndoRedoInProgress = !1;
721
734
  isInvalidatingRedo = !1;
722
735
  syncDepth = 0;
723
- redoStack = new he();
736
+ redoStack = new xe();
724
737
  history_cache = /* @__PURE__ */ new Map();
725
738
  history_ref_counts = /* @__PURE__ */ new Map();
726
739
  histories$;
@@ -728,7 +741,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
728
741
  redoHistories$;
729
742
  undoCount$;
730
743
  redoCount$;
731
- errors$ = new se();
744
+ errors$ = new de();
732
745
  pushableCount$;
733
746
  pullableCount$;
734
747
  count$;
@@ -737,21 +750,21 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
737
750
  }
738
751
  constructor(e) {
739
752
  this.rxdb = e, this.#n = this.#R(), this.#r = this.#z();
740
- let t = e.entityManager.getRepository(a), n = e.entityManager.getRepository(o), r = t.findOne({ where: {
753
+ let t = e.entityManager.getRepository(o), n = e.entityManager.getRepository(s), r = this.rxdb.connected$.pipe(A((e) => e ? t.findOne({ where: {
741
754
  combinator: "and",
742
755
  rules: [{
743
756
  field: "activated",
744
757
  operator: "=",
745
758
  value: !0
746
759
  }]
747
- } });
748
- this.#e.push(r.pipe(O(this.#i)).subscribe({
760
+ } }) : ce));
761
+ this.#e.push(r.pipe(j(this.#i)).subscribe({
749
762
  next: (e) => this.#E(e?.id ?? null),
750
763
  error: (e) => this.#T("undo session 分支跟随的活跃分支流已中断", e)
751
- })), this.#m = S({
764
+ })), this.#m = T({
752
765
  connected: this.rxdb.connected$,
753
766
  branch: r
754
- }).pipe(C(({ connected: e, branch: t }) => e && !!t), D(({ branch: e }) => {
767
+ }).pipe(E(({ connected: e, branch: t }) => e && !!t), A(({ branch: e }) => {
755
768
  let t = this.#M();
756
769
  return n.findAll({
757
770
  where: {
@@ -771,25 +784,25 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
771
784
  sort: "desc"
772
785
  }]
773
786
  });
774
- }), O(this.#i));
775
- let s = this.#m.pipe(T((e) => N(e)), E({
787
+ }), j(this.#i));
788
+ let i = this.#m.pipe(O((e) => I(e)), k({
776
789
  bufferSize: 1,
777
790
  refCount: !0
778
791
  }));
779
- this.histories$ = S([s, this.#f]).pipe(T(([e]) => this.#O(e)), E({
792
+ this.histories$ = T([i, this.#f]).pipe(O(([e]) => this.#O(e)), k({
780
793
  bufferSize: 1,
781
794
  refCount: !0
782
- })), this.count$ = this.histories$.pipe(T((e) => e.length), E({
795
+ })), this.count$ = this.histories$.pipe(O((e) => e.length), k({
783
796
  bufferSize: 1,
784
797
  refCount: !0
785
- })), this.undoHistories$ = S({
798
+ })), this.undoHistories$ = T({
786
799
  histories: this.histories$,
787
800
  undoSession: this.#x,
788
801
  trigger: this.#u
789
- }).pipe(D(async ({ histories: e, undoSession: t }) => {
802
+ }).pipe(A(async ({ histories: e, undoSession: t }) => {
790
803
  if (t.state === "cleared") return [];
791
804
  try {
792
- let n = await w(this.rxdb.entityManager.getRepository(a).findOne({ where: {
805
+ let n = await D(this.rxdb.entityManager.getRepository(o).findOne({ where: {
793
806
  combinator: "and",
794
807
  rules: [{
795
808
  field: "activated",
@@ -797,7 +810,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
797
810
  value: !0
798
811
  }]
799
812
  } }));
800
- return n ? L(e, F(await K(await w(this.rxdb.localAdapter$)).find({ where: {
813
+ return n ? B(e, R(await X(await D(this.rxdb.localAdapter$)).find({ where: {
801
814
  combinator: "and",
802
815
  rules: [{
803
816
  field: "branchId",
@@ -809,20 +822,20 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
809
822
  let t = e instanceof Error ? e : Error(String(e));
810
823
  return this.errors$.next(t), [];
811
824
  }
812
- }), E({
825
+ }), k({
813
826
  bufferSize: 1,
814
827
  refCount: !0
815
- })), this.redoHistories$ = this.redoStack.items$, this.undoCount$ = this.undoHistories$.pipe(T((e) => e.length), E({
828
+ })), this.redoHistories$ = this.redoStack.items$, this.undoCount$ = this.undoHistories$.pipe(O((e) => e.length), k({
816
829
  bufferSize: 1,
817
830
  refCount: !0
818
- })), this.redoCount$ = this.redoHistories$.pipe(T((e) => e.length), E({
831
+ })), this.redoCount$ = this.redoHistories$.pipe(O((e) => e.length), k({
819
832
  bufferSize: 1,
820
833
  refCount: !0
821
834
  })), this.pushableCount$ = this.#c.asObservable(), this.pullableCount$ = this.#o.asObservable();
822
- let c = S({
835
+ let c = T({
823
836
  connected: this.rxdb.connected$,
824
837
  branch: r
825
- }).pipe(C(({ connected: e, branch: t }) => e && !!t), D(({ branch: e }) => {
838
+ }).pipe(E(({ connected: e, branch: t }) => e && !!t), A(({ branch: e }) => {
826
839
  let t = [
827
840
  {
828
841
  field: "branchId",
@@ -838,24 +851,29 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
838
851
  field: "remoteId",
839
852
  operator: "=",
840
853
  value: null
854
+ },
855
+ {
856
+ field: "rejectedAt",
857
+ operator: "=",
858
+ value: null
841
859
  }
842
860
  ];
843
861
  return n.count({ where: {
844
862
  combinator: "and",
845
863
  rules: t
846
- } }).pipe(ce((e) => (this.#T("pushableCount 的变更计数查询", e), ae)));
864
+ } }).pipe(fe((e) => (this.#T("pushableCount 的变更计数查询", e), se)));
847
865
  })).subscribe({
848
866
  next: () => {
849
867
  this.#L();
850
868
  },
851
869
  error: (e) => this.#T("pushableCount 重算的活跃分支流已中断", e)
852
870
  });
853
- this.#e.push(c), this.rxdb.addEventListener(i, this.#F), this.#L();
871
+ this.#e.push(c), this.rxdb.addEventListener(a, this.#F), this.#L();
854
872
  }
855
873
  destroy() {
856
874
  this.#t = !0, this.#i.next(), this.#i.complete();
857
875
  for (let e of this.#e) e.unsubscribe();
858
- this.#e.length = 0, this.rxdb.removeEventListener(i, this.#F), this.#d.clear(), this.errors$.complete();
876
+ this.#e.length = 0, this.rxdb.removeEventListener(a, this.#F), this.#d.clear(), this.errors$.complete();
859
877
  }
860
878
  incrementPullableCount(e) {
861
879
  this.#s++;
@@ -873,7 +891,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
873
891
  this.#o.next(n);
874
892
  }
875
893
  settlePullableCount(e, t) {
876
- this.#o.next(B(this.#o.value, {
894
+ this.#o.next(ye(this.#o.value, {
877
895
  complete: t.complete,
878
896
  concurrent: e !== this.#s,
879
897
  pulled: t.pulled
@@ -910,7 +928,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
910
928
  this.#v = t(this.#v ?? {
911
929
  generation: 0,
912
930
  state: "active",
913
- boundary: R
931
+ boundary: V
914
932
  });
915
933
  let n = this.#b === null ? void 0 : this.#_.get(this.#b);
916
934
  this.#x.next(n ?? this.#v), this.clearRedoStack();
@@ -921,7 +939,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
921
939
  let r = e.filter((e) => Number.isSafeInteger(e) && e > 0);
922
940
  if (t === void 0) {
923
941
  if (r.length === 0) return;
924
- let e = q(r);
942
+ let e = Z(r);
925
943
  this.#w({
926
944
  generation: n.generation,
927
945
  state: "active",
@@ -933,7 +951,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
933
951
  return;
934
952
  }
935
953
  if (!(t.generation === null ? t.recordAt !== null && Number.isFinite(t.recordAt.getTime()) && t.recordAt.getTime() > n.clearedAt.getTime() : t.generation === n.generation)) return;
936
- let i = r.length > 0 ? q(r) : null, a = i === null && (n.boundary.createdAfter === null || n.boundary.createdAfter.getTime() < n.clearedAt.getTime()) ? n.clearedAt : n.boundary.createdAfter;
954
+ let i = r.length > 0 ? Z(r) : null, a = i === null && (n.boundary.createdAfter === null || n.boundary.createdAfter.getTime() < n.clearedAt.getTime()) ? n.clearedAt : n.boundary.createdAfter;
937
955
  this.#w({
938
956
  generation: n.generation,
939
957
  state: "active",
@@ -956,19 +974,26 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
956
974
  }
957
975
  async invalidateRedoStack(e) {
958
976
  return this.#j(async () => {
959
- if (!(this.isUndoRedoInProgress || this.isInvalidatingRedo) && !(e?.length && e.every((e) => e <= this.#p))) {
977
+ if (!(e?.length && e.every((e) => e <= this.#p))) {
960
978
  this.isInvalidatingRedo = !0;
961
979
  try {
962
- let e = await w(this.redoHistories$);
980
+ let e = await D(this.redoHistories$);
963
981
  if (e.length === 0) return;
964
- let t = e.flatMap((e) => e.changes), n = /* @__PURE__ */ new Date(), r = W([], !1), { adapter: i } = await this.rxdb.versionManager.getLocalRepositories();
982
+ let t = e.flatMap((e) => e.changes), n = /* @__PURE__ */ new Date(), r = J([], !1), { adapter: i } = await this.rxdb.versionManager.getLocalRepositories();
965
983
  t.forEach((e) => {
966
984
  let t = `rxdb:RxDBChange:${e.id}`;
967
985
  r.updates.set(t, {
968
986
  patch: { redoInvalidatedAt: n },
969
987
  inversePatch: { redoInvalidatedAt: null }
970
988
  });
971
- }), await i.switchBranch({ actions: r }), this.clearRedoStack();
989
+ }), y(i, {
990
+ file: "HistoryManager.ts",
991
+ symbol: "invalidateRedoStack",
992
+ intent: v.redo_invalidation
993
+ }), await i.switchBranch({
994
+ actions: r,
995
+ prepare: d
996
+ }), this.clearRedoStack();
972
997
  } catch (e) {
973
998
  throw console.error("[HistoryManager] Failed to invalidate redo stack:", e), e;
974
999
  } finally {
@@ -978,11 +1003,11 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
978
1003
  });
979
1004
  }
980
1005
  history(e) {
981
- return pe(this.#n, e);
1006
+ return _e(this.#n, e);
982
1007
  }
983
1008
  #S(e, t, n) {
984
- let { crossScope: r, selected: i } = ve(e, t, n);
985
- if (r.length > 0) throw new H(t, r);
1009
+ let { crossScope: r, selected: i } = we(e, t, n);
1010
+ if (r.length > 0) throw new U(t, r);
986
1011
  return i;
987
1012
  }
988
1013
  #C() {
@@ -992,7 +1017,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
992
1017
  this.#b !== null && this.#_.set(this.#b, e), this.#x.next(e);
993
1018
  }
994
1019
  #T(e, t) {
995
- this.#t || y(t) || (console.error(`[HistoryManager] ${e}:`, t), this.errors$.next(t instanceof Error ? t : Error(String(t))));
1020
+ this.#t || C(t) || (console.error(`[HistoryManager] ${e}:`, t), this.errors$.next(t instanceof Error ? t : Error(String(t))));
996
1021
  }
997
1022
  #E(e) {
998
1023
  if (e === this.#b || (this.#b === null && e !== null && !this.#_.has(e) && this.#_.set(e, this.#x.value), this.#b = e, e === null)) return;
@@ -1004,7 +1029,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1004
1029
  return t === null ? {
1005
1030
  generation: e,
1006
1031
  state: "active",
1007
- boundary: R
1032
+ boundary: V
1008
1033
  } : {
1009
1034
  ...t,
1010
1035
  generation: e
@@ -1052,16 +1077,16 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1052
1077
  return this.#x.value === e;
1053
1078
  }
1054
1079
  async #P(e) {
1055
- return Te(this.#r, e);
1080
+ return Ae(this.#r, e);
1056
1081
  }
1057
1082
  #F = () => {
1058
1083
  this.#L(), this.#u.next(Date.now());
1059
1084
  };
1060
1085
  async #I(e, t, n) {
1061
- return Ee(this.#r, e, t, n);
1086
+ return je(this.#r, e, t, n);
1062
1087
  }
1063
1088
  async #L() {
1064
- return De(this.#r);
1089
+ return Me(this.#r);
1065
1090
  }
1066
1091
  #R() {
1067
1092
  let e = this;
@@ -1135,52 +1160,56 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1135
1160
  removeFromRedoStack: (t) => e.removeFromRedoStack(t)
1136
1161
  };
1137
1162
  }
1138
- }, Y = async (e, t) => {
1139
- let { adapter: n } = await e.getLocalRepositories();
1140
- if (t === "main") throw new s("Cannot remove main branch");
1141
- let r = await n.transaction(async (e) => {
1142
- let n = e.getRepository(a), r = e.getRepository(o), i = (await n.find({
1163
+ }, Pe = async (e, n) => {
1164
+ let { adapter: r } = await e.getLocalRepositories();
1165
+ if (n === t) throw new c("Cannot remove main branch");
1166
+ let i = await r.transaction(async (t) => {
1167
+ let r = t.getRepository(o), i = t.getRepository(s), a = (await r.find({
1143
1168
  where: {
1144
1169
  combinator: "and",
1145
1170
  rules: [{
1146
1171
  field: "id",
1147
1172
  operator: "=",
1148
- value: t
1173
+ value: n
1149
1174
  }]
1150
1175
  },
1151
1176
  limit: 1
1152
1177
  }))[0];
1153
- if (!i) return `Branch '${t}' not found`;
1154
- if (i.activated) return `Cannot remove active branch '${t}'. Switch to another branch first.`;
1155
- if ((await n.find({
1178
+ if (!a) return `Branch '${n}' not found`;
1179
+ if (a.activated) return `Cannot remove active branch '${n}'. Switch to another branch first.`;
1180
+ if ((await r.find({
1156
1181
  where: {
1157
1182
  combinator: "and",
1158
1183
  rules: [{
1159
1184
  field: "parentId",
1160
1185
  operator: "=",
1161
- value: t
1186
+ value: n
1162
1187
  }, {
1163
1188
  field: "id",
1164
1189
  operator: "!=",
1165
- value: t
1190
+ value: n
1166
1191
  }]
1167
1192
  },
1168
1193
  limit: 1
1169
- }))?.length) return `Cannot remove branch '${t}' because it has child branches`;
1170
- let s = await r.find({ where: {
1194
+ }))?.length) return `Cannot remove branch '${n}' because it has child branches`;
1195
+ let c = await i.find({ where: {
1171
1196
  combinator: "and",
1172
1197
  rules: [{
1173
1198
  field: "branchId",
1174
1199
  operator: "=",
1175
- value: t
1200
+ value: n
1176
1201
  }]
1177
1202
  } });
1178
- await e.removeMany([...s, i]);
1203
+ for (let r of e.rxdb.systemContributions) await r.removeBranchRows({
1204
+ executor: t,
1205
+ branchId: n
1206
+ });
1207
+ await t.removeMany([...c, a]);
1179
1208
  });
1180
- if (r) throw new s(r);
1181
- }, Oe = async (e, t, n, r) => {
1182
- let i = r?.strategy ?? "squash", a = r?.deleteSource ?? !1, { branchRepository: o, changeRepository: c, adapter: l } = await e.getLocalRepositories();
1183
- if (t === n) throw new s(`Cannot merge branch '${t}' into itself`);
1209
+ if (i) throw new c(i);
1210
+ }, Fe = async (e, t, n, r) => {
1211
+ let i = r?.strategy ?? "squash", a = r?.deleteSource ?? !1, { branchRepository: o, changeRepository: s, adapter: l } = await e.getLocalRepositories();
1212
+ if (t === n) throw new c(`Cannot merge branch '${t}' into itself`);
1184
1213
  let u = (await o.find({
1185
1214
  where: {
1186
1215
  combinator: "and",
@@ -1192,8 +1221,8 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1192
1221
  },
1193
1222
  limit: 1
1194
1223
  }))[0];
1195
- if (!u) throw new s(`Branch '${t}' not found`);
1196
- let d = await c.find({
1224
+ if (!u) throw new c(`Branch '${t}' not found`);
1225
+ let d = await s.find({
1197
1226
  where: {
1198
1227
  combinator: "and",
1199
1228
  rules: [
@@ -1221,7 +1250,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1221
1250
  }), f = async () => {
1222
1251
  if (!a) return { deleted: !1 };
1223
1252
  try {
1224
- return await Y(e, t), { deleted: !0 };
1253
+ return await Pe(e, t), { deleted: !0 };
1225
1254
  } catch (e) {
1226
1255
  return {
1227
1256
  deleted: !1,
@@ -1242,7 +1271,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1242
1271
  deletes: /* @__PURE__ */ new Map(),
1243
1272
  updates: /* @__PURE__ */ new Map(),
1244
1273
  inserts: /* @__PURE__ */ new Map()
1245
- }, r = _(t);
1274
+ }, r = x(t);
1246
1275
  t.type === "INSERT" ? n.inserts.set(r, {
1247
1276
  patch: t.patch,
1248
1277
  inversePatch: null
@@ -1252,17 +1281,27 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1252
1281
  }) : t.type === "DELETE" && n.deletes.set(r, {
1253
1282
  patch: null,
1254
1283
  inversePatch: t.inversePatch
1284
+ }), y(e, {
1285
+ file: "merge-branch.ts",
1286
+ symbol: "merge_branch",
1287
+ intent: v.merge_per_change
1255
1288
  }), await e.mergeChanges(n, void 0, !1);
1256
1289
  }
1257
1290
  }), m = d.length;
1258
1291
  else {
1259
- let e = W(d, !0), t = new Set(d.filter((e) => e.type === "INSERT").map((e) => _(e)));
1292
+ let e = J(d, !0), t = new Set(d.filter((e) => e.type === "INSERT").map((e) => x(e)));
1260
1293
  for (let n of t) e.deletes.has(n) && e.deletes.delete(n);
1261
1294
  if (m = e.inserts.size + e.updates.size + e.deletes.size, m === 0) return p(0, await f());
1262
- await l.mergeChanges(e, void 0, !1);
1295
+ await l.transaction(async (t) => {
1296
+ y(t, {
1297
+ file: "merge-branch.ts",
1298
+ symbol: "merge_branch",
1299
+ intent: v.merge_squash
1300
+ }), await t.mergeChanges(e, void 0, !1);
1301
+ }, !1);
1263
1302
  }
1264
1303
  return p(m, await f());
1265
- }, X = class {
1304
+ }, Q = class {
1266
1305
  #e = /* @__PURE__ */ new Map();
1267
1306
  #t = 0;
1268
1307
  session() {
@@ -1288,7 +1327,7 @@ var q = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), J = class {
1288
1327
  };
1289
1328
  //#endregion
1290
1329
  //#region src/restore-entity.ts
1291
- async function ke(e, t, n) {
1330
+ async function Ie(e, t, n) {
1292
1331
  let { changeRepository: r, adapter: i } = await e.getLocalRepositories(), a = await r.find({
1293
1332
  where: {
1294
1333
  combinator: "and",
@@ -1300,16 +1339,22 @@ async function ke(e, t, n) {
1300
1339
  },
1301
1340
  limit: 1
1302
1341
  });
1303
- if (a.length === 0) throw new s(`RxDBChange not found: ${n.changeId}`);
1342
+ if (a.length === 0) throw new c(`RxDBChange not found: ${n.changeId}`);
1304
1343
  let o = a[0];
1305
- if (o.type !== "DELETE") throw new s(`Cannot restore from non-DELETE change (type=${o.type})`);
1306
- if (!o.inversePatch) throw new s(`RxDBChange ${n.changeId} has no inversePatch`);
1307
- let c = t.constructor, l = g(c), u = await e.getCurrentBranch();
1308
- if (o.namespace !== l.namespace || o.entity !== l.name) throw new s(`RxDBChange ${n.changeId} belongs to ${o.namespace}:${o.entity}, not ${l.namespace}:${l.name}`);
1309
- if (o.branchId != null && o.branchId !== u.id) throw new s(`RxDBChange ${n.changeId} belongs to branch '${o.branchId}', current branch is '${u.id}'`);
1310
- let d = W([o], !1);
1311
- await i.mergeChanges(d, void 0, !1);
1312
- let f = await i.getRepository(c).find({
1344
+ if (o.type !== "DELETE") throw new c(`Cannot restore from non-DELETE change (type=${o.type})`);
1345
+ if (!o.inversePatch) throw new c(`RxDBChange ${n.changeId} has no inversePatch`);
1346
+ let s = t.constructor, l = b(s), u = await e.getCurrentBranch();
1347
+ if (o.namespace !== l.namespace || o.entity !== l.name) throw new c(`RxDBChange ${n.changeId} belongs to ${o.namespace}:${o.entity}, not ${l.namespace}:${l.name}`);
1348
+ if (o.branchId != null && o.branchId !== u.id) throw new c(`RxDBChange ${n.changeId} belongs to branch '${o.branchId}', current branch is '${u.id}'`);
1349
+ let d = J([o], !1);
1350
+ await i.transaction(async (e) => {
1351
+ y(e, {
1352
+ file: "restore-entity.ts",
1353
+ symbol: "restore_entity",
1354
+ intent: v.restore_entity
1355
+ }), await e.mergeChanges(d, void 0, !1);
1356
+ }, !1);
1357
+ let f = await i.getRepository(s).find({
1313
1358
  where: {
1314
1359
  combinator: "and",
1315
1360
  rules: [{
@@ -1320,18 +1365,18 @@ async function ke(e, t, n) {
1320
1365
  },
1321
1366
  limit: 1
1322
1367
  });
1323
- if (!f[0]) throw new s(`Restore produced no row for ${l.namespace}:${l.name} id=${String(o.entityId)}`);
1368
+ if (!f[0]) throw new c(`Restore produced no row for ${l.namespace}:${l.name} id=${String(o.entityId)}`);
1324
1369
  return f[0];
1325
1370
  }
1326
1371
  //#endregion
1327
1372
  //#region src/sync-history-bridge.ts
1328
- var Z = (e, t) => ({
1373
+ var Le = (e, t) => ({
1329
1374
  pushInFlight: t,
1330
1375
  syncing: (t) => e().syncing(t),
1331
1376
  clearUndoHistory: () => e().clearUndoHistory(),
1332
1377
  beginPullableSettlement: () => e().beginPullableSettlement(),
1333
1378
  settlePull: (t, n, r) => e().settlePullableCount(t, {
1334
- complete: z(n, r),
1379
+ complete: ve(n, r),
1335
1380
  pulled: r.pulled
1336
1381
  }),
1337
1382
  settleAbortedPull: (t, n) => e().settlePullableCount(t, {
@@ -1340,14 +1385,14 @@ var Z = (e, t) => ({
1340
1385
  }),
1341
1386
  reconcilePullableCount: (t, n) => e().reconcilePullableCount(t, n),
1342
1387
  incrementPullableCount: (t) => e().incrementPullableCount(t)
1343
- }), Q = (e) => typeof e == "number" && Number.isSafeInteger(e) && e > 0 ? e : null, Ae = (e) => {
1344
- let t = Q(e.id);
1345
- return t === null ? typeof e.patch != "object" || e.patch === null || !("id" in e.patch) ? null : Q(e.patch.id) : t;
1346
- }, je = (e) => {
1388
+ }), Re = (e) => typeof e == "number" && Number.isSafeInteger(e) && e > 0 ? e : null, ze = (e) => {
1389
+ let t = Re(e.id);
1390
+ return t === null ? typeof e.patch != "object" || e.patch === null || !("id" in e.patch) ? null : Re(e.patch.id) : t;
1391
+ }, Be = (e) => {
1347
1392
  let t = null;
1348
1393
  for (let n of e) n.recordAt instanceof Date && Number.isFinite(n.recordAt.getTime()) && (t === null || n.recordAt.getTime() < t.getTime()) && (t = n.recordAt);
1349
1394
  return t;
1350
- }, Me = class {
1395
+ }, Ve = class {
1351
1396
  rxdb;
1352
1397
  #e = [];
1353
1398
  #t = 0;
@@ -1355,8 +1400,8 @@ var Z = (e, t) => ({
1355
1400
  #r = !1;
1356
1401
  #i = !1;
1357
1402
  historyManager;
1358
- pushInFlight = new X();
1359
- syncBridge = Z(() => this.historyManager, this.pushInFlight);
1403
+ pushInFlight = new Q();
1404
+ syncBridge = Le(() => this.historyManager, this.pushInFlight);
1360
1405
  get pushableCount$() {
1361
1406
  return this.historyManager.pushableCount$;
1362
1407
  }
@@ -1364,10 +1409,10 @@ var Z = (e, t) => ({
1364
1409
  return this.historyManager.pullableCount$;
1365
1410
  }
1366
1411
  constructor(e) {
1367
- this.rxdb = e, this.historyManager = new J(this.rxdb);
1412
+ this.rxdb = e, this.historyManager = new Ne(this.rxdb);
1368
1413
  }
1369
1414
  init() {
1370
- this.#i &&= (this.historyManager = new J(this.rxdb), !1);
1415
+ this.#i &&= (this.historyManager = new Ne(this.rxdb), !1);
1371
1416
  let t = () => {
1372
1417
  if (!this.#r) {
1373
1418
  this.#r = !0;
@@ -1380,20 +1425,20 @@ var Z = (e, t) => ({
1380
1425
  }, t = () => {
1381
1426
  this.#t = 0, this.#n = null;
1382
1427
  };
1383
- this.rxdb.addEventListener(m, e), this.rxdb.addEventListener(h, t), this.#e.push(() => this.rxdb.removeEventListener(m, e), () => this.rxdb.removeEventListener(h, t));
1428
+ this.rxdb.addEventListener(g, e), this.rxdb.addEventListener(_, t), this.#e.push(() => this.rxdb.removeEventListener(g, e), () => this.rxdb.removeEventListener(_, t));
1384
1429
  }
1385
1430
  this.#t === 0 && (this.#n = this.historyManager.undoSessionGeneration), this.#t += 1;
1386
1431
  };
1387
- this.rxdb.addEventListener(p, t), this.#e.push(() => this.rxdb.removeEventListener(p, t));
1432
+ this.rxdb.addEventListener(h, t), this.#e.push(() => this.rxdb.removeEventListener(h, t));
1388
1433
  let n = (e) => {
1389
1434
  let t = e.entities?.filter((e) => e.namespace === "rxdb" && e.entity === "RxDBChange") ?? [];
1390
1435
  if (t.length > 0 && !this.historyManager.isExecutingUndoRedo()) {
1391
1436
  let e = t.flatMap((e) => {
1392
- let t = Ae(e);
1437
+ let t = ze(e);
1393
1438
  return t === null ? [] : [t];
1394
1439
  });
1395
- this.#a(this.historyManager.invalidateRedoStack(e), "invalidateRedoStack");
1396
- let n = je(t);
1440
+ this.#l(this.historyManager.invalidateRedoStack(e), "invalidateRedoStack");
1441
+ let n = Be(t);
1397
1442
  this.#n !== null || n !== null ? this.historyManager.resetSyncCleared(e, {
1398
1443
  generation: this.#n,
1399
1444
  recordAt: n
@@ -1413,68 +1458,108 @@ var Z = (e, t) => ({
1413
1458
  this.historyManager.clearAllUndoHistory(), this.historyManager.resetPullableCount();
1414
1459
  }
1415
1460
  async createBranch(e, t) {
1416
- return le(this, e, t);
1461
+ return pe(this, e, t);
1417
1462
  }
1418
1463
  async removeBranch(e) {
1419
- return Y(this, e);
1464
+ return Pe(this, e);
1420
1465
  }
1421
- async switchBranch(e) {
1422
- if ((await this.getCurrentBranch())?.id === e) return;
1423
- let t = !1;
1466
+ async switchBranch(e, t) {
1467
+ let n = await this.getCurrentBranch();
1468
+ if (n?.id === e) return;
1469
+ let r = !1, i, a = !1;
1424
1470
  try {
1425
- this.rxdb.dispatchEvent(new u(e));
1426
- let { adapter: n } = await this.getLocalRepositories(), r = await Se(this, e), i = await n.switchBranch({
1471
+ if (this.rxdb.dispatchEvent(new f(e)), await this.#o(n?.id ?? null, e, t)) {
1472
+ r = !0, this.#a(e);
1473
+ return;
1474
+ }
1475
+ let { adapter: o } = await this.getLocalRepositories(), s = await De(this, e);
1476
+ y(o, {
1477
+ file: "VersionManager.ts",
1478
+ symbol: "switchBranch",
1479
+ intent: v.branch_materialization
1480
+ }), i = o;
1481
+ let l = await o.switchBranch({
1427
1482
  branchId: e,
1428
- actions: r
1483
+ actions: s,
1484
+ prepare: async ({ executor: e, targetBranchId: r }) => {
1485
+ a = !0, await this.#c(e, n?.id ?? null, r, t);
1486
+ }
1429
1487
  });
1430
- return t = !0, this.historyManager.clearRedoStack(), this.historyManager.setUndoBranch(e), this.rxdb.dispatchEvent(new d(e)), i;
1431
- } catch (n) {
1432
- throw t || this.rxdb.dispatchEvent(new f(e)), n;
1488
+ if (r = !0, this.#a(e), !a) throw new c(`适配器 ${o.constructor.name} 的 switchBranch 没有调用 options.prepare:分支已经切到 ${e},但这次切换一条前置条件都没校验过。适配器必须在解析出目标分支之后、动第一行之前 await 它(见 rxdb-adapter.ts › SwitchBranchOptions.prepare)。`);
1489
+ return l;
1490
+ } catch (t) {
1491
+ throw i && oe(i), r || (this.rxdb.dispatchEvent(new m(e)), await this.#s(n?.id ?? null, e, t)), t;
1433
1492
  }
1434
1493
  }
1435
- async mergeBranch(e, i) {
1494
+ async mergeBranch(e, t) {
1436
1495
  let a = await this.getCurrentBranch();
1437
- if (!a) throw new s("No active branch found");
1496
+ if (!a) throw new c("No active branch found");
1438
1497
  let o = a.id;
1439
1498
  try {
1440
- this.rxdb.dispatchEvent(new t(e, o));
1441
- let r = await Oe(this, e, o, i);
1442
- return r.merged > 0 && this.historyManager.clearUndoHistory(), this.rxdb.dispatchEvent(new n(e, o)), r;
1499
+ this.rxdb.dispatchEvent(new n(e, o));
1500
+ let i = await Fe(this, e, o, t);
1501
+ return i.merged > 0 && this.historyManager.clearUndoHistory(), this.rxdb.dispatchEvent(new r(e, o)), i;
1443
1502
  } catch (t) {
1444
- throw this.rxdb.dispatchEvent(new r(e, o)), t;
1503
+ throw this.rxdb.dispatchEvent(new i(e, o)), t;
1445
1504
  }
1446
1505
  }
1447
1506
  history(e) {
1448
1507
  return this.historyManager.history(e);
1449
1508
  }
1450
1509
  async restoreEntity(e, t) {
1451
- return ke(this, e, t);
1510
+ return Ie(this, e, t);
1452
1511
  }
1453
1512
  async getLocalRepositories() {
1454
- return ne(this.rxdb);
1513
+ return re(this.rxdb);
1455
1514
  }
1456
1515
  async getRemoteRepositories() {
1457
- return re(this.rxdb);
1516
+ return ie(this.rxdb);
1458
1517
  }
1459
1518
  async getCurrentBranch() {
1460
- return te(this.rxdb);
1519
+ return ne(this.rxdb);
1520
+ }
1521
+ #a(e) {
1522
+ this.historyManager.clearRedoStack(), this.historyManager.setUndoBranch(e), this.rxdb.dispatchEvent(new p(e));
1523
+ }
1524
+ async #o(e, t, n) {
1525
+ for (let r of this.rxdb.systemContributions) if (await r.takeOverBranchSwitch({
1526
+ currentBranchId: e,
1527
+ targetBranchId: t,
1528
+ preconditions: n
1529
+ }) === "switched") return !0;
1530
+ return !1;
1531
+ }
1532
+ async #s(e, t, n) {
1533
+ for (let r of this.rxdb.systemContributions) await r.settleBranchSwitchFailure({
1534
+ currentBranchId: e,
1535
+ targetBranchId: t,
1536
+ error: n
1537
+ });
1538
+ }
1539
+ async #c(e, t, n, r) {
1540
+ for (let i of this.rxdb.systemContributions) await i.prepareBranchSwitch({
1541
+ executor: e,
1542
+ currentBranchId: t,
1543
+ targetBranchId: n,
1544
+ preconditions: r
1545
+ });
1461
1546
  }
1462
- #a(e, t) {
1547
+ #l(e, t) {
1463
1548
  e.catch((e) => {
1464
- A(e) || console.error(`[VersionManager] ${t} failed:`, e);
1549
+ N(e) || console.error(`[VersionManager] ${t} failed:`, e);
1465
1550
  });
1466
1551
  }
1467
- }, $ = class extends c {
1552
+ }, $ = class extends l {
1468
1553
  lifecycle = "scoped";
1469
1554
  name = "history";
1470
1555
  install(e) {
1471
- let t = new Me(this.rxdb);
1556
+ let t = new Ve(this.rxdb);
1472
1557
  e.acquire(() => (Object.defineProperty(this.rxdb, "versionManager", {
1473
1558
  value: t,
1474
1559
  configurable: !0,
1475
1560
  enumerable: !0
1476
1561
  }), () => void Reflect.deleteProperty(this.rxdb, "versionManager")), "history:slot"), e.acquire(() => () => t.destroy(), "history:versionManager"), t.init(), e.acquire(() => this.rxdb.syncState.bindPushableCount(t.pushableCount$), "history:pushableCount");
1477
1562
  }
1478
- }, Ne = (e) => new $(e);
1563
+ }, He = (e) => new $(e);
1479
1564
  //#endregion
1480
- export { X as PushInFlightRegistry, H as RxDBCrossScopeTransactionError, $ as RxDBPluginHistory, A as isIgnorableDetachedVersionEventError, Ne as rxDBPluginHistory };
1565
+ export { Q as PushInFlightRegistry, U as RxDBCrossScopeTransactionError, $ as RxDBPluginHistory, q as compute_switch_branch_actions, G as find_branch_path_to_root, K as find_switch_branch_step, Y as get_branch_max_change, N as isIgnorableDetachedVersionEventError, He as rxDBPluginHistory };