@aiao/rxdb-adapter-sqliteai 0.0.24 → 0.0.26

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,1537 @@
1
+ import { n as e, t } from "./RxDBAdapterSqliteai-Bebaerj4.js";
2
+ import { ENTITY_LOCAL_CREATE_EVENT as n, MergeBranchBeginEvent as r, MergeBranchCommitEvent as i, MergeBranchFailedEvent as a, REPOSITORY_SYNC_COMPLETE_EVENT as o, RxDB as s, RxDBBranch as c, RxDBChange as l, RxDBError as u, RxDBPluginBase as d, RxDBSync as f, SwitchBranchBeginEvent as p, SwitchBranchCommitEvent as m, SwitchBranchRollbackEvent as h, SyncType as ee, TRANSACTION_BEGIN as g, TRANSACTION_COMMIT as _, TRANSACTION_ROLLBACK as v, buildPushableRepositoryRules as te, getCurrentBranch as ne, getEntityMetadata as y, getLocalSystemRepositories as re, getRemoteSystemRepositories as ie, getRxDBChangeKey as b, getRxDBEntityIdentityKey as x, isAdapterShutdownError as S, resolve_current_branch as ae } from "@aiao/rxdb";
3
+ import { BehaviorSubject as C, EMPTY as oe, Observable as se, ReplaySubject as ce, Subject as le, catchError as ue, combineLatest as w, filter as T, firstValueFrom as E, map as D, shareReplay as O, switchMap as k, takeUntil as A } from "rxjs";
4
+ import { isNil as j } from "@aiao/utils";
5
+ //#region \0rolldown/runtime.js
6
+ var M = Object.defineProperty, de = (e, t) => {
7
+ let n = {};
8
+ for (var r in e) M(n, r, {
9
+ get: e[r],
10
+ enumerable: !0
11
+ });
12
+ return t || M(n, Symbol.toStringTag, { value: "Module" }), n;
13
+ }, fe = async (e, t, n) => {
14
+ let { branchRepository: r, adapter: i } = await e.getLocalRepositories();
15
+ if ((await r.find({
16
+ where: {
17
+ combinator: "and",
18
+ rules: [{
19
+ field: "id",
20
+ operator: "=",
21
+ value: t
22
+ }]
23
+ },
24
+ limit: 1
25
+ })).length) throw new u(`Branch id (${t}) already exists`);
26
+ if (e.rxdb.config.sync?.remote?.adapter) {
27
+ let { adapter: n } = await e.getRemoteRepositories();
28
+ if (n.branchExists && await n.branchExists(t)) throw new u(`Branch id (${t}) already exists on remote`);
29
+ }
30
+ let a = await i.transaction(async (r) => {
31
+ let i = r.getRepository(c), a = r.getRepository(l);
32
+ if ((await i.find({
33
+ where: {
34
+ combinator: "and",
35
+ rules: [{
36
+ field: "id",
37
+ operator: "=",
38
+ value: t
39
+ }]
40
+ },
41
+ limit: 1
42
+ })).length) return `Branch id (${t}) already exists`;
43
+ let o, s;
44
+ if (n) {
45
+ let e = (await a.find({
46
+ where: {
47
+ combinator: "and",
48
+ rules: [{
49
+ field: "id",
50
+ operator: "=",
51
+ value: n
52
+ }]
53
+ },
54
+ limit: 1
55
+ }))[0];
56
+ if (!e) return `Change ID (${n}) not found`;
57
+ s = e, o = (await i.find({
58
+ where: {
59
+ combinator: "and",
60
+ rules: [{
61
+ field: "id",
62
+ operator: "=",
63
+ value: e.branchId
64
+ }]
65
+ },
66
+ limit: 1
67
+ }))[0];
68
+ } else o = await ae(i, e.rxdb), s = await pe(a, o.id);
69
+ if (!o) return "Source branch not found";
70
+ let u = e.rxdb.entityManager.instantiate(c);
71
+ return u.id = t, u.activated = !1, u.local = !0, u.remote = !1, u.fromChangeId = s?.id ?? null, u.parentId = o.id, await i.create(u), u;
72
+ });
73
+ if (typeof a == "string") throw new u(a);
74
+ return a;
75
+ }, pe = async (e, t) => (await e.find({
76
+ where: {
77
+ combinator: "and",
78
+ rules: [t ? {
79
+ field: "branchId",
80
+ operator: "=",
81
+ value: t
82
+ } : {
83
+ field: "branch.activated",
84
+ operator: "=",
85
+ value: !0
86
+ }, {
87
+ field: "revertChangeId",
88
+ operator: "=",
89
+ value: null
90
+ }]
91
+ },
92
+ orderBy: [{
93
+ field: "id",
94
+ sort: "desc"
95
+ }],
96
+ limit: 1
97
+ }))[0], me = (e) => {
98
+ if (!e || typeof e != "object") return !1;
99
+ let t = "name" in e ? String(e.name) : "";
100
+ return ("errno" in e ? Number(e.errno) : void 0) === 44 || t === "AbortError" || S(e);
101
+ };
102
+ function N(e) {
103
+ if (e.length === 1) {
104
+ let t = e[0];
105
+ return `${t.type === "INSERT" ? "创建" : t.type === "UPDATE" ? "更新" : "删除"} ${t.entity}`;
106
+ }
107
+ let t = {};
108
+ for (let n of e) {
109
+ let e = n.type.toLowerCase();
110
+ t[e] = (t[e] ?? 0) + 1;
111
+ }
112
+ let n = [];
113
+ return t.insert && n.push(`创建${t.insert}条`), t.update && n.push(`更新${t.update}条`), t.delete && n.push(`删除${t.delete}条`), `事务: ${n.join(", ")}`;
114
+ }
115
+ function P(e) {
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 = [
117
+ s,
118
+ x(t.entityId),
119
+ i.getTime()
120
+ ].join(":"), l = e.some((e) => j(e.revertChangeId) === !1), u = e.some((e) => j(e.redoInvalidatedAt) === !1);
121
+ return {
122
+ transactionId: r,
123
+ changeId: e.reduce((e, t) => t.id > e ? t.id : e, e[0].id),
124
+ fingerprint: c,
125
+ changes: e,
126
+ type: s,
127
+ count: n,
128
+ createdAt: i,
129
+ description: N(e),
130
+ namespace: a,
131
+ entity: o,
132
+ reverted: l,
133
+ redoInvalidated: u
134
+ };
135
+ }
136
+ function F(e) {
137
+ let t = [], n = [], r;
138
+ return e.forEach((e) => {
139
+ e.transactionId && e.transactionId === r ? n.push(e) : (r = e.transactionId, n.length &&= (t.push(P([...n])), 0), e.transactionId ? n.push(e) : t.push(P([e])));
140
+ }), n.length && t.push(P([...n])), t;
141
+ }
142
+ var I = (e) => `${e.namespace}:${e.entity}`;
143
+ function L(e, t) {
144
+ let n = new Map(t);
145
+ for (let t of e) {
146
+ if (t.lastPushedChangeId === null) continue;
147
+ let e = I(t), r = n.get(e);
148
+ r !== void 0 && r >= t.lastPushedChangeId || n.set(e, t.lastPushedChangeId);
149
+ }
150
+ return n;
151
+ }
152
+ function R(e, t) {
153
+ return t.type === "database" ? e : e.map((e) => {
154
+ 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);
155
+ return n.length === 0 ? null : {
156
+ ...e,
157
+ changes: n,
158
+ count: n.length,
159
+ description: N(n)
160
+ };
161
+ }).filter((e) => e !== null);
162
+ }
163
+ function z(e, t, n = 0, r = null) {
164
+ return e.filter((e) => !e.reverted && e.changes.every((e) => {
165
+ let i = e.remoteId == null, a = t.get(I(e)), o = a == null || e.id > a, s = e.id > n, c = r === null || e.createdAt.getTime() > r.getTime();
166
+ return i && o && s && c;
167
+ }));
168
+ }
169
+ function he(e) {
170
+ return e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}:${x(e.entityId)}`;
171
+ }
172
+ function ge(e) {
173
+ if (!e) return { type: "database" };
174
+ if (Object.getPrototypeOf(e) === Object.prototype && "type" in e) return e;
175
+ let t = y(e), n = "id" in e ? e.id : void 0, r = typeof n == "string" || typeof n == "number" || typeof n == "bigint" ? n : void 0;
176
+ return r === void 0 ? {
177
+ type: "repository",
178
+ namespace: t.namespace,
179
+ entity: t.name
180
+ } : {
181
+ type: "entity",
182
+ namespace: t.namespace,
183
+ entity: t.name,
184
+ entityId: r
185
+ };
186
+ }
187
+ function _e(e, t) {
188
+ let n = ge(t), r = he(n), i = e.history_cache.get(r);
189
+ if (i) return i;
190
+ let a = () => {
191
+ let t = (e.history_ref_counts.get(r) || 0) - 1;
192
+ t <= 0 ? (e.history_cache.delete(r), e.history_ref_counts.delete(r)) : e.history_ref_counts.set(r, t);
193
+ }, o = () => {
194
+ let t = (e.history_ref_counts.get(r) || 0) + 1;
195
+ e.history_ref_counts.set(r, t), e.history_cache.set(r, h);
196
+ }, s = (e) => new se((t) => {
197
+ o();
198
+ let n = e.subscribe(t);
199
+ return () => {
200
+ n.unsubscribe(), a();
201
+ };
202
+ }), c = e.histories$.pipe(D((e) => R(e, n)), O({
203
+ bufferSize: 1,
204
+ refCount: !0
205
+ })), l = s(c), u = s(e.undoHistories$.pipe(D((e) => R(e, n)), O({
206
+ bufferSize: 1,
207
+ refCount: !0
208
+ }))), d = s(e.redoHistories$.pipe(D((e) => R(e, n)), O({
209
+ bufferSize: 1,
210
+ refCount: !0
211
+ }))), f = s(c.pipe(D((e) => e.length), O({
212
+ bufferSize: 1,
213
+ refCount: !0
214
+ }))), p = s(u.pipe(D((e) => e.length), O({
215
+ bufferSize: 1,
216
+ refCount: !0
217
+ }))), m = s(d.pipe(D((e) => e.length), O({
218
+ bufferSize: 1,
219
+ refCount: !0
220
+ }))), h = {
221
+ type: n.type,
222
+ histories$: l,
223
+ undoHistories$: u,
224
+ redoHistories$: d,
225
+ count$: f,
226
+ undoCount$: p,
227
+ redoCount$: m,
228
+ undo: (t = 1) => e.runSerialized(async () => {
229
+ let r = e.undoSession$.value;
230
+ if (r.state === "cleared") return;
231
+ let { histories: i, lastPushedMap: a } = await e.fetchLatestHistories(r.boundary);
232
+ if (!e.isUndoSessionCurrent(r)) return;
233
+ let o = z(i, a, r.boundary.changeId, r.boundary.createdAfter), s = e.selectWholeTransactions(o, n, t);
234
+ s.length !== 0 && await e.applyUndoRedoHistories("undo", s, r);
235
+ }),
236
+ redo: (t = 1) => e.runSerialized(async () => {
237
+ let r = await E(e.redoHistories$), i = e.selectWholeTransactions(r, n, t);
238
+ i.length !== 0 && await e.applyUndoRedoHistories("redo", i);
239
+ })
240
+ };
241
+ return h;
242
+ }
243
+ var B = {
244
+ changeId: 0,
245
+ createdAfter: null
246
+ };
247
+ function ve(e, t) {
248
+ return e?.repositoryFilter !== void 0 && e.repositoryFilter.length > 0 ? !1 : !t.hasMore && t.failures.length === 0;
249
+ }
250
+ function ye(e, t) {
251
+ return t.complete && !t.concurrent ? 0 : Math.max(0, e - t.pulled);
252
+ }
253
+ var be = 1e3, xe = class {
254
+ #e = new C([]);
255
+ get items$() {
256
+ return this.#e.asObservable();
257
+ }
258
+ get value() {
259
+ return this.#e.value;
260
+ }
261
+ push(e) {
262
+ let t = [...e, ...this.#e.value], n = t.length > 1e3 ? t.slice(0, be) : t;
263
+ this.#e.next(n);
264
+ }
265
+ remove(e) {
266
+ let t = new Set(e.map((e) => e.fingerprint)), n = this.#e.value, r = n.filter((e) => t.has(e.fingerprint));
267
+ return r.length === 0 || this.#e.next(n.filter((e) => !t.has(e.fingerprint))), r;
268
+ }
269
+ clear() {
270
+ this.#e.next([]);
271
+ }
272
+ };
273
+ function V(e, t) {
274
+ return t.type === "database" ? !0 : e.namespace !== t.namespace || e.entity !== t.entity ? !1 : t.type === "repository" || e.entityId === t.entityId;
275
+ }
276
+ function Se(e, t) {
277
+ return e.changes.some((e) => V(e, t));
278
+ }
279
+ function Ce(e, t) {
280
+ return e.changes.every((e) => V(e, t));
281
+ }
282
+ function we(e, t, n) {
283
+ let r = e.filter((e) => Se(e, t)).slice(0, Math.max(0, n)), i = [], a = [];
284
+ for (let e of r) Ce(e, t) ? a.push(e) : i.push(e);
285
+ return {
286
+ crossScope: i,
287
+ selected: a
288
+ };
289
+ }
290
+ var Te = (e) => e.type === "database" ? "database" : e.type === "repository" ? `${e.namespace}:${e.entity}` : `${e.namespace}:${e.entity}#${String(e.entityId)}`, Ee = (e, t) => {
291
+ let n = /* @__PURE__ */ new Set();
292
+ 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}`);
293
+ return [...n].join(", ");
294
+ }, De = class e extends u {
295
+ scope;
296
+ histories;
297
+ constructor(t, n) {
298
+ 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);
299
+ }
300
+ }, H = (e) => e.fromChangeId ?? 0, Oe = (e) => {
301
+ let { branches: t, currentBranch: n, nextBranch: r } = e, i = e.currentChangeId ?? H(n), a = e.nextChangeId ?? H(r);
302
+ if (i === a) return [];
303
+ if (n.id === r.id) return [{
304
+ branch: n,
305
+ fromChangeId: i,
306
+ toChangeId: a
307
+ }];
308
+ let o = /* @__PURE__ */ new Map();
309
+ for (let e of t) o.set(e.id, e);
310
+ let s = (e) => {
311
+ let t = [e], n = /* @__PURE__ */ new Set([e.id]), r = e;
312
+ for (; r.parentId;) {
313
+ if (n.has(r.parentId)) throw new u(`Branch history is corrupt: cycle detected at branch '${r.id}' (parentId '${r.parentId}' already visited)`);
314
+ let e = o.get(r.parentId);
315
+ if (!e) throw new u(`Branch history is corrupt: branch '${r.id}' references missing parent '${r.parentId}'`);
316
+ n.add(e.id), t.push(e), r = e;
317
+ }
318
+ return t;
319
+ }, c = s(n), l = s(r), d = null, f = -1;
320
+ for (let e = 0; e < c.length; e++) if (l.findIndex((t) => t.id === c[e].id) !== -1) {
321
+ d = c[e], f = e;
322
+ break;
323
+ }
324
+ let p = [];
325
+ if (d) {
326
+ for (let e = 0; e < f; e++) {
327
+ let t = c[e], n = e === 0 ? i : H(c[e - 1]), r = H(t);
328
+ n !== r && p.push({
329
+ branch: t,
330
+ fromChangeId: n,
331
+ toChangeId: r
332
+ });
333
+ }
334
+ let e = l.findIndex((e) => e.id === d.id);
335
+ if (e === 0) {
336
+ let e = f === 0 ? i : H(c[f - 1]), t = a;
337
+ e !== t && p.push({
338
+ branch: d,
339
+ fromChangeId: e,
340
+ toChangeId: t
341
+ });
342
+ } else if (e > 0) {
343
+ let t = f === 0 ? i : H(c[f - 1]), n = H(l[e - 1]);
344
+ t !== n && p.push({
345
+ branch: d,
346
+ fromChangeId: t,
347
+ toChangeId: n
348
+ });
349
+ }
350
+ let t = l.slice(0, e).reverse();
351
+ for (let e = 0; e < t.length; e++) {
352
+ let n = t[e], r = H(n), i = e === t.length - 1 ? a : H(t[e + 1]);
353
+ r !== i && p.push({
354
+ branch: n,
355
+ fromChangeId: r,
356
+ toChangeId: i
357
+ });
358
+ }
359
+ } else {
360
+ for (let e = 0; e < c.length; e++) {
361
+ let t = c[e], n = e === 0 ? i : H(c[e - 1]), r = H(t);
362
+ n !== r && p.push({
363
+ branch: t,
364
+ fromChangeId: n,
365
+ toChangeId: r
366
+ });
367
+ }
368
+ let e = c[c.length - 1], t = H(e);
369
+ t !== 0 && p.push({
370
+ branch: e,
371
+ fromChangeId: t,
372
+ toChangeId: 0
373
+ });
374
+ let n = l[l.length - 1], r = l.length > 1 ? H(l[l.length - 2]) : a;
375
+ r !== 0 && p.push({
376
+ branch: n,
377
+ fromChangeId: 0,
378
+ toChangeId: r
379
+ });
380
+ let o = l.slice(0, l.length - 1).reverse();
381
+ for (let e = 0; e < o.length; e++) {
382
+ let t = o[e], n = H(t), r = e === o.length - 1 ? a : H(o[e + 1]);
383
+ n !== r && p.push({
384
+ branch: t,
385
+ fromChangeId: n,
386
+ toChangeId: r
387
+ });
388
+ }
389
+ }
390
+ return p;
391
+ }, ke = async (e, t) => {
392
+ let { branchRepository: n, changeRepository: r } = await e.getLocalRepositories(), i = (await n.find({
393
+ where: {
394
+ combinator: "and",
395
+ rules: [{
396
+ field: "activated",
397
+ operator: "=",
398
+ value: !0
399
+ }]
400
+ },
401
+ limit: 1
402
+ }))[0];
403
+ if (!i) throw new u("Current branch not found");
404
+ let a = await n.find({ where: {
405
+ combinator: "and",
406
+ rules: []
407
+ } }), o = a.find((e) => e.id === t);
408
+ if (!o) throw new u(`Branch (${t}) not found`);
409
+ if (i.id === o.id) throw new u("Cannot switch to the same branch");
410
+ let s = await W(r, i.id), c = await W(r, o.id), l = Oe({
411
+ branches: a,
412
+ currentBranch: i,
413
+ currentChangeId: s ? s.id : null,
414
+ nextBranch: o,
415
+ nextChangeId: c ? c.id : null
416
+ }), d = {
417
+ deletes: /* @__PURE__ */ new Map(),
418
+ updates: /* @__PURE__ */ new Map(),
419
+ inserts: /* @__PURE__ */ new Map()
420
+ };
421
+ for (let e = 0; e < l.length; e++) {
422
+ let { branch: t, fromChangeId: n, toChangeId: i } = l[e], a = n < i, o = n > i, s = Math.min(n, i), c = Math.max(n, i), u = { where: {
423
+ combinator: "and",
424
+ rules: [
425
+ {
426
+ field: "branchId",
427
+ operator: "=",
428
+ value: t.id
429
+ },
430
+ {
431
+ field: "id",
432
+ operator: ">",
433
+ value: s
434
+ },
435
+ {
436
+ field: "id",
437
+ operator: "<=",
438
+ value: c
439
+ },
440
+ {
441
+ field: "revertChangeId",
442
+ operator: "=",
443
+ value: null
444
+ }
445
+ ]
446
+ } };
447
+ t.fromChangeId && s < t.fromChangeId && u.where.rules.push({
448
+ field: "id",
449
+ operator: ">",
450
+ value: t.fromChangeId
451
+ });
452
+ let f = await r.find(u);
453
+ o ? je(f, d) : a && Ae(f, d);
454
+ }
455
+ return d;
456
+ }, Ae = (e, t) => U(e, !0, t), je = (e, t) => U(e, !1, t), U = (e, t, n = {
457
+ deletes: /* @__PURE__ */ new Map(),
458
+ updates: /* @__PURE__ */ new Map(),
459
+ inserts: /* @__PURE__ */ new Map()
460
+ }) => {
461
+ if (t) {
462
+ let t = [...e].sort((e, t) => e.id - t.id);
463
+ for (let e of t) {
464
+ let t = b(e);
465
+ switch (e.type) {
466
+ case "INSERT":
467
+ n.inserts.set(t, {
468
+ patch: { ...e.patch },
469
+ inversePatch: null
470
+ });
471
+ break;
472
+ case "UPDATE":
473
+ {
474
+ let r = n.inserts.get(t) || n.updates.get(t);
475
+ r ? (r.patch && e.patch && Object.assign(r.patch, e.patch), r.inversePatch === null && e.inversePatch ? r.inversePatch = { ...e.inversePatch } : r.inversePatch && e.inversePatch && Object.assign(r.inversePatch, e.inversePatch)) : n.updates.set(t, {
476
+ patch: { ...e.patch },
477
+ inversePatch: { ...e.inversePatch }
478
+ });
479
+ }
480
+ break;
481
+ case "DELETE": n.deletes.set(t, {
482
+ patch: null,
483
+ inversePatch: { ...e.inversePatch }
484
+ }), n.inserts.delete(t), n.updates.delete(t);
485
+ }
486
+ }
487
+ } else {
488
+ let t = [...e].sort((e, t) => t.id - e.id);
489
+ for (let e of t) {
490
+ let t = b(e);
491
+ switch (e.type) {
492
+ case "INSERT":
493
+ n.deletes.set(t, {
494
+ patch: null,
495
+ inversePatch: { ...e.patch }
496
+ }), n.inserts.delete(t), n.updates.delete(t);
497
+ break;
498
+ case "UPDATE":
499
+ {
500
+ let r = n.inserts.get(t) || n.updates.get(t);
501
+ r ? (r.patch && e.inversePatch && Object.assign(r.patch, e.inversePatch), r.inversePatch && e.patch && Object.assign(r.inversePatch, e.patch)) : n.updates.set(t, {
502
+ patch: { ...e.inversePatch },
503
+ inversePatch: { ...e.patch }
504
+ });
505
+ }
506
+ break;
507
+ case "DELETE": n.inserts.set(t, {
508
+ patch: { ...e.inversePatch },
509
+ inversePatch: null
510
+ });
511
+ }
512
+ }
513
+ }
514
+ return n;
515
+ }, W = async (e, t) => (await e.find({
516
+ where: {
517
+ combinator: "and",
518
+ rules: [{
519
+ field: "branchId",
520
+ operator: "=",
521
+ value: t
522
+ }, {
523
+ field: "revertChangeId",
524
+ operator: "=",
525
+ value: null
526
+ }]
527
+ },
528
+ orderBy: [{
529
+ field: "id",
530
+ sort: "desc"
531
+ }],
532
+ limit: 1
533
+ }))[0], G = (e) => e.getRepository(f);
534
+ async function Me(e, t) {
535
+ let { changeRepository: n, branchRepository: r } = await e.rxdb.versionManager.getLocalRepositories(), i = await r.find({ where: {
536
+ combinator: "and",
537
+ rules: [{
538
+ field: "activated",
539
+ operator: "=",
540
+ value: !0
541
+ }]
542
+ } });
543
+ if (i.length === 0) return {
544
+ histories: [],
545
+ lastPushedMap: /* @__PURE__ */ new Map()
546
+ };
547
+ let a = i[0], o = L(await G(await E(e.rxdb.localAdapter$)).find({ where: {
548
+ combinator: "and",
549
+ rules: [{
550
+ field: "branchId",
551
+ operator: "=",
552
+ value: a.id
553
+ }]
554
+ } }), e.rxdb.versionManager.pushInFlight.snapshot()), s = [{
555
+ field: "branchId",
556
+ operator: "=",
557
+ value: a.id
558
+ }, {
559
+ field: "createdAt",
560
+ operator: ">=",
561
+ value: e.getFirstConnectedAt()
562
+ }];
563
+ return t.changeId > 0 && s.push({
564
+ field: "id",
565
+ operator: ">",
566
+ value: t.changeId
567
+ }), {
568
+ histories: F(await n.find({
569
+ where: {
570
+ combinator: "and",
571
+ rules: s
572
+ },
573
+ orderBy: [{
574
+ field: "id",
575
+ sort: "desc"
576
+ }]
577
+ })),
578
+ lastPushedMap: o
579
+ };
580
+ }
581
+ async function Ne(e, t, n, r) {
582
+ e.isUndoRedoInProgress = !0;
583
+ try {
584
+ let i = n.flatMap((e) => e.changes).sort((e, n) => t === "undo" ? n.id - e.id : e.id - n.id), a = U(i, t === "redo"), o = e.getNextRevertStateUpdatedAt(i);
585
+ if (t === "undo") {
586
+ let { adapter: t } = await e.rxdb.versionManager.getLocalRepositories(), n = await t.getRxDBChangeSequence(), r = /* @__PURE__ */ new Date();
587
+ i.forEach((e, t) => {
588
+ let i = `rxdb:RxDBChange:${e.id}`, s = a.updates.get(i) || {
589
+ patch: {},
590
+ inversePatch: null
591
+ };
592
+ a.updates.set(i, {
593
+ patch: {
594
+ ...s.patch,
595
+ revertChangeId: n + t + 1,
596
+ revertChangedAt: r,
597
+ updatedAt: o
598
+ },
599
+ inversePatch: s.inversePatch
600
+ });
601
+ }), a.updateRxDBChangeSequence = n + i.length, e.redoInvalidationFloor = n + i.length;
602
+ } else i.forEach((e) => {
603
+ let t = `rxdb:RxDBChange:${e.id}`, n = a.updates.get(t) || {
604
+ patch: {},
605
+ inversePatch: null
606
+ };
607
+ a.updates.set(t, {
608
+ patch: {
609
+ ...n.patch,
610
+ revertChangeId: null,
611
+ updatedAt: o
612
+ },
613
+ inversePatch: n.inversePatch
614
+ });
615
+ });
616
+ let { adapter: s } = await e.rxdb.versionManager.getLocalRepositories();
617
+ if (t === "undo" && (r === void 0 || !e.isUndoSessionCurrent(r))) return;
618
+ await s.switchBranch({ actions: a }), e.pushableCountTrigger$.next(Date.now()), e.setRevertStateWatermarks(i, t === "undo", o), t === "undo" ? e.pushToRedoStack(n) : e.removeFromRedoStack(n);
619
+ } finally {
620
+ e.isUndoRedoInProgress = !1;
621
+ }
622
+ }
623
+ async function Pe(e) {
624
+ let t = ++e.pushableGeneration, n = (n) => {
625
+ t === e.pushableGeneration && e.pushableCount$.next(n);
626
+ };
627
+ try {
628
+ if (!await E(e.rxdb.connected$)) {
629
+ n(0);
630
+ return;
631
+ }
632
+ let t = G(await E(e.rxdb.localAdapter$)), r = e.rxdb.entityManager.getRepository(l), i = await E(e.rxdb.entityManager.getRepository(c).findOne({ where: {
633
+ combinator: "and",
634
+ rules: [{
635
+ field: "activated",
636
+ operator: "=",
637
+ value: !0
638
+ }]
639
+ } }));
640
+ if (!i) {
641
+ n(0);
642
+ return;
643
+ }
644
+ let a = await t.find({ where: {
645
+ combinator: "and",
646
+ rules: [{
647
+ field: "branchId",
648
+ operator: "=",
649
+ value: i.id
650
+ }]
651
+ } }), o = te(e.rxdb.config.entities, e.rxdb.config.sync, a);
652
+ if (o.length === 0) {
653
+ n(0);
654
+ return;
655
+ }
656
+ n(await E(r.count({ where: {
657
+ combinator: "and",
658
+ rules: [
659
+ {
660
+ field: "branchId",
661
+ operator: "=",
662
+ value: i.id
663
+ },
664
+ {
665
+ field: "revertChangeId",
666
+ operator: "=",
667
+ value: null
668
+ },
669
+ {
670
+ field: "remoteId",
671
+ operator: "=",
672
+ value: null
673
+ },
674
+ {
675
+ combinator: "or",
676
+ rules: o
677
+ }
678
+ ]
679
+ } })));
680
+ } catch (t) {
681
+ !e.destroyed && !S(t) && (console.error("[#updatePushableCount] error", t), e.errors$.next(t instanceof Error ? t : Error(String(t)))), n(0);
682
+ }
683
+ }
684
+ var K = (e) => e.reduce((e, t) => t < e ? t : e, Infinity), q = class {
685
+ rxdb;
686
+ #e = [];
687
+ #t = !1;
688
+ #n;
689
+ #r;
690
+ #i = new ce(1);
691
+ #a = Promise.resolve();
692
+ #o = new C(0);
693
+ #s = 0;
694
+ #c = new C(0);
695
+ #l = 0;
696
+ #u = new C(0);
697
+ #d = /* @__PURE__ */ new Map();
698
+ #f = new C(0);
699
+ #p = 0;
700
+ #m;
701
+ #h = null;
702
+ #g = /* @__PURE__ */ new Date();
703
+ #_ = /* @__PURE__ */ new Map();
704
+ #v = null;
705
+ #y = 0;
706
+ #b = null;
707
+ #x = new C({
708
+ generation: 0,
709
+ state: "active",
710
+ boundary: B
711
+ });
712
+ isUndoRedoInProgress = !1;
713
+ isInvalidatingRedo = !1;
714
+ syncDepth = 0;
715
+ redoStack = new xe();
716
+ history_cache = /* @__PURE__ */ new Map();
717
+ history_ref_counts = /* @__PURE__ */ new Map();
718
+ histories$;
719
+ undoHistories$;
720
+ redoHistories$;
721
+ undoCount$;
722
+ redoCount$;
723
+ errors$ = new le();
724
+ pushableCount$;
725
+ pullableCount$;
726
+ count$;
727
+ get undoSessionGeneration() {
728
+ return this.#x.value.generation;
729
+ }
730
+ constructor(e) {
731
+ this.rxdb = e, this.#n = this.#R(), this.#r = this.#z();
732
+ let t = e.entityManager.getRepository(c), n = e.entityManager.getRepository(l), r = t.findOne({ where: {
733
+ combinator: "and",
734
+ rules: [{
735
+ field: "activated",
736
+ operator: "=",
737
+ value: !0
738
+ }]
739
+ } });
740
+ this.#e.push(r.pipe(A(this.#i)).subscribe({
741
+ next: (e) => this.#E(e?.id ?? null),
742
+ error: (e) => this.#T("undo session 分支跟随的活跃分支流已中断", e)
743
+ })), this.#m = w({
744
+ connected: this.rxdb.connected$,
745
+ branch: r
746
+ }).pipe(T(({ connected: e, branch: t }) => e && !!t), k(({ branch: e }) => {
747
+ let t = this.#M();
748
+ return n.findAll({
749
+ where: {
750
+ combinator: "and",
751
+ rules: [{
752
+ field: "branchId",
753
+ operator: "=",
754
+ value: e.id
755
+ }, {
756
+ field: "createdAt",
757
+ operator: ">=",
758
+ value: t
759
+ }]
760
+ },
761
+ orderBy: [{
762
+ field: "id",
763
+ sort: "desc"
764
+ }]
765
+ });
766
+ }), A(this.#i));
767
+ let i = this.#m.pipe(D((e) => F(e)), O({
768
+ bufferSize: 1,
769
+ refCount: !0
770
+ }));
771
+ this.histories$ = w([i, this.#f]).pipe(D(([e]) => this.#O(e)), O({
772
+ bufferSize: 1,
773
+ refCount: !0
774
+ })), this.count$ = this.histories$.pipe(D((e) => e.length), O({
775
+ bufferSize: 1,
776
+ refCount: !0
777
+ })), this.undoHistories$ = w({
778
+ histories: this.histories$,
779
+ undoSession: this.#x,
780
+ trigger: this.#u
781
+ }).pipe(k(async ({ histories: e, undoSession: t }) => {
782
+ if (t.state === "cleared") return [];
783
+ try {
784
+ let n = await E(this.rxdb.entityManager.getRepository(c).findOne({ where: {
785
+ combinator: "and",
786
+ rules: [{
787
+ field: "activated",
788
+ operator: "=",
789
+ value: !0
790
+ }]
791
+ } }));
792
+ return n ? z(e, L(await G(await E(this.rxdb.localAdapter$)).find({ where: {
793
+ combinator: "and",
794
+ rules: [{
795
+ field: "branchId",
796
+ operator: "=",
797
+ value: n.id
798
+ }]
799
+ } }), this.rxdb.versionManager.pushInFlight.snapshot()), t.boundary.changeId, t.boundary.createdAfter) : [];
800
+ } catch (e) {
801
+ let t = e instanceof Error ? e : Error(String(e));
802
+ return this.errors$.next(t), [];
803
+ }
804
+ }), O({
805
+ bufferSize: 1,
806
+ refCount: !0
807
+ })), this.redoHistories$ = this.redoStack.items$, this.undoCount$ = this.undoHistories$.pipe(D((e) => e.length), O({
808
+ bufferSize: 1,
809
+ refCount: !0
810
+ })), this.redoCount$ = this.redoHistories$.pipe(D((e) => e.length), O({
811
+ bufferSize: 1,
812
+ refCount: !0
813
+ })), this.pushableCount$ = this.#c.asObservable(), this.pullableCount$ = this.#o.asObservable();
814
+ let a = w({
815
+ connected: this.rxdb.connected$,
816
+ branch: r
817
+ }).pipe(T(({ connected: e, branch: t }) => e && !!t), k(({ branch: e }) => {
818
+ let t = [
819
+ {
820
+ field: "branchId",
821
+ operator: "=",
822
+ value: e.id
823
+ },
824
+ {
825
+ field: "revertChangeId",
826
+ operator: "=",
827
+ value: null
828
+ },
829
+ {
830
+ field: "remoteId",
831
+ operator: "=",
832
+ value: null
833
+ }
834
+ ];
835
+ return n.count({ where: {
836
+ combinator: "and",
837
+ rules: t
838
+ } }).pipe(ue((e) => (this.#T("pushableCount 的变更计数查询", e), oe)));
839
+ })).subscribe({
840
+ next: () => {
841
+ this.#L();
842
+ },
843
+ error: (e) => this.#T("pushableCount 重算的活跃分支流已中断", e)
844
+ });
845
+ this.#e.push(a), this.rxdb.addEventListener(o, this.#F), this.#L();
846
+ }
847
+ destroy() {
848
+ this.#t = !0, this.#i.next(), this.#i.complete();
849
+ for (let e of this.#e) e.unsubscribe();
850
+ this.#e.length = 0, this.rxdb.removeEventListener(o, this.#F), this.#d.clear(), this.errors$.complete();
851
+ }
852
+ incrementPullableCount(e) {
853
+ this.#s++;
854
+ let t = this.#o.value + e;
855
+ this.#o.next(t);
856
+ }
857
+ resetPullableCount() {
858
+ this.#s++, this.#o.next(0);
859
+ }
860
+ beginPullableSettlement() {
861
+ return this.#s;
862
+ }
863
+ reconcilePullableCount(e, t) {
864
+ let n = e === this.#s ? t : Math.max(this.#o.value, t);
865
+ this.#o.next(n);
866
+ }
867
+ settlePullableCount(e, t) {
868
+ this.#o.next(ye(this.#o.value, {
869
+ complete: t.complete,
870
+ concurrent: e !== this.#s,
871
+ pulled: t.pulled
872
+ }));
873
+ }
874
+ pushToRedoStack(e) {
875
+ this.redoStack.push(e);
876
+ }
877
+ removeFromRedoStack(e) {
878
+ return this.redoStack.remove(e);
879
+ }
880
+ clearRedoStack() {
881
+ this.redoStack.clear();
882
+ }
883
+ setUndoBranch(e) {
884
+ this.#E(e);
885
+ }
886
+ clearUndoHistory() {
887
+ this.#w({
888
+ generation: this.#C(),
889
+ state: "cleared",
890
+ boundary: this.#x.value.boundary,
891
+ clearedAt: /* @__PURE__ */ new Date()
892
+ }), this.clearRedoStack();
893
+ }
894
+ clearAllUndoHistory() {
895
+ let e = /* @__PURE__ */ new Date(), t = (t) => ({
896
+ generation: this.#C(),
897
+ state: "cleared",
898
+ boundary: t.boundary,
899
+ clearedAt: e
900
+ });
901
+ for (let [e, n] of this.#_) this.#_.set(e, t(n));
902
+ this.#v = t(this.#v ?? {
903
+ generation: 0,
904
+ state: "active",
905
+ boundary: B
906
+ });
907
+ let n = this.#b === null ? void 0 : this.#_.get(this.#b);
908
+ this.#x.next(n ?? this.#v), this.clearRedoStack();
909
+ }
910
+ resetSyncCleared(e = [], t) {
911
+ let n = this.#x.value;
912
+ if (n.state === "active") return;
913
+ let r = e.filter((e) => Number.isSafeInteger(e) && e > 0);
914
+ if (t === void 0) {
915
+ if (r.length === 0) return;
916
+ let e = K(r);
917
+ this.#w({
918
+ generation: n.generation,
919
+ state: "active",
920
+ boundary: {
921
+ changeId: Math.max(n.boundary.changeId, e - 1),
922
+ createdAfter: n.boundary.createdAfter
923
+ }
924
+ });
925
+ return;
926
+ }
927
+ if (!(t.generation === null ? t.recordAt !== null && Number.isFinite(t.recordAt.getTime()) && t.recordAt.getTime() > n.clearedAt.getTime() : t.generation === n.generation)) return;
928
+ let i = r.length > 0 ? K(r) : null, a = i === null && (n.boundary.createdAfter === null || n.boundary.createdAfter.getTime() < n.clearedAt.getTime()) ? n.clearedAt : n.boundary.createdAfter;
929
+ this.#w({
930
+ generation: n.generation,
931
+ state: "active",
932
+ boundary: {
933
+ changeId: i === null ? n.boundary.changeId : Math.max(n.boundary.changeId, i - 1),
934
+ createdAfter: a
935
+ }
936
+ });
937
+ }
938
+ isExecutingUndoRedo() {
939
+ return this.isUndoRedoInProgress || this.isInvalidatingRedo || this.syncDepth > 0;
940
+ }
941
+ async syncing(e) {
942
+ this.syncDepth += 1;
943
+ try {
944
+ return await e();
945
+ } finally {
946
+ --this.syncDepth;
947
+ }
948
+ }
949
+ async invalidateRedoStack(e) {
950
+ return this.#j(async () => {
951
+ if (!(this.isUndoRedoInProgress || this.isInvalidatingRedo) && !(e?.length && e.every((e) => e <= this.#p))) {
952
+ this.isInvalidatingRedo = !0;
953
+ try {
954
+ let e = await E(this.redoHistories$);
955
+ if (e.length === 0) return;
956
+ let t = e.flatMap((e) => e.changes), n = /* @__PURE__ */ new Date(), r = U([], !1), { adapter: i } = await this.rxdb.versionManager.getLocalRepositories();
957
+ t.forEach((e) => {
958
+ let t = `rxdb:RxDBChange:${e.id}`;
959
+ r.updates.set(t, {
960
+ patch: { redoInvalidatedAt: n },
961
+ inversePatch: { redoInvalidatedAt: null }
962
+ });
963
+ }), await i.switchBranch({ actions: r }), this.clearRedoStack();
964
+ } catch (e) {
965
+ throw console.error("[HistoryManager] Failed to invalidate redo stack:", e), e;
966
+ } finally {
967
+ this.isInvalidatingRedo = !1;
968
+ }
969
+ }
970
+ });
971
+ }
972
+ history(e) {
973
+ return _e(this.#n, e);
974
+ }
975
+ #S(e, t, n) {
976
+ let { crossScope: r, selected: i } = we(e, t, n);
977
+ if (r.length > 0) throw new De(t, r);
978
+ return i;
979
+ }
980
+ #C() {
981
+ return ++this.#y;
982
+ }
983
+ #w(e) {
984
+ this.#b !== null && this.#_.set(this.#b, e), this.#x.next(e);
985
+ }
986
+ #T(e, t) {
987
+ this.#t || S(t) || (console.error(`[HistoryManager] ${e}:`, t), this.errors$.next(t instanceof Error ? t : Error(String(t))));
988
+ }
989
+ #E(e) {
990
+ if (e === this.#b || (this.#b === null && e !== null && !this.#_.has(e) && this.#_.set(e, this.#x.value), this.#b = e, e === null)) return;
991
+ let t = this.#_.get(e) ?? this.#D();
992
+ this.#_.set(e, t), this.#x.next(t);
993
+ }
994
+ #D() {
995
+ let e = this.#C(), t = this.#v;
996
+ return t === null ? {
997
+ generation: e,
998
+ state: "active",
999
+ boundary: B
1000
+ } : {
1001
+ ...t,
1002
+ generation: e
1003
+ };
1004
+ }
1005
+ #O(e) {
1006
+ return e.map((e) => {
1007
+ let t = !1;
1008
+ for (let n of e.changes) {
1009
+ let e = {
1010
+ reverted: n.revertChangeId != null,
1011
+ updatedAt: n.updatedAt.getTime()
1012
+ }, r = this.#d.get(n.id), i = r && r.updatedAt >= e.updatedAt ? r : e;
1013
+ r && e.updatedAt > r.updatedAt && this.#d.set(n.id, e), t ||= i.reverted;
1014
+ }
1015
+ return t === e.reverted ? e : {
1016
+ ...e,
1017
+ reverted: t
1018
+ };
1019
+ });
1020
+ }
1021
+ #k(e) {
1022
+ let t = Date.now();
1023
+ for (let n of e) {
1024
+ let e = this.#d.get(n.id)?.updatedAt ?? 0;
1025
+ t = Math.max(t, n.updatedAt.getTime() + 1, e + 1);
1026
+ }
1027
+ return new Date(t);
1028
+ }
1029
+ #A(e, t, n) {
1030
+ for (let r of e) this.#d.set(r.id, {
1031
+ reverted: t,
1032
+ updatedAt: n.getTime()
1033
+ });
1034
+ this.#f.next(this.#f.value + 1);
1035
+ }
1036
+ #j(e) {
1037
+ let t = this.#a.then(e, e);
1038
+ return this.#a = t.catch(() => void 0), t;
1039
+ }
1040
+ #M() {
1041
+ return this.#h ||= this.rxdb.firstConnectedAt ?? this.#g, this.#h;
1042
+ }
1043
+ #N(e) {
1044
+ return this.#x.value === e;
1045
+ }
1046
+ async #P(e) {
1047
+ return Me(this.#r, e);
1048
+ }
1049
+ #F = () => {
1050
+ this.#L(), this.#u.next(Date.now());
1051
+ };
1052
+ async #I(e, t, n) {
1053
+ return Ne(this.#r, e, t, n);
1054
+ }
1055
+ async #L() {
1056
+ return Pe(this.#r);
1057
+ }
1058
+ #R() {
1059
+ let e = this;
1060
+ return {
1061
+ get history_cache() {
1062
+ return e.history_cache;
1063
+ },
1064
+ get history_ref_counts() {
1065
+ return e.history_ref_counts;
1066
+ },
1067
+ get histories$() {
1068
+ return e.histories$;
1069
+ },
1070
+ get undoHistories$() {
1071
+ return e.undoHistories$;
1072
+ },
1073
+ get redoHistories$() {
1074
+ return e.redoHistories$;
1075
+ },
1076
+ get undoSession$() {
1077
+ return e.#x;
1078
+ },
1079
+ runSerialized: (t) => e.#j(t),
1080
+ fetchLatestHistories: (t) => e.#P(t),
1081
+ isUndoSessionCurrent: (t) => e.#N(t),
1082
+ selectWholeTransactions: (t, n, r) => e.#S(t, n, r),
1083
+ applyUndoRedoHistories: (t, n, r) => e.#I(t, n, r)
1084
+ };
1085
+ }
1086
+ #z() {
1087
+ let e = this;
1088
+ return {
1089
+ get rxdb() {
1090
+ return e.rxdb;
1091
+ },
1092
+ get destroyed() {
1093
+ return e.#t;
1094
+ },
1095
+ get isUndoRedoInProgress() {
1096
+ return e.isUndoRedoInProgress;
1097
+ },
1098
+ set isUndoRedoInProgress(t) {
1099
+ e.isUndoRedoInProgress = t;
1100
+ },
1101
+ get redoInvalidationFloor() {
1102
+ return e.#p;
1103
+ },
1104
+ set redoInvalidationFloor(t) {
1105
+ e.#p = t;
1106
+ },
1107
+ get pushableGeneration() {
1108
+ return e.#l;
1109
+ },
1110
+ set pushableGeneration(t) {
1111
+ e.#l = t;
1112
+ },
1113
+ get pushableCount$() {
1114
+ return e.#c;
1115
+ },
1116
+ get pushableCountTrigger$() {
1117
+ return e.#u;
1118
+ },
1119
+ get errors$() {
1120
+ return e.errors$;
1121
+ },
1122
+ getFirstConnectedAt: () => e.#M(),
1123
+ isUndoSessionCurrent: (t) => e.#N(t),
1124
+ getNextRevertStateUpdatedAt: (t) => e.#k(t),
1125
+ setRevertStateWatermarks: (t, n, r) => e.#A(t, n, r),
1126
+ pushToRedoStack: (t) => e.pushToRedoStack(t),
1127
+ removeFromRedoStack: (t) => e.removeFromRedoStack(t)
1128
+ };
1129
+ }
1130
+ }, J = async (e, t) => {
1131
+ let { adapter: n } = await e.getLocalRepositories();
1132
+ if (t === "main") throw new u("Cannot remove main branch");
1133
+ let r = await n.transaction(async (e) => {
1134
+ let n = e.getRepository(c), r = e.getRepository(l), i = (await n.find({
1135
+ where: {
1136
+ combinator: "and",
1137
+ rules: [{
1138
+ field: "id",
1139
+ operator: "=",
1140
+ value: t
1141
+ }]
1142
+ },
1143
+ limit: 1
1144
+ }))[0];
1145
+ if (!i) return `Branch '${t}' not found`;
1146
+ if (i.activated) return `Cannot remove active branch '${t}'. Switch to another branch first.`;
1147
+ if ((await n.find({
1148
+ where: {
1149
+ combinator: "and",
1150
+ rules: [{
1151
+ field: "parentId",
1152
+ operator: "=",
1153
+ value: t
1154
+ }, {
1155
+ field: "id",
1156
+ operator: "!=",
1157
+ value: t
1158
+ }]
1159
+ },
1160
+ limit: 1
1161
+ }))?.length) return `Cannot remove branch '${t}' because it has child branches`;
1162
+ let a = await r.find({ where: {
1163
+ combinator: "and",
1164
+ rules: [{
1165
+ field: "branchId",
1166
+ operator: "=",
1167
+ value: t
1168
+ }]
1169
+ } });
1170
+ await e.removeMany([...a, i]);
1171
+ });
1172
+ if (r) throw new u(r);
1173
+ }, Fe = async (e, t, n, r) => {
1174
+ let i = r?.strategy ?? "squash", a = r?.deleteSource ?? !1, { branchRepository: o, changeRepository: s, adapter: c } = await e.getLocalRepositories();
1175
+ if (t === n) throw new u(`Cannot merge branch '${t}' into itself`);
1176
+ let l = (await o.find({
1177
+ where: {
1178
+ combinator: "and",
1179
+ rules: [{
1180
+ field: "id",
1181
+ operator: "=",
1182
+ value: t
1183
+ }]
1184
+ },
1185
+ limit: 1
1186
+ }))[0];
1187
+ if (!l) throw new u(`Branch '${t}' not found`);
1188
+ let d = await s.find({
1189
+ where: {
1190
+ combinator: "and",
1191
+ rules: [
1192
+ {
1193
+ field: "branchId",
1194
+ operator: "=",
1195
+ value: t
1196
+ },
1197
+ {
1198
+ field: "revertChangeId",
1199
+ operator: "=",
1200
+ value: null
1201
+ },
1202
+ ...l.fromChangeId == null ? [] : [{
1203
+ field: "id",
1204
+ operator: ">",
1205
+ value: l.fromChangeId
1206
+ }]
1207
+ ]
1208
+ },
1209
+ orderBy: [{
1210
+ field: "id",
1211
+ sort: "asc"
1212
+ }]
1213
+ }), f = async () => {
1214
+ if (!a) return { deleted: !1 };
1215
+ try {
1216
+ return await J(e, t), { deleted: !0 };
1217
+ } catch (e) {
1218
+ return {
1219
+ deleted: !1,
1220
+ error: e instanceof Error ? e : Error(String(e))
1221
+ };
1222
+ }
1223
+ }, p = (e, t) => ({
1224
+ merged: e,
1225
+ strategy: i,
1226
+ sourceDeleted: t.deleted,
1227
+ ...t.error ? { sourceDeleteError: t.error } : {}
1228
+ });
1229
+ if (d.length === 0) return p(0, await f());
1230
+ let m;
1231
+ if (i === "normal") await c.transaction(async (e) => {
1232
+ for (let t of d) {
1233
+ let n = {
1234
+ deletes: /* @__PURE__ */ new Map(),
1235
+ updates: /* @__PURE__ */ new Map(),
1236
+ inserts: /* @__PURE__ */ new Map()
1237
+ }, r = b(t);
1238
+ t.type === "INSERT" ? n.inserts.set(r, {
1239
+ patch: t.patch,
1240
+ inversePatch: null
1241
+ }) : t.type === "UPDATE" ? n.updates.set(r, {
1242
+ patch: t.patch,
1243
+ inversePatch: t.inversePatch
1244
+ }) : t.type === "DELETE" && n.deletes.set(r, {
1245
+ patch: null,
1246
+ inversePatch: t.inversePatch
1247
+ }), await e.mergeChanges(n, void 0, !1);
1248
+ }
1249
+ }), m = d.length;
1250
+ else {
1251
+ let e = U(d, !0), t = new Set(d.filter((e) => e.type === "INSERT").map((e) => b(e)));
1252
+ for (let n of t) e.deletes.has(n) && e.deletes.delete(n);
1253
+ if (m = e.inserts.size + e.updates.size + e.deletes.size, m === 0) return p(0, await f());
1254
+ await c.mergeChanges(e, void 0, !1);
1255
+ }
1256
+ return p(m, await f());
1257
+ }, Ie = class {
1258
+ #e = /* @__PURE__ */ new Map();
1259
+ #t = 0;
1260
+ session() {
1261
+ let e = ++this.#t, t = /* @__PURE__ */ new Map();
1262
+ return this.#e.set(e, t), {
1263
+ claim: (e, n) => {
1264
+ let r = t.get(e);
1265
+ r !== void 0 && r >= n || t.set(e, n);
1266
+ },
1267
+ release: () => {
1268
+ this.#e.delete(e);
1269
+ }
1270
+ };
1271
+ }
1272
+ snapshot() {
1273
+ let e = /* @__PURE__ */ new Map();
1274
+ for (let t of this.#e.values()) for (let [n, r] of t) {
1275
+ let t = e.get(n);
1276
+ t !== void 0 && t >= r || e.set(n, r);
1277
+ }
1278
+ return e;
1279
+ }
1280
+ };
1281
+ async function Le(e, t, n) {
1282
+ let { changeRepository: r, adapter: i } = await e.getLocalRepositories(), a = await r.find({
1283
+ where: {
1284
+ combinator: "and",
1285
+ rules: [{
1286
+ field: "id",
1287
+ operator: "=",
1288
+ value: Number(n.changeId)
1289
+ }]
1290
+ },
1291
+ limit: 1
1292
+ });
1293
+ if (a.length === 0) throw new u(`RxDBChange not found: ${n.changeId}`);
1294
+ let o = a[0];
1295
+ if (o.type !== "DELETE") throw new u(`Cannot restore from non-DELETE change (type=${o.type})`);
1296
+ if (!o.inversePatch) throw new u(`RxDBChange ${n.changeId} has no inversePatch`);
1297
+ let s = t.constructor, c = y(s), l = await e.getCurrentBranch();
1298
+ if (o.namespace !== c.namespace || o.entity !== c.name) throw new u(`RxDBChange ${n.changeId} belongs to ${o.namespace}:${o.entity}, not ${c.namespace}:${c.name}`);
1299
+ if (o.branchId != null && o.branchId !== l.id) throw new u(`RxDBChange ${n.changeId} belongs to branch '${o.branchId}', current branch is '${l.id}'`);
1300
+ let d = U([o], !1);
1301
+ await i.mergeChanges(d, void 0, !1);
1302
+ let f = await i.getRepository(s).find({
1303
+ where: {
1304
+ combinator: "and",
1305
+ rules: [{
1306
+ field: "id",
1307
+ operator: "=",
1308
+ value: o.entityId
1309
+ }]
1310
+ },
1311
+ limit: 1
1312
+ });
1313
+ if (!f[0]) throw new u(`Restore produced no row for ${c.namespace}:${c.name} id=${String(o.entityId)}`);
1314
+ return f[0];
1315
+ }
1316
+ var Re = (e, t) => ({
1317
+ pushInFlight: t,
1318
+ syncing: (t) => e().syncing(t),
1319
+ clearUndoHistory: () => e().clearUndoHistory(),
1320
+ beginPullableSettlement: () => e().beginPullableSettlement(),
1321
+ settlePull: (t, n, r) => e().settlePullableCount(t, {
1322
+ complete: ve(n, r),
1323
+ pulled: r.pulled
1324
+ }),
1325
+ settleAbortedPull: (t, n) => e().settlePullableCount(t, {
1326
+ complete: !1,
1327
+ pulled: n
1328
+ }),
1329
+ reconcilePullableCount: (t, n) => e().reconcilePullableCount(t, n),
1330
+ incrementPullableCount: (t) => e().incrementPullableCount(t)
1331
+ }), Y = (e) => typeof e == "number" && Number.isSafeInteger(e) && e > 0 ? e : null, ze = (e) => {
1332
+ let t = Y(e.id);
1333
+ return t === null ? typeof e.patch != "object" || e.patch === null || !("id" in e.patch) ? null : Y(e.patch.id) : t;
1334
+ }, Be = (e) => {
1335
+ let t = null;
1336
+ for (let n of e) n.recordAt instanceof Date && Number.isFinite(n.recordAt.getTime()) && (t === null || n.recordAt.getTime() < t.getTime()) && (t = n.recordAt);
1337
+ return t;
1338
+ }, Ve = class {
1339
+ rxdb;
1340
+ #e = [];
1341
+ #t = 0;
1342
+ #n = null;
1343
+ #r = !1;
1344
+ #i = !1;
1345
+ historyManager;
1346
+ pushInFlight = new Ie();
1347
+ syncBridge = Re(() => this.historyManager, this.pushInFlight);
1348
+ get pushableCount$() {
1349
+ return this.historyManager.pushableCount$;
1350
+ }
1351
+ get pullableCount$() {
1352
+ return this.historyManager.pullableCount$;
1353
+ }
1354
+ constructor(e) {
1355
+ this.rxdb = e, this.historyManager = new q(this.rxdb);
1356
+ }
1357
+ init() {
1358
+ this.#i &&= (this.historyManager = new q(this.rxdb), !1);
1359
+ let e = () => {
1360
+ if (!this.#r) {
1361
+ this.#r = !0;
1362
+ let e = () => {
1363
+ if (this.#t > 1) {
1364
+ --this.#t;
1365
+ return;
1366
+ }
1367
+ this.#t = 0, this.#n = null;
1368
+ }, t = () => {
1369
+ this.#t = 0, this.#n = null;
1370
+ };
1371
+ this.rxdb.addEventListener(_, e), this.rxdb.addEventListener(v, t), this.#e.push(() => this.rxdb.removeEventListener(_, e), () => this.rxdb.removeEventListener(v, t));
1372
+ }
1373
+ this.#t === 0 && (this.#n = this.historyManager.undoSessionGeneration), this.#t += 1;
1374
+ };
1375
+ this.rxdb.addEventListener(g, e), this.#e.push(() => this.rxdb.removeEventListener(g, e));
1376
+ let t = (e) => {
1377
+ let t = e.entities?.filter((e) => e.namespace === "rxdb" && e.entity === "RxDBChange") ?? [];
1378
+ if (t.length > 0 && !this.historyManager.isExecutingUndoRedo()) {
1379
+ let e = t.flatMap((e) => {
1380
+ let t = ze(e);
1381
+ return t === null ? [] : [t];
1382
+ });
1383
+ this.#a(this.historyManager.invalidateRedoStack(e), "invalidateRedoStack");
1384
+ let n = Be(t);
1385
+ this.#n !== null || n !== null ? this.historyManager.resetSyncCleared(e, {
1386
+ generation: this.#n,
1387
+ recordAt: n
1388
+ }) : this.historyManager.resetSyncCleared(e);
1389
+ }
1390
+ };
1391
+ this.rxdb.addEventListener(n, t), this.#e.push(() => this.rxdb.removeEventListener(n, t));
1392
+ }
1393
+ destroy() {
1394
+ if (!this.#i) {
1395
+ this.#i = !0, this.historyManager.destroy();
1396
+ for (let e of this.#e) e();
1397
+ this.#e.length = 0, this.#t = 0, this.#n = null, this.#r = !1;
1398
+ }
1399
+ }
1400
+ resetSessionState() {
1401
+ this.historyManager.clearAllUndoHistory(), this.historyManager.resetPullableCount();
1402
+ }
1403
+ async createBranch(e, t) {
1404
+ return fe(this, e, t);
1405
+ }
1406
+ async removeBranch(e) {
1407
+ return J(this, e);
1408
+ }
1409
+ async switchBranch(e) {
1410
+ if ((await this.getCurrentBranch())?.id === e) return;
1411
+ let t = !1;
1412
+ try {
1413
+ this.rxdb.dispatchEvent(new p(e));
1414
+ let { adapter: n } = await this.getLocalRepositories(), r = await ke(this, e), i = await n.switchBranch({
1415
+ branchId: e,
1416
+ actions: r
1417
+ });
1418
+ return t = !0, this.historyManager.clearRedoStack(), this.historyManager.setUndoBranch(e), this.rxdb.dispatchEvent(new m(e)), i;
1419
+ } catch (n) {
1420
+ throw t || this.rxdb.dispatchEvent(new h(e)), n;
1421
+ }
1422
+ }
1423
+ async mergeBranch(e, t) {
1424
+ let n = await this.getCurrentBranch();
1425
+ if (!n) throw new u("No active branch found");
1426
+ let o = n.id;
1427
+ try {
1428
+ this.rxdb.dispatchEvent(new r(e, o));
1429
+ let n = await Fe(this, e, o, t);
1430
+ return n.merged > 0 && this.historyManager.clearUndoHistory(), this.rxdb.dispatchEvent(new i(e, o)), n;
1431
+ } catch (t) {
1432
+ throw this.rxdb.dispatchEvent(new a(e, o)), t;
1433
+ }
1434
+ }
1435
+ history(e) {
1436
+ return this.historyManager.history(e);
1437
+ }
1438
+ async restoreEntity(e, t) {
1439
+ return Le(this, e, t);
1440
+ }
1441
+ async getLocalRepositories() {
1442
+ return re(this.rxdb);
1443
+ }
1444
+ async getRemoteRepositories() {
1445
+ return ie(this.rxdb);
1446
+ }
1447
+ async getCurrentBranch() {
1448
+ return ne(this.rxdb);
1449
+ }
1450
+ #a(e, t) {
1451
+ e.catch((e) => {
1452
+ me(e) || console.error(`[VersionManager] ${t} failed:`, e);
1453
+ });
1454
+ }
1455
+ }, He = class extends d {
1456
+ lifecycle = "scoped";
1457
+ name = "history";
1458
+ install(e) {
1459
+ let t = new Ve(this.rxdb);
1460
+ e.acquire(() => (Object.defineProperty(this.rxdb, "versionManager", {
1461
+ value: t,
1462
+ configurable: !0,
1463
+ enumerable: !0
1464
+ }), () => 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");
1465
+ }
1466
+ }, Ue = (e) => new He(e), We = /* @__PURE__ */ de({
1467
+ sqliteaiEncryptedFactory: () => Je,
1468
+ sqliteaiFactory: () => Ke
1469
+ }), Ge = class extends t {
1470
+ queryCount = 0;
1471
+ query(...e) {
1472
+ return this.queryCount++, super.query(...e);
1473
+ }
1474
+ }, X = /* @__PURE__ */ new WeakMap(), Z = () => void 0, Q = /* @__PURE__ */ new WeakMap(), $ = (e) => {
1475
+ let t = Q.get(e);
1476
+ t && (Q.delete(e), t.terminate());
1477
+ }, Ke = {
1478
+ name: "sqliteai",
1479
+ async createAdapter(e) {
1480
+ return await qe(e);
1481
+ },
1482
+ async createClient(t, n) {
1483
+ return await e(t, {
1484
+ printErr: Z,
1485
+ ...n
1486
+ });
1487
+ },
1488
+ cleanupAdapter(e) {
1489
+ $(e.rxdb);
1490
+ }
1491
+ };
1492
+ async function qe(e) {
1493
+ let { entities: t, persistent: n, ...r } = e ?? {}, i = (t ?? []).slice(), a = `sqliteai-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, o = new s({
1494
+ dbName: a,
1495
+ context: { userId: "userId" },
1496
+ entities: i,
1497
+ sync: {
1498
+ local: { adapter: "sqliteai" },
1499
+ type: ee.None
1500
+ }
1501
+ });
1502
+ try {
1503
+ let e;
1504
+ return o.adapter("sqliteai", async (t) => {
1505
+ $(t);
1506
+ let i = n === !0 ? new Worker(new URL(
1507
+ /* @vite-ignore */
1508
+ "/assets/sqliteai-test.worker-CTOPs2O0.js",
1509
+ "" + import.meta.url
1510
+ ), {
1511
+ type: "module",
1512
+ name: `${a}-worker`
1513
+ }) : void 0;
1514
+ return i && Q.set(t, i), e = new Ge(t, {
1515
+ ...i ? {
1516
+ opfs: !0,
1517
+ opfsFallback: "throw",
1518
+ worker: !0,
1519
+ workerInstance: i
1520
+ } : { printErr: Z },
1521
+ ...r
1522
+ }), e;
1523
+ }), o.use(Ue), await o.getAdapter("sqliteai"), await o.connect("sqliteai"), e;
1524
+ } catch (e) {
1525
+ throw $(o), e;
1526
+ }
1527
+ }
1528
+ var Je = {
1529
+ name: "sqliteai",
1530
+ getQueryCount: (e) => X.get(e)?.() ?? 0,
1531
+ createAdapter: async (e) => {
1532
+ let t = await qe(e);
1533
+ return X.set(t, () => t.queryCount), t;
1534
+ }
1535
+ }, Ye = (/* @__PURE__ */ Object.assign({ "./__tests__/sqliteai-factory.ts": We }))["./__tests__/sqliteai-factory.ts"].sqliteaiFactory;
1536
+ //#endregion
1537
+ export { Ye as sqliteaiFactory };