@tanstack/db 0.5.23 → 0.5.25
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/cjs/collection/change-events.cjs +1 -1
- package/dist/cjs/collection/change-events.cjs.map +1 -1
- package/dist/cjs/collection/changes.cjs +6 -1
- package/dist/cjs/collection/changes.cjs.map +1 -1
- package/dist/cjs/collection/lifecycle.cjs +11 -0
- package/dist/cjs/collection/lifecycle.cjs.map +1 -1
- package/dist/cjs/collection/subscription.cjs +18 -5
- package/dist/cjs/collection/subscription.cjs.map +1 -1
- package/dist/cjs/collection/subscription.d.cts +7 -1
- package/dist/cjs/indexes/base-index.cjs.map +1 -1
- package/dist/cjs/indexes/base-index.d.cts +10 -6
- package/dist/cjs/indexes/btree-index.cjs +64 -24
- package/dist/cjs/indexes/btree-index.cjs.map +1 -1
- package/dist/cjs/indexes/btree-index.d.cts +31 -9
- package/dist/cjs/indexes/reverse-index.cjs +6 -0
- package/dist/cjs/indexes/reverse-index.cjs.map +1 -1
- package/dist/cjs/indexes/reverse-index.d.cts +4 -2
- package/dist/cjs/query/builder/index.cjs +2 -2
- package/dist/cjs/query/builder/index.cjs.map +1 -1
- package/dist/cjs/query/live/collection-config-builder.cjs +4 -1
- package/dist/cjs/query/live/collection-config-builder.cjs.map +1 -1
- package/dist/cjs/query/live/collection-subscriber.cjs +111 -30
- package/dist/cjs/query/live/collection-subscriber.cjs.map +1 -1
- package/dist/cjs/query/live/collection-subscriber.d.cts +5 -0
- package/dist/cjs/types.d.cts +16 -0
- package/dist/cjs/utils/comparison.cjs +16 -0
- package/dist/cjs/utils/comparison.cjs.map +1 -1
- package/dist/cjs/utils/comparison.d.cts +21 -0
- package/dist/esm/collection/change-events.js +1 -1
- package/dist/esm/collection/change-events.js.map +1 -1
- package/dist/esm/collection/changes.js +6 -1
- package/dist/esm/collection/changes.js.map +1 -1
- package/dist/esm/collection/lifecycle.js +11 -0
- package/dist/esm/collection/lifecycle.js.map +1 -1
- package/dist/esm/collection/subscription.d.ts +7 -1
- package/dist/esm/collection/subscription.js +18 -5
- package/dist/esm/collection/subscription.js.map +1 -1
- package/dist/esm/indexes/base-index.d.ts +10 -6
- package/dist/esm/indexes/base-index.js.map +1 -1
- package/dist/esm/indexes/btree-index.d.ts +31 -9
- package/dist/esm/indexes/btree-index.js +65 -25
- package/dist/esm/indexes/btree-index.js.map +1 -1
- package/dist/esm/indexes/reverse-index.d.ts +4 -2
- package/dist/esm/indexes/reverse-index.js +6 -0
- package/dist/esm/indexes/reverse-index.js.map +1 -1
- package/dist/esm/query/builder/index.js +2 -2
- package/dist/esm/query/builder/index.js.map +1 -1
- package/dist/esm/query/live/collection-config-builder.js +4 -1
- package/dist/esm/query/live/collection-config-builder.js.map +1 -1
- package/dist/esm/query/live/collection-subscriber.d.ts +5 -0
- package/dist/esm/query/live/collection-subscriber.js +112 -31
- package/dist/esm/query/live/collection-subscriber.js.map +1 -1
- package/dist/esm/types.d.ts +16 -0
- package/dist/esm/utils/comparison.d.ts +21 -0
- package/dist/esm/utils/comparison.js +16 -0
- package/dist/esm/utils/comparison.js.map +1 -1
- package/package.json +1 -1
- package/src/collection/change-events.ts +1 -1
- package/src/collection/changes.ts +6 -1
- package/src/collection/lifecycle.ts +14 -0
- package/src/collection/subscription.ts +38 -10
- package/src/indexes/base-index.ts +19 -6
- package/src/indexes/btree-index.ts +101 -30
- package/src/indexes/reverse-index.ts +13 -2
- package/src/query/builder/index.ts +4 -4
- package/src/query/live/collection-config-builder.ts +4 -5
- package/src/query/live/collection-subscriber.ts +173 -50
- package/src/types.ts +16 -0
- package/src/utils/comparison.ts +34 -0
|
@@ -25,24 +25,17 @@ class CollectionSubscriber {
|
|
|
25
25
|
}
|
|
26
26
|
subscribeToChanges(whereExpression) {
|
|
27
27
|
const orderByInfo = this.getOrderByInfo();
|
|
28
|
-
const
|
|
29
|
-
if (
|
|
30
|
-
let resolve;
|
|
31
|
-
const promise = new Promise((res) => {
|
|
32
|
-
resolve = res;
|
|
33
|
-
});
|
|
34
|
-
this.subscriptionLoadingPromises.set(subscription2, {
|
|
35
|
-
resolve
|
|
36
|
-
});
|
|
28
|
+
const trackLoadResult = (result) => {
|
|
29
|
+
if (result instanceof Promise) {
|
|
37
30
|
this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(
|
|
38
|
-
|
|
31
|
+
result
|
|
39
32
|
);
|
|
40
33
|
}
|
|
41
34
|
};
|
|
42
35
|
const onStatusChange = (event) => {
|
|
43
36
|
const subscription2 = event.subscription;
|
|
44
37
|
if (event.status === `loadingSubset`) {
|
|
45
|
-
|
|
38
|
+
this.ensureLoadingPromise(subscription2);
|
|
46
39
|
} else {
|
|
47
40
|
const deferred = this.subscriptionLoadingPromises.get(subscription2);
|
|
48
41
|
if (deferred) {
|
|
@@ -56,7 +49,8 @@ class CollectionSubscriber {
|
|
|
56
49
|
subscription = this.subscribeToOrderedChanges(
|
|
57
50
|
whereExpression,
|
|
58
51
|
orderByInfo,
|
|
59
|
-
onStatusChange
|
|
52
|
+
onStatusChange,
|
|
53
|
+
trackLoadResult
|
|
60
54
|
);
|
|
61
55
|
} else {
|
|
62
56
|
const includeInitialState = !this.collectionConfigBuilder.isLazyAlias(
|
|
@@ -69,7 +63,7 @@ class CollectionSubscriber {
|
|
|
69
63
|
);
|
|
70
64
|
}
|
|
71
65
|
if (subscription.status === `loadingSubset`) {
|
|
72
|
-
|
|
66
|
+
this.ensureLoadingPromise(subscription);
|
|
73
67
|
}
|
|
74
68
|
const unsubscribe = () => {
|
|
75
69
|
const deferred = this.subscriptionLoadingPromises.get(subscription);
|
|
@@ -113,18 +107,55 @@ class CollectionSubscriber {
|
|
|
113
107
|
const sendChanges = (changes) => {
|
|
114
108
|
this.sendChangesToPipeline(changes);
|
|
115
109
|
};
|
|
110
|
+
const { orderBy, limit, offset } = this.collectionConfigBuilder.query;
|
|
111
|
+
const effectiveLimit = limit !== void 0 && offset !== void 0 ? limit + offset : limit;
|
|
112
|
+
const normalizedOrderBy = orderBy ? expressions.normalizeOrderByPaths(orderBy, this.alias) : void 0;
|
|
113
|
+
const canPassOrderBy = normalizedOrderBy?.every((clause) => {
|
|
114
|
+
const exp = clause.expression;
|
|
115
|
+
if (exp.type !== `ref`) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
const path = exp.path;
|
|
119
|
+
return Array.isArray(path) && path.length === 1;
|
|
120
|
+
}) ?? false;
|
|
121
|
+
const orderByForSubscription = canPassOrderBy ? normalizedOrderBy : void 0;
|
|
122
|
+
const limitForSubscription = canPassOrderBy ? effectiveLimit : void 0;
|
|
123
|
+
const onLoadSubsetResult = includeInitialState ? (result) => {
|
|
124
|
+
if (result instanceof Promise) {
|
|
125
|
+
this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(
|
|
126
|
+
result
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
} : void 0;
|
|
116
130
|
const subscription = this.collection.subscribeChanges(sendChanges, {
|
|
117
131
|
...includeInitialState && { includeInitialState },
|
|
118
132
|
whereExpression,
|
|
119
|
-
onStatusChange
|
|
133
|
+
onStatusChange,
|
|
134
|
+
orderBy: orderByForSubscription,
|
|
135
|
+
limit: limitForSubscription,
|
|
136
|
+
onLoadSubsetResult
|
|
120
137
|
});
|
|
121
138
|
return subscription;
|
|
122
139
|
}
|
|
123
|
-
subscribeToOrderedChanges(whereExpression, orderByInfo, onStatusChange) {
|
|
140
|
+
subscribeToOrderedChanges(whereExpression, orderByInfo, onStatusChange, onLoadSubsetResult) {
|
|
124
141
|
const { orderBy, offset, limit, index } = orderByInfo;
|
|
142
|
+
const handleLoadSubsetResult = (result) => {
|
|
143
|
+
if (result instanceof Promise) {
|
|
144
|
+
this.pendingOrderedLoadPromise = result;
|
|
145
|
+
result.finally(() => {
|
|
146
|
+
if (this.pendingOrderedLoadPromise === result) {
|
|
147
|
+
this.pendingOrderedLoadPromise = void 0;
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
onLoadSubsetResult(result);
|
|
152
|
+
};
|
|
153
|
+
this.orderedLoadSubsetResult = handleLoadSubsetResult;
|
|
125
154
|
const subscriptionHolder = {};
|
|
126
155
|
const sendChangesInRange = (changes) => {
|
|
127
|
-
const
|
|
156
|
+
const changesArray = Array.isArray(changes) ? changes : [...changes];
|
|
157
|
+
this.trackSentValues(changesArray, orderByInfo.comparator);
|
|
158
|
+
const splittedChanges = splitUpdates(changesArray);
|
|
128
159
|
this.sendChangesToPipelineWithTracking(
|
|
129
160
|
splittedChanges,
|
|
130
161
|
subscriptionHolder.current
|
|
@@ -137,6 +168,8 @@ class CollectionSubscriber {
|
|
|
137
168
|
subscriptionHolder.current = subscription;
|
|
138
169
|
const truncateUnsubscribe = this.collection.on(`truncate`, () => {
|
|
139
170
|
this.biggest = void 0;
|
|
171
|
+
this.lastLoadRequestKey = void 0;
|
|
172
|
+
this.pendingOrderedLoadPromise = void 0;
|
|
140
173
|
this.sentToD2Keys.clear();
|
|
141
174
|
});
|
|
142
175
|
subscription.on(`unsubscribed`, () => {
|
|
@@ -147,12 +180,16 @@ class CollectionSubscriber {
|
|
|
147
180
|
subscription.setOrderByIndex(index);
|
|
148
181
|
subscription.requestLimitedSnapshot({
|
|
149
182
|
limit: offset + limit,
|
|
150
|
-
orderBy: normalizedOrderBy
|
|
183
|
+
orderBy: normalizedOrderBy,
|
|
184
|
+
trackLoadSubsetPromise: false,
|
|
185
|
+
onLoadSubsetResult: handleLoadSubsetResult
|
|
151
186
|
});
|
|
152
187
|
} else {
|
|
153
188
|
subscription.requestSnapshot({
|
|
154
189
|
orderBy: normalizedOrderBy,
|
|
155
|
-
limit: offset + limit
|
|
190
|
+
limit: offset + limit,
|
|
191
|
+
trackLoadSubsetPromise: false,
|
|
192
|
+
onLoadSubsetResult: handleLoadSubsetResult
|
|
156
193
|
});
|
|
157
194
|
}
|
|
158
195
|
return subscription;
|
|
@@ -169,6 +206,9 @@ class CollectionSubscriber {
|
|
|
169
206
|
if (!dataNeeded) {
|
|
170
207
|
return true;
|
|
171
208
|
}
|
|
209
|
+
if (this.pendingOrderedLoadPromise) {
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
172
212
|
const n = dataNeeded();
|
|
173
213
|
if (n > 0) {
|
|
174
214
|
this.loadNextItems(n, subscription);
|
|
@@ -181,11 +221,10 @@ class CollectionSubscriber {
|
|
|
181
221
|
this.sendChangesToPipeline(changes);
|
|
182
222
|
return;
|
|
183
223
|
}
|
|
184
|
-
const trackedChanges = this.trackSentValues(changes, orderByInfo.comparator);
|
|
185
224
|
const subscriptionWithLoader = subscription;
|
|
186
225
|
subscriptionWithLoader[loadMoreCallbackSymbol] ??= this.loadMoreIfNeeded.bind(this, subscription);
|
|
187
226
|
this.sendChangesToPipeline(
|
|
188
|
-
|
|
227
|
+
changes,
|
|
189
228
|
subscriptionWithLoader[loadMoreCallbackSymbol]
|
|
190
229
|
);
|
|
191
230
|
}
|
|
@@ -199,14 +238,29 @@ class CollectionSubscriber {
|
|
|
199
238
|
const { orderBy, valueExtractorForRawRow, offset } = orderByInfo;
|
|
200
239
|
const biggestSentRow = this.biggest;
|
|
201
240
|
const extractedValues = biggestSentRow ? valueExtractorForRawRow(biggestSentRow) : void 0;
|
|
202
|
-
|
|
241
|
+
let minValues;
|
|
242
|
+
if (extractedValues !== void 0) {
|
|
243
|
+
minValues = Array.isArray(extractedValues) ? extractedValues : [extractedValues];
|
|
244
|
+
}
|
|
245
|
+
const loadRequestKey = this.getLoadRequestKey({
|
|
246
|
+
minValues,
|
|
247
|
+
offset,
|
|
248
|
+
limit: n
|
|
249
|
+
});
|
|
250
|
+
if (this.lastLoadRequestKey === loadRequestKey) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
203
253
|
const normalizedOrderBy = expressions.normalizeOrderByPaths(orderBy, this.alias);
|
|
204
254
|
subscription.requestLimitedSnapshot({
|
|
205
255
|
orderBy: normalizedOrderBy,
|
|
206
256
|
limit: n,
|
|
207
257
|
minValues,
|
|
208
|
-
offset
|
|
258
|
+
// Omit offset so requestLimitedSnapshot can advance the offset based on
|
|
259
|
+
// the number of rows already loaded (supports offset-based backends).
|
|
260
|
+
trackLoadSubsetPromise: false,
|
|
261
|
+
onLoadSubsetResult: this.orderedLoadSubsetResult
|
|
209
262
|
});
|
|
263
|
+
this.lastLoadRequestKey = loadRequestKey;
|
|
210
264
|
}
|
|
211
265
|
getWhereClauseForAlias() {
|
|
212
266
|
const sourceWhereClausesCache = this.collectionConfigBuilder.sourceWhereClausesCache;
|
|
@@ -222,18 +276,45 @@ class CollectionSubscriber {
|
|
|
222
276
|
}
|
|
223
277
|
return void 0;
|
|
224
278
|
}
|
|
225
|
-
|
|
279
|
+
trackSentValues(changes, comparator) {
|
|
226
280
|
for (const change of changes) {
|
|
227
|
-
if (change.type
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
281
|
+
if (change.type === `delete`) {
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const isNewKey = !this.sentToD2Keys.has(change.key);
|
|
285
|
+
if (!this.biggest) {
|
|
286
|
+
this.biggest = change.value;
|
|
287
|
+
this.lastLoadRequestKey = void 0;
|
|
288
|
+
} else if (comparator(this.biggest, change.value) < 0) {
|
|
289
|
+
this.biggest = change.value;
|
|
290
|
+
this.lastLoadRequestKey = void 0;
|
|
291
|
+
} else if (isNewKey) {
|
|
292
|
+
this.lastLoadRequestKey = void 0;
|
|
233
293
|
}
|
|
234
|
-
yield change;
|
|
235
294
|
}
|
|
236
295
|
}
|
|
296
|
+
ensureLoadingPromise(subscription) {
|
|
297
|
+
if (this.subscriptionLoadingPromises.has(subscription)) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
let resolve;
|
|
301
|
+
const promise = new Promise((res) => {
|
|
302
|
+
resolve = res;
|
|
303
|
+
});
|
|
304
|
+
this.subscriptionLoadingPromises.set(subscription, {
|
|
305
|
+
resolve
|
|
306
|
+
});
|
|
307
|
+
this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(
|
|
308
|
+
promise
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
getLoadRequestKey(options) {
|
|
312
|
+
return dbIvm.serializeValue({
|
|
313
|
+
minValues: options.minValues ?? null,
|
|
314
|
+
offset: options.offset,
|
|
315
|
+
limit: options.limit
|
|
316
|
+
});
|
|
317
|
+
}
|
|
237
318
|
}
|
|
238
319
|
function sendChangesToInput(input, changes, getKey) {
|
|
239
320
|
const multiSetArray = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection-subscriber.cjs","sources":["../../../../src/query/live/collection-subscriber.ts"],"sourcesContent":["import { MultiSet } from '@tanstack/db-ivm'\nimport {\n normalizeExpressionPaths,\n normalizeOrderByPaths,\n} from '../compiler/expressions.js'\nimport type { MultiSetArray, RootStreamBuilder } from '@tanstack/db-ivm'\nimport type { Collection } from '../../collection/index.js'\nimport type {\n ChangeMessage,\n SubscriptionStatusChangeEvent,\n} from '../../types.js'\nimport type { Context, GetResult } from '../builder/types.js'\nimport type { BasicExpression } from '../ir.js'\nimport type { OrderByOptimizationInfo } from '../compiler/order-by.js'\nimport type { CollectionConfigBuilder } from './collection-config-builder.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\n\nconst loadMoreCallbackSymbol = Symbol.for(\n `@tanstack/db.collection-config-builder`,\n)\n\nexport class CollectionSubscriber<\n TContext extends Context,\n TResult extends object = GetResult<TContext>,\n> {\n // Keep track of the biggest value we've sent so far (needed for orderBy optimization)\n private biggest: any = undefined\n\n // Track deferred promises for subscription loading states\n private subscriptionLoadingPromises = new Map<\n CollectionSubscription,\n { resolve: () => void }\n >()\n\n // Track keys that have been sent to the D2 pipeline to prevent duplicate inserts\n // This is necessary because different code paths (initial load, change events)\n // can potentially send the same item to D2 multiple times.\n private sentToD2Keys = new Set<string | number>()\n\n constructor(\n private alias: string,\n private collectionId: string,\n private collection: Collection,\n private collectionConfigBuilder: CollectionConfigBuilder<TContext, TResult>,\n ) {}\n\n subscribe(): CollectionSubscription {\n const whereClause = this.getWhereClauseForAlias()\n\n if (whereClause) {\n const whereExpression = normalizeExpressionPaths(whereClause, this.alias)\n return this.subscribeToChanges(whereExpression)\n }\n\n return this.subscribeToChanges()\n }\n\n private subscribeToChanges(whereExpression?: BasicExpression<boolean>) {\n const orderByInfo = this.getOrderByInfo()\n\n // Track load promises using subscription from the event (avoids circular dependency)\n const trackLoadPromise = (subscription: CollectionSubscription) => {\n // Guard against duplicate transitions\n if (!this.subscriptionLoadingPromises.has(subscription)) {\n let resolve: () => void\n const promise = new Promise<void>((res) => {\n resolve = res\n })\n\n this.subscriptionLoadingPromises.set(subscription, {\n resolve: resolve!,\n })\n this.collectionConfigBuilder.liveQueryCollection!._sync.trackLoadPromise(\n promise,\n )\n }\n }\n\n // Status change handler - passed to subscribeChanges so it's registered\n // BEFORE any snapshot is requested, preventing race conditions\n const onStatusChange = (event: SubscriptionStatusChangeEvent) => {\n const subscription = event.subscription as CollectionSubscription\n if (event.status === `loadingSubset`) {\n trackLoadPromise(subscription)\n } else {\n // status is 'ready'\n const deferred = this.subscriptionLoadingPromises.get(subscription)\n if (deferred) {\n // Clear the map entry FIRST (before resolving)\n this.subscriptionLoadingPromises.delete(subscription)\n deferred.resolve()\n }\n }\n }\n\n // Create subscription with onStatusChange - listener is registered before any async work\n let subscription: CollectionSubscription\n if (orderByInfo) {\n subscription = this.subscribeToOrderedChanges(\n whereExpression,\n orderByInfo,\n onStatusChange,\n )\n } else {\n // If the source alias is lazy then we should not include the initial state\n const includeInitialState = !this.collectionConfigBuilder.isLazyAlias(\n this.alias,\n )\n\n subscription = this.subscribeToMatchingChanges(\n whereExpression,\n includeInitialState,\n onStatusChange,\n )\n }\n\n // Check current status after subscribing - if status is 'loadingSubset', track it.\n // The onStatusChange listener will catch the transition to 'ready'.\n if (subscription.status === `loadingSubset`) {\n trackLoadPromise(subscription)\n }\n\n const unsubscribe = () => {\n // If subscription has a pending promise, resolve it before unsubscribing\n const deferred = this.subscriptionLoadingPromises.get(subscription)\n if (deferred) {\n // Clear the map entry FIRST (before resolving)\n this.subscriptionLoadingPromises.delete(subscription)\n deferred.resolve()\n }\n\n subscription.unsubscribe()\n }\n // currentSyncState is always defined when subscribe() is called\n // (called during sync session setup)\n this.collectionConfigBuilder.currentSyncState!.unsubscribeCallbacks.add(\n unsubscribe,\n )\n return subscription\n }\n\n private sendChangesToPipeline(\n changes: Iterable<ChangeMessage<any, string | number>>,\n callback?: () => boolean,\n ) {\n // Filter changes to prevent duplicate inserts to D2 pipeline.\n // This ensures D2 multiplicity stays at 1 for visible items, so deletes\n // properly reduce multiplicity to 0 (triggering DELETE output).\n const changesArray = Array.isArray(changes) ? changes : [...changes]\n const filteredChanges: Array<ChangeMessage<any, string | number>> = []\n for (const change of changesArray) {\n if (change.type === `insert`) {\n if (this.sentToD2Keys.has(change.key)) {\n // Skip duplicate insert - already sent to D2\n continue\n }\n this.sentToD2Keys.add(change.key)\n } else if (change.type === `delete`) {\n // Remove from tracking so future re-inserts are allowed\n this.sentToD2Keys.delete(change.key)\n }\n // Updates are handled as delete+insert by splitUpdates, so no special handling needed\n filteredChanges.push(change)\n }\n\n // currentSyncState and input are always defined when this method is called\n // (only called from active subscriptions during a sync session)\n const input =\n this.collectionConfigBuilder.currentSyncState!.inputs[this.alias]!\n const sentChanges = sendChangesToInput(\n input,\n filteredChanges,\n this.collection.config.getKey,\n )\n\n // Do not provide the callback that loads more data\n // if there's no more data to load\n // otherwise we end up in an infinite loop trying to load more data\n const dataLoader = sentChanges > 0 ? callback : undefined\n\n // We need to schedule a graph run even if there's no data to load\n // because we need to mark the collection as ready if it's not already\n // and that's only done in `scheduleGraphRun`\n this.collectionConfigBuilder.scheduleGraphRun(dataLoader, {\n alias: this.alias,\n })\n }\n\n private subscribeToMatchingChanges(\n whereExpression: BasicExpression<boolean> | undefined,\n includeInitialState: boolean,\n onStatusChange: (event: SubscriptionStatusChangeEvent) => void,\n ): CollectionSubscription {\n const sendChanges = (\n changes: Array<ChangeMessage<any, string | number>>,\n ) => {\n this.sendChangesToPipeline(changes)\n }\n\n // Create subscription with onStatusChange - listener is registered before snapshot\n // Note: For non-ordered queries (no limit/offset), we use trackLoadSubsetPromise: false\n // which is the default behavior in subscribeChanges\n const subscription = this.collection.subscribeChanges(sendChanges, {\n ...(includeInitialState && { includeInitialState }),\n whereExpression,\n onStatusChange,\n })\n\n return subscription\n }\n\n private subscribeToOrderedChanges(\n whereExpression: BasicExpression<boolean> | undefined,\n orderByInfo: OrderByOptimizationInfo,\n onStatusChange: (event: SubscriptionStatusChangeEvent) => void,\n ): CollectionSubscription {\n const { orderBy, offset, limit, index } = orderByInfo\n\n // Use a holder to forward-reference subscription in the callback\n const subscriptionHolder: { current?: CollectionSubscription } = {}\n\n const sendChangesInRange = (\n changes: Iterable<ChangeMessage<any, string | number>>,\n ) => {\n // Split live updates into a delete of the old value and an insert of the new value\n const splittedChanges = splitUpdates(changes)\n this.sendChangesToPipelineWithTracking(\n splittedChanges,\n subscriptionHolder.current!,\n )\n }\n\n // Subscribe to changes with onStatusChange - listener is registered before any snapshot\n // values bigger than what we've sent don't need to be sent because they can't affect the topK\n const subscription = this.collection.subscribeChanges(sendChangesInRange, {\n whereExpression,\n onStatusChange,\n })\n subscriptionHolder.current = subscription\n\n // Listen for truncate events to reset cursor tracking state and sentToD2Keys\n // This ensures that after a must-refetch/truncate, we don't use stale cursor data\n // and allow re-inserts of previously sent keys\n const truncateUnsubscribe = this.collection.on(`truncate`, () => {\n this.biggest = undefined\n this.sentToD2Keys.clear()\n })\n\n // Clean up truncate listener when subscription is unsubscribed\n subscription.on(`unsubscribed`, () => {\n truncateUnsubscribe()\n })\n\n // Normalize the orderBy clauses such that the references are relative to the collection\n const normalizedOrderBy = normalizeOrderByPaths(orderBy, this.alias)\n\n // Trigger the snapshot request - onStatusChange listener is already registered\n if (index) {\n // We have an index on the first orderBy column - use lazy loading optimization\n // This works for both single-column and multi-column orderBy:\n // - Single-column: index provides exact ordering\n // - Multi-column: index provides ordering on first column, secondary sort in memory\n subscription.setOrderByIndex(index)\n\n // Load the first `offset + limit` values from the index\n // i.e. the K items from the collection that fall into the requested range: [offset, offset + limit[\n subscription.requestLimitedSnapshot({\n limit: offset + limit,\n orderBy: normalizedOrderBy,\n })\n } else {\n // No index available (e.g., non-ref expression): pass orderBy/limit to loadSubset\n // so the sync layer can optimize if the backend supports it\n subscription.requestSnapshot({\n orderBy: normalizedOrderBy,\n limit: offset + limit,\n })\n }\n\n return subscription\n }\n\n // This function is called by maybeRunGraph\n // after each iteration of the query pipeline\n // to ensure that the orderBy operator has enough data to work with\n loadMoreIfNeeded(subscription: CollectionSubscription) {\n const orderByInfo = this.getOrderByInfo()\n\n if (!orderByInfo) {\n // This query has no orderBy operator\n // so there's no data to load\n return true\n }\n\n const { dataNeeded } = orderByInfo\n\n if (!dataNeeded) {\n // dataNeeded is not set when there's no index (e.g., non-ref expression).\n // In this case, we've already loaded all data via requestSnapshot\n // and don't need to lazily load more.\n return true\n }\n\n // `dataNeeded` probes the orderBy operator to see if it needs more data\n // if it needs more data, it returns the number of items it needs\n const n = dataNeeded()\n if (n > 0) {\n this.loadNextItems(n, subscription)\n }\n return true\n }\n\n private sendChangesToPipelineWithTracking(\n changes: Iterable<ChangeMessage<any, string | number>>,\n subscription: CollectionSubscription,\n ) {\n const orderByInfo = this.getOrderByInfo()\n if (!orderByInfo) {\n this.sendChangesToPipeline(changes)\n return\n }\n\n const trackedChanges = this.trackSentValues(changes, orderByInfo.comparator)\n\n // Cache the loadMoreIfNeeded callback on the subscription using a symbol property.\n // This ensures we pass the same function instance to the scheduler each time,\n // allowing it to deduplicate callbacks when multiple changes arrive during a transaction.\n type SubscriptionWithLoader = CollectionSubscription & {\n [loadMoreCallbackSymbol]?: () => boolean\n }\n\n const subscriptionWithLoader = subscription as SubscriptionWithLoader\n\n subscriptionWithLoader[loadMoreCallbackSymbol] ??=\n this.loadMoreIfNeeded.bind(this, subscription)\n\n this.sendChangesToPipeline(\n trackedChanges,\n subscriptionWithLoader[loadMoreCallbackSymbol],\n )\n }\n\n // Loads the next `n` items from the collection\n // starting from the biggest item it has sent\n private loadNextItems(n: number, subscription: CollectionSubscription) {\n const orderByInfo = this.getOrderByInfo()\n if (!orderByInfo) {\n return\n }\n const { orderBy, valueExtractorForRawRow, offset } = orderByInfo\n const biggestSentRow = this.biggest\n\n // Extract all orderBy column values from the biggest sent row\n // For single-column: returns single value, for multi-column: returns array\n const extractedValues = biggestSentRow\n ? valueExtractorForRawRow(biggestSentRow)\n : undefined\n\n // Normalize to array format for minValues\n const minValues =\n extractedValues !== undefined\n ? Array.isArray(extractedValues)\n ? extractedValues\n : [extractedValues]\n : undefined\n\n // Normalize the orderBy clauses such that the references are relative to the collection\n const normalizedOrderBy = normalizeOrderByPaths(orderBy, this.alias)\n\n // Take the `n` items after the biggest sent value\n // Pass the current window offset to ensure proper deduplication\n subscription.requestLimitedSnapshot({\n orderBy: normalizedOrderBy,\n limit: n,\n minValues,\n offset,\n })\n }\n\n private getWhereClauseForAlias(): BasicExpression<boolean> | undefined {\n const sourceWhereClausesCache =\n this.collectionConfigBuilder.sourceWhereClausesCache\n if (!sourceWhereClausesCache) {\n return undefined\n }\n return sourceWhereClausesCache.get(this.alias)\n }\n\n private getOrderByInfo(): OrderByOptimizationInfo | undefined {\n const info =\n this.collectionConfigBuilder.optimizableOrderByCollections[\n this.collectionId\n ]\n if (info && info.alias === this.alias) {\n return info\n }\n return undefined\n }\n\n private *trackSentValues(\n changes: Iterable<ChangeMessage<any, string | number>>,\n comparator: (a: any, b: any) => number,\n ) {\n for (const change of changes) {\n // Only track inserts/updates for cursor positioning, not deletes\n if (change.type !== `delete`) {\n if (!this.biggest) {\n this.biggest = change.value\n } else if (comparator(this.biggest, change.value) < 0) {\n this.biggest = change.value\n }\n }\n\n yield change\n }\n }\n}\n\n/**\n * Helper function to send changes to a D2 input stream\n */\nfunction sendChangesToInput(\n input: RootStreamBuilder<unknown>,\n changes: Iterable<ChangeMessage>,\n getKey: (item: ChangeMessage[`value`]) => any,\n): number {\n const multiSetArray: MultiSetArray<unknown> = []\n for (const change of changes) {\n const key = getKey(change.value)\n if (change.type === `insert`) {\n multiSetArray.push([[key, change.value], 1])\n } else if (change.type === `update`) {\n multiSetArray.push([[key, change.previousValue], -1])\n multiSetArray.push([[key, change.value], 1])\n } else {\n // change.type === `delete`\n multiSetArray.push([[key, change.value], -1])\n }\n }\n\n if (multiSetArray.length !== 0) {\n input.sendData(new MultiSet(multiSetArray))\n }\n\n return multiSetArray.length\n}\n\n/** Splits updates into a delete of the old value and an insert of the new value */\nfunction* splitUpdates<\n T extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n>(\n changes: Iterable<ChangeMessage<T, TKey>>,\n): Generator<ChangeMessage<T, TKey>> {\n for (const change of changes) {\n if (change.type === `update`) {\n yield { type: `delete`, key: change.key, value: change.previousValue! }\n yield { type: `insert`, key: change.key, value: change.value }\n } else {\n yield change\n }\n }\n}\n"],"names":["normalizeExpressionPaths","subscription","normalizeOrderByPaths","MultiSet"],"mappings":";;;;AAiBA,MAAM,yBAAyB,uBAAO;AAAA,EACpC;AACF;AAEO,MAAM,qBAGX;AAAA,EAeA,YACU,OACA,cACA,YACA,yBACR;AAJQ,SAAA,QAAA;AACA,SAAA,eAAA;AACA,SAAA,aAAA;AACA,SAAA,0BAAA;AAjBV,SAAQ,UAAe;AAGvB,SAAQ,kDAAkC,IAAA;AAQ1C,SAAQ,mCAAmB,IAAA;AAAA,EAOxB;AAAA,EAEH,YAAoC;AAClC,UAAM,cAAc,KAAK,uBAAA;AAEzB,QAAI,aAAa;AACf,YAAM,kBAAkBA,YAAAA,yBAAyB,aAAa,KAAK,KAAK;AACxE,aAAO,KAAK,mBAAmB,eAAe;AAAA,IAChD;AAEA,WAAO,KAAK,mBAAA;AAAA,EACd;AAAA,EAEQ,mBAAmB,iBAA4C;AACrE,UA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AC,CAAC;AAAA,IAC7C,WAAW,OAAO,SAAS,UAAU;AACnC,oBAAc,KAAK,CAAC,CAAC,KAAK,OAAO,aAAa,GAAG,EAAE,CAAC;AACpD,oBAAc,KAAK,CAAC,CAAC,KAAK,OAAO,KAAK,GAAG,CAAC,CAAC;AAAA,IAC7C,OAAO;AAEL,oBAAc,KAAK,CAAC,CAAC,KAAK,OAAO,KAAK,GAAG,EAAE,CAAC;AAAA,IAC9C;AAAA,EACF;AAEA,MAAI,cAAc,WAAW,GAAG;AAC9B,UAAM,SAAS,IAAIC,MAAAA,SAAS,aAAa,CAAC;AAAA,EAC5C;AAEA,SAAO,cAAc;AACvB;AAGA,UAAU,aAIR,SACmC;AACnC,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,SAAS,UAAU;AAC5B,YAAM,EAAE,MAAM,UAAU,KAAK,OAAO,KAAK,OAAO,OAAO,cAAA;AACvD,YAAM,EAAE,MAAM,UAAU,KAAK,OAAO,KAAK,OAAO,OAAO,MAAA;AAAA,IACzD,OAAO;AACL,YAAM;AAAA,IACR;AAAA,EACF;AACF;;"}
|
|
1
|
+
{"version":3,"file":"collection-subscriber.cjs","sources":["../../../../src/query/live/collection-subscriber.ts"],"sourcesContent":["import { MultiSet, serializeValue } from '@tanstack/db-ivm'\nimport {\n normalizeExpressionPaths,\n normalizeOrderByPaths,\n} from '../compiler/expressions.js'\nimport type { MultiSetArray, RootStreamBuilder } from '@tanstack/db-ivm'\nimport type { Collection } from '../../collection/index.js'\nimport type {\n ChangeMessage,\n SubscriptionStatusChangeEvent,\n} from '../../types.js'\nimport type { Context, GetResult } from '../builder/types.js'\nimport type { BasicExpression } from '../ir.js'\nimport type { OrderByOptimizationInfo } from '../compiler/order-by.js'\nimport type { CollectionConfigBuilder } from './collection-config-builder.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\n\nconst loadMoreCallbackSymbol = Symbol.for(\n `@tanstack/db.collection-config-builder`,\n)\n\nexport class CollectionSubscriber<\n TContext extends Context,\n TResult extends object = GetResult<TContext>,\n> {\n // Keep track of the biggest value we've sent so far (needed for orderBy optimization)\n private biggest: any = undefined\n\n // Track the most recent ordered load request key (cursor + window).\n // This avoids infinite loops from cached data re-writes while still allowing\n // window moves or new keys at the same cursor value to trigger new requests.\n private lastLoadRequestKey: string | undefined\n\n // Track deferred promises for subscription loading states\n private subscriptionLoadingPromises = new Map<\n CollectionSubscription,\n { resolve: () => void }\n >()\n\n // Track keys that have been sent to the D2 pipeline to prevent duplicate inserts\n // This is necessary because different code paths (initial load, change events)\n // can potentially send the same item to D2 multiple times.\n private sentToD2Keys = new Set<string | number>()\n\n // Direct load tracking callback for ordered path (set during subscribeToOrderedChanges,\n // used by loadNextItems for subsequent requestLimitedSnapshot calls)\n private orderedLoadSubsetResult?: (result: Promise<void> | true) => void\n private pendingOrderedLoadPromise: Promise<void> | undefined\n\n constructor(\n private alias: string,\n private collectionId: string,\n private collection: Collection,\n private collectionConfigBuilder: CollectionConfigBuilder<TContext, TResult>,\n ) {}\n\n subscribe(): CollectionSubscription {\n const whereClause = this.getWhereClauseForAlias()\n\n if (whereClause) {\n const whereExpression = normalizeExpressionPaths(whereClause, this.alias)\n return this.subscribeToChanges(whereExpression)\n }\n\n return this.subscribeToChanges()\n }\n\n private subscribeToChanges(whereExpression?: BasicExpression<boolean>) {\n const orderByInfo = this.getOrderByInfo()\n\n // Direct load promise tracking: pipes loadSubset results straight to the\n // live query collection, avoiding the multi-hop deferred promise chain that\n // can break under microtask timing (e.g., queueMicrotask in TanStack Query).\n const trackLoadResult = (result: Promise<void> | true) => {\n if (result instanceof Promise) {\n this.collectionConfigBuilder.liveQueryCollection!._sync.trackLoadPromise(\n result,\n )\n }\n }\n\n // Status change handler - passed to subscribeChanges so it's registered\n // BEFORE any snapshot is requested, preventing race conditions.\n // Used as a fallback for status transitions not covered by direct tracking\n // (e.g., truncate-triggered reloads that call trackLoadSubsetPromise directly).\n const onStatusChange = (event: SubscriptionStatusChangeEvent) => {\n const subscription = event.subscription as CollectionSubscription\n if (event.status === `loadingSubset`) {\n this.ensureLoadingPromise(subscription)\n } else {\n // status is 'ready'\n const deferred = this.subscriptionLoadingPromises.get(subscription)\n if (deferred) {\n this.subscriptionLoadingPromises.delete(subscription)\n deferred.resolve()\n }\n }\n }\n\n // Create subscription with onStatusChange - listener is registered before any async work\n let subscription: CollectionSubscription\n if (orderByInfo) {\n subscription = this.subscribeToOrderedChanges(\n whereExpression,\n orderByInfo,\n onStatusChange,\n trackLoadResult,\n )\n } else {\n // If the source alias is lazy then we should not include the initial state\n const includeInitialState = !this.collectionConfigBuilder.isLazyAlias(\n this.alias,\n )\n\n subscription = this.subscribeToMatchingChanges(\n whereExpression,\n includeInitialState,\n onStatusChange,\n )\n }\n\n // Check current status after subscribing - if status is 'loadingSubset', track it.\n // The onStatusChange listener will catch the transition to 'ready'.\n if (subscription.status === `loadingSubset`) {\n this.ensureLoadingPromise(subscription)\n }\n\n const unsubscribe = () => {\n // If subscription has a pending promise, resolve it before unsubscribing\n const deferred = this.subscriptionLoadingPromises.get(subscription)\n if (deferred) {\n this.subscriptionLoadingPromises.delete(subscription)\n deferred.resolve()\n }\n\n subscription.unsubscribe()\n }\n // currentSyncState is always defined when subscribe() is called\n // (called during sync session setup)\n this.collectionConfigBuilder.currentSyncState!.unsubscribeCallbacks.add(\n unsubscribe,\n )\n return subscription\n }\n\n private sendChangesToPipeline(\n changes: Iterable<ChangeMessage<any, string | number>>,\n callback?: () => boolean,\n ) {\n // Filter changes to prevent duplicate inserts to D2 pipeline.\n // This ensures D2 multiplicity stays at 1 for visible items, so deletes\n // properly reduce multiplicity to 0 (triggering DELETE output).\n const changesArray = Array.isArray(changes) ? changes : [...changes]\n const filteredChanges: Array<ChangeMessage<any, string | number>> = []\n for (const change of changesArray) {\n if (change.type === `insert`) {\n if (this.sentToD2Keys.has(change.key)) {\n // Skip duplicate insert - already sent to D2\n continue\n }\n this.sentToD2Keys.add(change.key)\n } else if (change.type === `delete`) {\n // Remove from tracking so future re-inserts are allowed\n this.sentToD2Keys.delete(change.key)\n }\n // Updates are handled as delete+insert by splitUpdates, so no special handling needed\n filteredChanges.push(change)\n }\n\n // currentSyncState and input are always defined when this method is called\n // (only called from active subscriptions during a sync session)\n const input =\n this.collectionConfigBuilder.currentSyncState!.inputs[this.alias]!\n const sentChanges = sendChangesToInput(\n input,\n filteredChanges,\n this.collection.config.getKey,\n )\n\n // Do not provide the callback that loads more data\n // if there's no more data to load\n // otherwise we end up in an infinite loop trying to load more data\n const dataLoader = sentChanges > 0 ? callback : undefined\n\n // We need to schedule a graph run even if there's no data to load\n // because we need to mark the collection as ready if it's not already\n // and that's only done in `scheduleGraphRun`\n this.collectionConfigBuilder.scheduleGraphRun(dataLoader, {\n alias: this.alias,\n })\n }\n\n private subscribeToMatchingChanges(\n whereExpression: BasicExpression<boolean> | undefined,\n includeInitialState: boolean,\n onStatusChange: (event: SubscriptionStatusChangeEvent) => void,\n ): CollectionSubscription {\n const sendChanges = (\n changes: Array<ChangeMessage<any, string | number>>,\n ) => {\n this.sendChangesToPipeline(changes)\n }\n\n // Get the query's orderBy and limit to pass to loadSubset.\n // Only include orderBy when it is scoped to this alias and uses simple refs,\n // to avoid leaking cross-collection paths into backend-specific compilers.\n const { orderBy, limit, offset } = this.collectionConfigBuilder.query\n const effectiveLimit =\n limit !== undefined && offset !== undefined ? limit + offset : limit\n const normalizedOrderBy = orderBy\n ? normalizeOrderByPaths(orderBy, this.alias)\n : undefined\n const canPassOrderBy =\n normalizedOrderBy?.every((clause) => {\n const exp = clause.expression\n if (exp.type !== `ref`) {\n return false\n }\n const path = exp.path\n return Array.isArray(path) && path.length === 1\n }) ?? false\n const orderByForSubscription = canPassOrderBy\n ? normalizedOrderBy\n : undefined\n const limitForSubscription = canPassOrderBy ? effectiveLimit : undefined\n\n // Track loading via the loadSubset promise directly.\n // requestSnapshot uses trackLoadSubsetPromise: false (needed for truncate handling),\n // so we use onLoadSubsetResult to get the promise and track it ourselves.\n const onLoadSubsetResult = includeInitialState\n ? (result: Promise<void> | true) => {\n if (result instanceof Promise) {\n this.collectionConfigBuilder.liveQueryCollection!._sync.trackLoadPromise(\n result,\n )\n }\n }\n : undefined\n\n const subscription = this.collection.subscribeChanges(sendChanges, {\n ...(includeInitialState && { includeInitialState }),\n whereExpression,\n onStatusChange,\n orderBy: orderByForSubscription,\n limit: limitForSubscription,\n onLoadSubsetResult,\n })\n\n return subscription\n }\n\n private subscribeToOrderedChanges(\n whereExpression: BasicExpression<boolean> | undefined,\n orderByInfo: OrderByOptimizationInfo,\n onStatusChange: (event: SubscriptionStatusChangeEvent) => void,\n onLoadSubsetResult: (result: Promise<void> | true) => void,\n ): CollectionSubscription {\n const { orderBy, offset, limit, index } = orderByInfo\n\n // Store the callback so loadNextItems can also use direct tracking.\n // Track in-flight ordered loads to avoid issuing redundant requests while\n // a previous snapshot is still pending.\n const handleLoadSubsetResult = (result: Promise<void> | true) => {\n if (result instanceof Promise) {\n this.pendingOrderedLoadPromise = result\n result.finally(() => {\n if (this.pendingOrderedLoadPromise === result) {\n this.pendingOrderedLoadPromise = undefined\n }\n })\n }\n onLoadSubsetResult(result)\n }\n\n this.orderedLoadSubsetResult = handleLoadSubsetResult\n\n // Use a holder to forward-reference subscription in the callback\n const subscriptionHolder: { current?: CollectionSubscription } = {}\n\n const sendChangesInRange = (\n changes: Iterable<ChangeMessage<any, string | number>>,\n ) => {\n const changesArray = Array.isArray(changes) ? changes : [...changes]\n\n this.trackSentValues(changesArray, orderByInfo.comparator)\n\n // Split live updates into a delete of the old value and an insert of the new value\n const splittedChanges = splitUpdates(changesArray)\n this.sendChangesToPipelineWithTracking(\n splittedChanges,\n subscriptionHolder.current!,\n )\n }\n\n // Subscribe to changes with onStatusChange - listener is registered before any snapshot\n // values bigger than what we've sent don't need to be sent because they can't affect the topK\n const subscription = this.collection.subscribeChanges(sendChangesInRange, {\n whereExpression,\n onStatusChange,\n })\n subscriptionHolder.current = subscription\n\n // Listen for truncate events to reset cursor tracking state and sentToD2Keys\n // This ensures that after a must-refetch/truncate, we don't use stale cursor data\n // and allow re-inserts of previously sent keys\n const truncateUnsubscribe = this.collection.on(`truncate`, () => {\n this.biggest = undefined\n this.lastLoadRequestKey = undefined\n this.pendingOrderedLoadPromise = undefined\n this.sentToD2Keys.clear()\n })\n\n // Clean up truncate listener when subscription is unsubscribed\n subscription.on(`unsubscribed`, () => {\n truncateUnsubscribe()\n })\n\n // Normalize the orderBy clauses such that the references are relative to the collection\n const normalizedOrderBy = normalizeOrderByPaths(orderBy, this.alias)\n\n // Trigger the snapshot request — use direct load tracking (trackLoadSubsetPromise: false)\n // to pipe the loadSubset result straight to the live query collection. This bypasses\n // the subscription status → onStatusChange → deferred promise chain which is fragile\n // under microtask timing (e.g., queueMicrotask delays in TanStack Query observers).\n if (index) {\n // We have an index on the first orderBy column - use lazy loading optimization\n subscription.setOrderByIndex(index)\n\n subscription.requestLimitedSnapshot({\n limit: offset + limit,\n orderBy: normalizedOrderBy,\n trackLoadSubsetPromise: false,\n onLoadSubsetResult: handleLoadSubsetResult,\n })\n } else {\n // No index available (e.g., non-ref expression): pass orderBy/limit to loadSubset\n subscription.requestSnapshot({\n orderBy: normalizedOrderBy,\n limit: offset + limit,\n trackLoadSubsetPromise: false,\n onLoadSubsetResult: handleLoadSubsetResult,\n })\n }\n\n return subscription\n }\n\n // This function is called by maybeRunGraph\n // after each iteration of the query pipeline\n // to ensure that the orderBy operator has enough data to work with\n loadMoreIfNeeded(subscription: CollectionSubscription) {\n const orderByInfo = this.getOrderByInfo()\n\n if (!orderByInfo) {\n // This query has no orderBy operator\n // so there's no data to load\n return true\n }\n\n const { dataNeeded } = orderByInfo\n\n if (!dataNeeded) {\n // dataNeeded is not set when there's no index (e.g., non-ref expression).\n // In this case, we've already loaded all data via requestSnapshot\n // and don't need to lazily load more.\n return true\n }\n\n if (this.pendingOrderedLoadPromise) {\n // Wait for in-flight ordered loads to resolve before issuing another request.\n return true\n }\n\n // `dataNeeded` probes the orderBy operator to see if it needs more data\n // if it needs more data, it returns the number of items it needs\n const n = dataNeeded()\n if (n > 0) {\n this.loadNextItems(n, subscription)\n }\n return true\n }\n\n private sendChangesToPipelineWithTracking(\n changes: Iterable<ChangeMessage<any, string | number>>,\n subscription: CollectionSubscription,\n ) {\n const orderByInfo = this.getOrderByInfo()\n if (!orderByInfo) {\n this.sendChangesToPipeline(changes)\n return\n }\n\n // Cache the loadMoreIfNeeded callback on the subscription using a symbol property.\n // This ensures we pass the same function instance to the scheduler each time,\n // allowing it to deduplicate callbacks when multiple changes arrive during a transaction.\n type SubscriptionWithLoader = CollectionSubscription & {\n [loadMoreCallbackSymbol]?: () => boolean\n }\n\n const subscriptionWithLoader = subscription as SubscriptionWithLoader\n\n subscriptionWithLoader[loadMoreCallbackSymbol] ??=\n this.loadMoreIfNeeded.bind(this, subscription)\n\n this.sendChangesToPipeline(\n changes,\n subscriptionWithLoader[loadMoreCallbackSymbol],\n )\n }\n\n // Loads the next `n` items from the collection\n // starting from the biggest item it has sent\n private loadNextItems(n: number, subscription: CollectionSubscription) {\n const orderByInfo = this.getOrderByInfo()\n if (!orderByInfo) {\n return\n }\n const { orderBy, valueExtractorForRawRow, offset } = orderByInfo\n const biggestSentRow = this.biggest\n\n // Extract all orderBy column values from the biggest sent row\n // For single-column: returns single value, for multi-column: returns array\n const extractedValues = biggestSentRow\n ? valueExtractorForRawRow(biggestSentRow)\n : undefined\n\n // Normalize to array format for minValues\n let minValues: Array<unknown> | undefined\n if (extractedValues !== undefined) {\n minValues = Array.isArray(extractedValues)\n ? extractedValues\n : [extractedValues]\n }\n\n const loadRequestKey = this.getLoadRequestKey({\n minValues,\n offset,\n limit: n,\n })\n\n // Skip if we already requested a load for this cursor+window.\n // This prevents infinite loops from cached data re-writes while still allowing\n // window moves (offset/limit changes) to trigger new requests.\n if (this.lastLoadRequestKey === loadRequestKey) {\n return\n }\n\n // Normalize the orderBy clauses such that the references are relative to the collection\n const normalizedOrderBy = normalizeOrderByPaths(orderBy, this.alias)\n\n // Take the `n` items after the biggest sent value\n // Pass the current window offset to ensure proper deduplication\n subscription.requestLimitedSnapshot({\n orderBy: normalizedOrderBy,\n limit: n,\n minValues,\n // Omit offset so requestLimitedSnapshot can advance the offset based on\n // the number of rows already loaded (supports offset-based backends).\n trackLoadSubsetPromise: false,\n onLoadSubsetResult: this.orderedLoadSubsetResult,\n })\n\n this.lastLoadRequestKey = loadRequestKey\n }\n\n private getWhereClauseForAlias(): BasicExpression<boolean> | undefined {\n const sourceWhereClausesCache =\n this.collectionConfigBuilder.sourceWhereClausesCache\n if (!sourceWhereClausesCache) {\n return undefined\n }\n return sourceWhereClausesCache.get(this.alias)\n }\n\n private getOrderByInfo(): OrderByOptimizationInfo | undefined {\n const info =\n this.collectionConfigBuilder.optimizableOrderByCollections[\n this.collectionId\n ]\n if (info && info.alias === this.alias) {\n return info\n }\n return undefined\n }\n\n private trackSentValues(\n changes: Array<ChangeMessage<any, string | number>>,\n comparator: (a: any, b: any) => number,\n ): void {\n for (const change of changes) {\n if (change.type === `delete`) {\n continue\n }\n\n const isNewKey = !this.sentToD2Keys.has(change.key)\n\n // Only track inserts/updates for cursor positioning, not deletes\n if (!this.biggest) {\n this.biggest = change.value\n this.lastLoadRequestKey = undefined\n } else if (comparator(this.biggest, change.value) < 0) {\n this.biggest = change.value\n this.lastLoadRequestKey = undefined\n } else if (isNewKey) {\n // New key with same orderBy value - allow another load if needed\n this.lastLoadRequestKey = undefined\n }\n }\n }\n\n private ensureLoadingPromise(subscription: CollectionSubscription) {\n if (this.subscriptionLoadingPromises.has(subscription)) {\n return\n }\n\n let resolve: () => void\n const promise = new Promise<void>((res) => {\n resolve = res\n })\n\n this.subscriptionLoadingPromises.set(subscription, {\n resolve: resolve!,\n })\n this.collectionConfigBuilder.liveQueryCollection!._sync.trackLoadPromise(\n promise,\n )\n }\n\n private getLoadRequestKey(options: {\n minValues: Array<unknown> | undefined\n offset: number\n limit: number\n }): string {\n return serializeValue({\n minValues: options.minValues ?? null,\n offset: options.offset,\n limit: options.limit,\n })\n }\n}\n\n/**\n * Helper function to send changes to a D2 input stream\n */\nfunction sendChangesToInput(\n input: RootStreamBuilder<unknown>,\n changes: Iterable<ChangeMessage>,\n getKey: (item: ChangeMessage[`value`]) => any,\n): number {\n const multiSetArray: MultiSetArray<unknown> = []\n for (const change of changes) {\n const key = getKey(change.value)\n if (change.type === `insert`) {\n multiSetArray.push([[key, change.value], 1])\n } else if (change.type === `update`) {\n multiSetArray.push([[key, change.previousValue], -1])\n multiSetArray.push([[key, change.value], 1])\n } else {\n // change.type === `delete`\n multiSetArray.push([[key, change.value], -1])\n }\n }\n\n if (multiSetArray.length !== 0) {\n input.sendData(new MultiSet(multiSetArray))\n }\n\n return multiSetArray.length\n}\n\n/** Splits updates into a delete of the old value and an insert of the new value */\nfunction* splitUpdates<\n T extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n>(\n changes: Iterable<ChangeMessage<T, TKey>>,\n): Generator<ChangeMessage<T, TKey>> {\n for (const change of changes) {\n if (change.type === `update`) {\n yield { type: `delete`, key: change.key, value: change.previousValue! }\n yield { type: `insert`, key: change.key, value: change.value }\n } else {\n yield change\n }\n }\n}\n"],"names":["normalizeExpressionPaths","subscription","normalizeOrderByPaths","serializeValue","MultiSet"],"mappings":";;;;AAiBA,MAAM,yBAAyB,uBAAO;AAAA,EACpC;AACF;AAEO,MAAM,qBAGX;AAAA,EAyBA,YACU,OACA,cACA,YACA,yBACR;AAJQ,SAAA,QAAA;AACA,SAAA,eAAA;AACA,SAAA,aAAA;AACA,SAAA,0BAAA;AA3BV,SAAQ,UAAe;AAQvB,SAAQ,kDAAkC,IAAA;AAQ1C,SAAQ,mCAAmB,IAAA;AAAA,EAYxB;AAAA,EAEH,YAAoC;AAClC,UAAM,cAAc,KAAK,uBAAA;AAEzB,QAAI,aAAa;AACf,YAAM,kBAAkBA,YAAAA,yBAAyB,aAAa,KAAK,KAAK;AACxE,aAAO,KAAK,mBAAmB,eAAe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OAAO,KAAK,OAAO,OAAO,cAAA;AACvD,YAAM,EAAE,MAAM,UAAU,KAAK,OAAO,KAAK,OAAO,OAAO,MAAA;AAAA,IACzD,OAAO;AACL,YAAM;AAAA,IACR;AAAA,EACF;AACF;;"}
|
|
@@ -8,8 +8,11 @@ export declare class CollectionSubscriber<TContext extends Context, TResult exte
|
|
|
8
8
|
private collection;
|
|
9
9
|
private collectionConfigBuilder;
|
|
10
10
|
private biggest;
|
|
11
|
+
private lastLoadRequestKey;
|
|
11
12
|
private subscriptionLoadingPromises;
|
|
12
13
|
private sentToD2Keys;
|
|
14
|
+
private orderedLoadSubsetResult?;
|
|
15
|
+
private pendingOrderedLoadPromise;
|
|
13
16
|
constructor(alias: string, collectionId: string, collection: Collection, collectionConfigBuilder: CollectionConfigBuilder<TContext, TResult>);
|
|
14
17
|
subscribe(): CollectionSubscription;
|
|
15
18
|
private subscribeToChanges;
|
|
@@ -22,4 +25,6 @@ export declare class CollectionSubscriber<TContext extends Context, TResult exte
|
|
|
22
25
|
private getWhereClauseForAlias;
|
|
23
26
|
private getOrderByInfo;
|
|
24
27
|
private trackSentValues;
|
|
28
|
+
private ensureLoadingPromise;
|
|
29
|
+
private getLoadRequestKey;
|
|
25
30
|
}
|
package/dist/cjs/types.d.cts
CHANGED
|
@@ -628,6 +628,22 @@ export interface SubscribeChangesOptions<T extends object = Record<string, unkno
|
|
|
628
628
|
* @internal
|
|
629
629
|
*/
|
|
630
630
|
onStatusChange?: (event: SubscriptionStatusChangeEvent) => void;
|
|
631
|
+
/**
|
|
632
|
+
* Optional orderBy to include in loadSubset for query-specific cache keys.
|
|
633
|
+
* @internal
|
|
634
|
+
*/
|
|
635
|
+
orderBy?: OrderBy;
|
|
636
|
+
/**
|
|
637
|
+
* Optional limit to include in loadSubset for query-specific cache keys.
|
|
638
|
+
* @internal
|
|
639
|
+
*/
|
|
640
|
+
limit?: number;
|
|
641
|
+
/**
|
|
642
|
+
* Callback that receives the loadSubset result (Promise or true) from requestSnapshot.
|
|
643
|
+
* Allows the caller to directly track the loading promise for isReady status.
|
|
644
|
+
* @internal
|
|
645
|
+
*/
|
|
646
|
+
onLoadSubsetResult?: (result: Promise<void> | true) => void;
|
|
631
647
|
}
|
|
632
648
|
export interface SubscribeChangesSnapshotOptions<T extends object = Record<string, unknown>> extends Omit<SubscribeChangesOptions<T>, `includeInitialState`> {
|
|
633
649
|
orderBy?: OrderBy;
|
|
@@ -79,6 +79,7 @@ function areUint8ArraysEqual(a, b) {
|
|
|
79
79
|
return true;
|
|
80
80
|
}
|
|
81
81
|
const UINT8ARRAY_NORMALIZE_THRESHOLD = 128;
|
|
82
|
+
const UNDEFINED_SENTINEL = `__TS_DB_BTREE_UNDEFINED_VALUE__`;
|
|
82
83
|
function normalizeValue(value) {
|
|
83
84
|
if (value instanceof Date) {
|
|
84
85
|
return value.getTime();
|
|
@@ -91,6 +92,18 @@ function normalizeValue(value) {
|
|
|
91
92
|
}
|
|
92
93
|
return value;
|
|
93
94
|
}
|
|
95
|
+
function normalizeForBTree(value) {
|
|
96
|
+
if (value === void 0) {
|
|
97
|
+
return UNDEFINED_SENTINEL;
|
|
98
|
+
}
|
|
99
|
+
return normalizeValue(value);
|
|
100
|
+
}
|
|
101
|
+
function denormalizeUndefined(value) {
|
|
102
|
+
if (value === UNDEFINED_SENTINEL) {
|
|
103
|
+
return void 0;
|
|
104
|
+
}
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
94
107
|
function areValuesEqual(a, b) {
|
|
95
108
|
if (a === b) {
|
|
96
109
|
return true;
|
|
@@ -102,10 +115,13 @@ function areValuesEqual(a, b) {
|
|
|
102
115
|
}
|
|
103
116
|
return false;
|
|
104
117
|
}
|
|
118
|
+
exports.UNDEFINED_SENTINEL = UNDEFINED_SENTINEL;
|
|
105
119
|
exports.areValuesEqual = areValuesEqual;
|
|
106
120
|
exports.ascComparator = ascComparator;
|
|
107
121
|
exports.defaultComparator = defaultComparator;
|
|
122
|
+
exports.denormalizeUndefined = denormalizeUndefined;
|
|
108
123
|
exports.descComparator = descComparator;
|
|
109
124
|
exports.makeComparator = makeComparator;
|
|
125
|
+
exports.normalizeForBTree = normalizeForBTree;
|
|
110
126
|
exports.normalizeValue = normalizeValue;
|
|
111
127
|
//# sourceMappingURL=comparison.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comparison.cjs","sources":["../../../src/utils/comparison.ts"],"sourcesContent":["import type { CompareOptions } from '../query/builder/types'\n\n// WeakMap to store stable IDs for objects\nconst objectIds = new WeakMap<object, number>()\nlet nextObjectId = 1\n\n/**\n * Get or create a stable ID for an object\n */\nfunction getObjectId(obj: object): number {\n if (objectIds.has(obj)) {\n return objectIds.get(obj)!\n }\n const id = nextObjectId++\n objectIds.set(obj, id)\n return id\n}\n\n/**\n * Universal comparison function for all data types\n * Handles null/undefined, strings, arrays, dates, objects, and primitives\n * Always sorts null/undefined values first\n */\nexport const ascComparator = (a: any, b: any, opts: CompareOptions): number => {\n const { nulls } = opts\n\n // Handle null/undefined\n if (a == null && b == null) return 0\n if (a == null) return nulls === `first` ? -1 : 1\n if (b == null) return nulls === `first` ? 1 : -1\n\n // if a and b are both strings, compare them based on locale\n if (typeof a === `string` && typeof b === `string`) {\n if (opts.stringSort === `locale`) {\n return a.localeCompare(b, opts.locale, opts.localeOptions)\n }\n // For lexical sort we rely on direct comparison for primitive values\n }\n\n // if a and b are both arrays, compare them element by element\n if (Array.isArray(a) && Array.isArray(b)) {\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const result = ascComparator(a[i], b[i], opts)\n if (result !== 0) {\n return result\n }\n }\n // All elements are equal up to the minimum length\n return a.length - b.length\n }\n\n // If both are dates, compare them\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() - b.getTime()\n }\n\n // If at least one of the values is an object, use stable IDs for comparison\n const aIsObject = typeof a === `object`\n const bIsObject = typeof b === `object`\n\n if (aIsObject || bIsObject) {\n // If both are objects, compare their stable IDs\n if (aIsObject && bIsObject) {\n const aId = getObjectId(a)\n const bId = getObjectId(b)\n return aId - bId\n }\n\n // If only one is an object, objects come after primitives\n if (aIsObject) return 1\n if (bIsObject) return -1\n }\n\n // For primitive values, use direct comparison\n if (a < b) return -1\n if (a > b) return 1\n return 0\n}\n\n/**\n * Descending comparator function for ordering values\n * Handles null/undefined as largest values (opposite of ascending)\n */\nexport const descComparator = (\n a: unknown,\n b: unknown,\n opts: CompareOptions,\n): number => {\n return ascComparator(b, a, {\n ...opts,\n nulls: opts.nulls === `first` ? `last` : `first`,\n })\n}\n\nexport function makeComparator(\n opts: CompareOptions,\n): (a: any, b: any) => number {\n return (a, b) => {\n if (opts.direction === `asc`) {\n return ascComparator(a, b, opts)\n } else {\n return descComparator(a, b, opts)\n }\n }\n}\n\n/** Default comparator orders values in ascending order with nulls first and locale string comparison. */\nexport const defaultComparator = makeComparator({\n direction: `asc`,\n nulls: `first`,\n stringSort: `locale`,\n})\n\n/**\n * Compare two Uint8Arrays for content equality\n */\nfunction areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n return true\n}\n\n/**\n * Threshold for normalizing Uint8Arrays to string representations.\n * Arrays larger than this will use reference equality to avoid memory overhead.\n * 128 bytes is enough for common ID formats (ULIDs are 16 bytes, UUIDs are 16 bytes)\n * while avoiding excessive string allocation for large binary data.\n */\nconst UINT8ARRAY_NORMALIZE_THRESHOLD = 128\n\n/**\n * Normalize a value for comparison and Map key usage\n * Converts values that can't be directly compared or used as Map keys\n * into comparable primitive representations\n */\nexport function normalizeValue(value: any): any {\n if (value instanceof Date) {\n return value.getTime()\n }\n\n // Normalize Uint8Arrays/Buffers to a string representation for Map key usage\n // This enables content-based equality for binary data like ULIDs\n const isUint8Array =\n (typeof Buffer !== `undefined` && value instanceof Buffer) ||\n value instanceof Uint8Array\n\n if (isUint8Array) {\n // Only normalize small arrays to avoid memory overhead for large binary data\n if (value.byteLength <= UINT8ARRAY_NORMALIZE_THRESHOLD) {\n // Convert to a string representation that can be used as a Map key\n // Use a special prefix to avoid collisions with user strings\n return `__u8__${Array.from(value).join(`,`)}`\n }\n // For large arrays, fall back to reference equality\n // Users working with large binary data should use a derived key if needed\n }\n\n return value\n}\n\n/**\n * Compare two values for equality, with special handling for Uint8Arrays and Buffers\n */\nexport function areValuesEqual(a: any, b: any): boolean {\n // Fast path for reference equality\n if (a === b) {\n return true\n }\n\n // Check for Uint8Array/Buffer comparison\n const aIsUint8Array =\n (typeof Buffer !== `undefined` && a instanceof Buffer) ||\n a instanceof Uint8Array\n const bIsUint8Array =\n (typeof Buffer !== `undefined` && b instanceof Buffer) ||\n b instanceof Uint8Array\n\n // If both are Uint8Arrays, compare by content\n if (aIsUint8Array && bIsUint8Array) {\n return areUint8ArraysEqual(a, b)\n }\n\n // Different types or not Uint8Arrays\n return false\n}\n"],"names":[],"mappings":";;AAGA,MAAM,gCAAgB,QAAA;AACtB,IAAI,eAAe;AAKnB,SAAS,YAAY,KAAqB;AACxC,MAAI,UAAU,IAAI,GAAG,GAAG;AACtB,WAAO,UAAU,IAAI,GAAG;AAAA,EAC1B;AACA,QAAM,KAAK;AACX,YAAU,IAAI,KAAK,EAAE;AACrB,SAAO;AACT;AAOO,MAAM,gBAAgB,CAAC,GAAQ,GAAQ,SAAiC;AAC7E,QAAM,EAAE,UAAU;AAGlB,MAAI,KAAK,QAAQ,KAAK,KAAM,QAAO;AACnC,MAAI,KAAK,KAAM,QAAO,UAAU,UAAU,KAAK;AAC/C,MAAI,KAAK,KAAM,QAAO,UAAU,UAAU,IAAI;AAG9C,MAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;AAClD,QAAI,KAAK,eAAe,UAAU;AAChC,aAAO,EAAE,cAAc,GAAG,KAAK,QAAQ,KAAK,aAAa;AAAA,IAC3D;AAAA,EAEF;AAGA,MAAI,MAAM,QAAQ,CAAC,KAAK,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EACT;AACA,WAAS,IAAI,GAAG,IAAI,EAAE,YAAY,KAAK;AACrC,QAAI,EAAE,CAAC,MAAM,EAAE,CAAC,GAAG;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAQA,MAAM,iCAAiC;AAOhC,SAAS,eAAe,OAAiB;AAC9C,MAAI,iBAAiB,MAAM;AACzB,WAAO,MAAM,QAAA;AAAA,EACf;AAIA,QAAM,eACH,OAAO,WAAW,eAAe,iBAAiB,UACnD,iBAAiB;AAEnB,MAAI,cAAc;AAEhB,QAAI,MAAM,cAAc,gCAAgC;AAGtD,aAAO,SAAS,MAAM,KAAK,KAAK,EAAE,KAAK,GAAG,CAAC;AAAA,IAC7C;AAAA,EAGF;AAEA,SAAO;AACT;AAKO,SAAS,eAAe,GAAQ,GAAiB;AAEtD,MAAI,MAAM,GAAG;AACX,WAAO;AAAA,EACT;AAGA,QAAM,gBACH,OAAO,WAAW,eAAe,aAAa,UAC/C,aAAa;AACf,QAAM,gBACH,OAAO,WAAW,eAAe,aAAa,UAC/C,aAAa;AAGf,MAAI,iBAAiB,eAAe;AAClC,WAAO,oBAAoB,GAAG,CAAC;AAAA,EACjC;AAGA,SAAO;AACT
|
|
1
|
+
{"version":3,"file":"comparison.cjs","sources":["../../../src/utils/comparison.ts"],"sourcesContent":["import type { CompareOptions } from '../query/builder/types'\n\n// WeakMap to store stable IDs for objects\nconst objectIds = new WeakMap<object, number>()\nlet nextObjectId = 1\n\n/**\n * Get or create a stable ID for an object\n */\nfunction getObjectId(obj: object): number {\n if (objectIds.has(obj)) {\n return objectIds.get(obj)!\n }\n const id = nextObjectId++\n objectIds.set(obj, id)\n return id\n}\n\n/**\n * Universal comparison function for all data types\n * Handles null/undefined, strings, arrays, dates, objects, and primitives\n * Always sorts null/undefined values first\n */\nexport const ascComparator = (a: any, b: any, opts: CompareOptions): number => {\n const { nulls } = opts\n\n // Handle null/undefined\n if (a == null && b == null) return 0\n if (a == null) return nulls === `first` ? -1 : 1\n if (b == null) return nulls === `first` ? 1 : -1\n\n // if a and b are both strings, compare them based on locale\n if (typeof a === `string` && typeof b === `string`) {\n if (opts.stringSort === `locale`) {\n return a.localeCompare(b, opts.locale, opts.localeOptions)\n }\n // For lexical sort we rely on direct comparison for primitive values\n }\n\n // if a and b are both arrays, compare them element by element\n if (Array.isArray(a) && Array.isArray(b)) {\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const result = ascComparator(a[i], b[i], opts)\n if (result !== 0) {\n return result\n }\n }\n // All elements are equal up to the minimum length\n return a.length - b.length\n }\n\n // If both are dates, compare them\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() - b.getTime()\n }\n\n // If at least one of the values is an object, use stable IDs for comparison\n const aIsObject = typeof a === `object`\n const bIsObject = typeof b === `object`\n\n if (aIsObject || bIsObject) {\n // If both are objects, compare their stable IDs\n if (aIsObject && bIsObject) {\n const aId = getObjectId(a)\n const bId = getObjectId(b)\n return aId - bId\n }\n\n // If only one is an object, objects come after primitives\n if (aIsObject) return 1\n if (bIsObject) return -1\n }\n\n // For primitive values, use direct comparison\n if (a < b) return -1\n if (a > b) return 1\n return 0\n}\n\n/**\n * Descending comparator function for ordering values\n * Handles null/undefined as largest values (opposite of ascending)\n */\nexport const descComparator = (\n a: unknown,\n b: unknown,\n opts: CompareOptions,\n): number => {\n return ascComparator(b, a, {\n ...opts,\n nulls: opts.nulls === `first` ? `last` : `first`,\n })\n}\n\nexport function makeComparator(\n opts: CompareOptions,\n): (a: any, b: any) => number {\n return (a, b) => {\n if (opts.direction === `asc`) {\n return ascComparator(a, b, opts)\n } else {\n return descComparator(a, b, opts)\n }\n }\n}\n\n/** Default comparator orders values in ascending order with nulls first and locale string comparison. */\nexport const defaultComparator = makeComparator({\n direction: `asc`,\n nulls: `first`,\n stringSort: `locale`,\n})\n\n/**\n * Compare two Uint8Arrays for content equality\n */\nfunction areUint8ArraysEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) {\n return false\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false\n }\n }\n return true\n}\n\n/**\n * Threshold for normalizing Uint8Arrays to string representations.\n * Arrays larger than this will use reference equality to avoid memory overhead.\n * 128 bytes is enough for common ID formats (ULIDs are 16 bytes, UUIDs are 16 bytes)\n * while avoiding excessive string allocation for large binary data.\n */\nconst UINT8ARRAY_NORMALIZE_THRESHOLD = 128\n\n/**\n * Sentinel value representing undefined in normalized form.\n * This allows distinguishing between \"start from beginning\" (undefined parameter)\n * and \"start from the key undefined\" (actual undefined value in the tree).\n */\nexport const UNDEFINED_SENTINEL = `__TS_DB_BTREE_UNDEFINED_VALUE__`\n\n/**\n * Normalize a value for comparison and Map key usage\n * Converts values that can't be directly compared or used as Map keys\n * into comparable primitive representations\n *\n * Note: This does NOT convert undefined to a sentinel. Use normalizeForBTree\n * for BTree index operations that need to distinguish undefined values.\n */\nexport function normalizeValue(value: any): any {\n if (value instanceof Date) {\n return value.getTime()\n }\n\n // Normalize Uint8Arrays/Buffers to a string representation for Map key usage\n // This enables content-based equality for binary data like ULIDs\n const isUint8Array =\n (typeof Buffer !== `undefined` && value instanceof Buffer) ||\n value instanceof Uint8Array\n\n if (isUint8Array) {\n // Only normalize small arrays to avoid memory overhead for large binary data\n if (value.byteLength <= UINT8ARRAY_NORMALIZE_THRESHOLD) {\n // Convert to a string representation that can be used as a Map key\n // Use a special prefix to avoid collisions with user strings\n return `__u8__${Array.from(value).join(`,`)}`\n }\n // For large arrays, fall back to reference equality\n // Users working with large binary data should use a derived key if needed\n }\n\n return value\n}\n\n/**\n * Normalize a value for BTree index usage.\n * Extends normalizeValue to also convert undefined to a sentinel value.\n * This is needed because the BTree does not properly support `undefined` as a key\n * (it interprets undefined as \"start from beginning\" in nextHigherPair/nextLowerPair).\n */\nexport function normalizeForBTree(value: any): any {\n if (value === undefined) {\n return UNDEFINED_SENTINEL\n }\n return normalizeValue(value)\n}\n\n/**\n * Converts the `UNDEFINED_SENTINEL` back to `undefined`.\n * Needed such that the sentinel is converted back to `undefined` before comparison.\n */\nexport function denormalizeUndefined(value: any): any {\n if (value === UNDEFINED_SENTINEL) {\n return undefined\n }\n return value\n}\n\n/**\n * Compare two values for equality, with special handling for Uint8Arrays and Buffers\n */\nexport function areValuesEqual(a: any, b: any): boolean {\n // Fast path for reference equality\n if (a === b) {\n return true\n }\n\n // Check for Uint8Array/Buffer comparison\n const aIsUint8Array =\n (typeof Buffer !== `undefined` && a instanceof Buffer) ||\n a instanceof Uint8Array\n const bIsUint8Array =\n (typeof Buffer !== `undefined` && b instanceof Buffer) ||\n b instanceof Uint8Array\n\n // If both are Uint8Arrays, compare by content\n if (aIsUint8Array && bIsUint8Array) {\n return areUint8ArraysEqual(a, b)\n }\n\n // Different types or not Uint8Arrays\n return false\n}\n"],"names":[],"mappings":";;AAGA,MAAM,gCAAgB,QAAA;AACtB,IAAI,eAAe;AAKnB,SAAS,YAAY,KAAqB;AACxC,MAAI,UAAU,IAAI,GAAG,GAAG;AACtB,WAAO,UAAU,IAAI,GAAG;AAAA,EAC1B;AACA,QAAM,KAAK;AACX,YAAU,IAAI,KAAK,EAAE;AACrB,SAAO;AACT;AAOO,MAAM,gBAAgB,CAAC,GAAQ,GAAQ,SAAiC;AAC7E,QAAM,EAAE,UAAU;AAGlB,MAAI,KAAK,QAAQ,KAAK,KAAM,QAAO;AACnC,MAAI,KAAK,KAAM,QAAO,UAAU,UAAU,KAAK;AAC/C,MAAI,KAAK,KAAM,QAAO,UAAU,UAAU,IAAI;AAG9C,MAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;AAClD,QAAI,KAAK,eAAe,UAAU;AAChC,aAAO,EAAE,cAAc,GAAG,KAAK,QAAQ,KAAK,aAAa;AAAA,IAC3D;AAAA,EAEF;AAGA,MAAI,MAAM,QAAQ,CAAC,KAAK,MAAM,QAAQ,CAAC,GAAG;AACxC,aAAS,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,QAAQ,EAA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AE,CAAC,GAAG;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAQA,MAAM,iCAAiC;AAOhC,MAAM,qBAAqB;AAU3B,SAAS,eAAe,OAAiB;AAC9C,MAAI,iBAAiB,MAAM;AACzB,WAAO,MAAM,QAAA;AAAA,EACf;AAIA,QAAM,eACH,OAAO,WAAW,eAAe,iBAAiB,UACnD,iBAAiB;AAEnB,MAAI,cAAc;AAEhB,QAAI,MAAM,cAAc,gCAAgC;AAGtD,aAAO,SAAS,MAAM,KAAK,KAAK,EAAE,KAAK,GAAG,CAAC;AAAA,IAC7C;AAAA,EAGF;AAEA,SAAO;AACT;AAQO,SAAS,kBAAkB,OAAiB;AACjD,MAAI,UAAU,QAAW;AACvB,WAAO;AAAA,EACT;AACA,SAAO,eAAe,KAAK;AAC7B;AAMO,SAAS,qBAAqB,OAAiB;AACpD,MAAI,UAAU,oBAAoB;AAChC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAKO,SAAS,eAAe,GAAQ,GAAiB;AAEtD,MAAI,MAAM,GAAG;AACX,WAAO;AAAA,EACT;AAGA,QAAM,gBACH,OAAO,WAAW,eAAe,aAAa,UAC/C,aAAa;AACf,QAAM,gBACH,OAAO,WAAW,eAAe,aAAa,UAC/C,aAAa;AAGf,MAAI,iBAAiB,eAAe;AAClC,WAAO,oBAAoB,GAAG,CAAC;AAAA,EACjC;AAGA,SAAO;AACT;;;;;;;;;;"}
|
|
@@ -13,12 +13,33 @@ export declare const descComparator: (a: unknown, b: unknown, opts: CompareOptio
|
|
|
13
13
|
export declare function makeComparator(opts: CompareOptions): (a: any, b: any) => number;
|
|
14
14
|
/** Default comparator orders values in ascending order with nulls first and locale string comparison. */
|
|
15
15
|
export declare const defaultComparator: (a: any, b: any) => number;
|
|
16
|
+
/**
|
|
17
|
+
* Sentinel value representing undefined in normalized form.
|
|
18
|
+
* This allows distinguishing between "start from beginning" (undefined parameter)
|
|
19
|
+
* and "start from the key undefined" (actual undefined value in the tree).
|
|
20
|
+
*/
|
|
21
|
+
export declare const UNDEFINED_SENTINEL = "__TS_DB_BTREE_UNDEFINED_VALUE__";
|
|
16
22
|
/**
|
|
17
23
|
* Normalize a value for comparison and Map key usage
|
|
18
24
|
* Converts values that can't be directly compared or used as Map keys
|
|
19
25
|
* into comparable primitive representations
|
|
26
|
+
*
|
|
27
|
+
* Note: This does NOT convert undefined to a sentinel. Use normalizeForBTree
|
|
28
|
+
* for BTree index operations that need to distinguish undefined values.
|
|
20
29
|
*/
|
|
21
30
|
export declare function normalizeValue(value: any): any;
|
|
31
|
+
/**
|
|
32
|
+
* Normalize a value for BTree index usage.
|
|
33
|
+
* Extends normalizeValue to also convert undefined to a sentinel value.
|
|
34
|
+
* This is needed because the BTree does not properly support `undefined` as a key
|
|
35
|
+
* (it interprets undefined as "start from beginning" in nextHigherPair/nextLowerPair).
|
|
36
|
+
*/
|
|
37
|
+
export declare function normalizeForBTree(value: any): any;
|
|
38
|
+
/**
|
|
39
|
+
* Converts the `UNDEFINED_SENTINEL` back to `undefined`.
|
|
40
|
+
* Needed such that the sentinel is converted back to `undefined` before comparison.
|
|
41
|
+
*/
|
|
42
|
+
export declare function denormalizeUndefined(value: any): any;
|
|
22
43
|
/**
|
|
23
44
|
* Compare two values for equality, with special handling for Uint8Arrays and Buffers
|
|
24
45
|
*/
|
|
@@ -158,7 +158,7 @@ function getOrderedKeys(collection, orderBy, limit, whereFilter, optimizedOnly)
|
|
|
158
158
|
}
|
|
159
159
|
return whereFilter?.(value) ?? true;
|
|
160
160
|
};
|
|
161
|
-
return index.
|
|
161
|
+
return index.takeFromStart(limit ?? index.keyCount, filterFn);
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
164
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"change-events.js","sources":["../../../src/collection/change-events.ts"],"sourcesContent":["import {\n createSingleRowRefProxy,\n toExpression,\n} from '../query/builder/ref-proxy'\nimport {\n compileSingleRowExpression,\n toBooleanPredicate,\n} from '../query/compiler/evaluators.js'\nimport {\n findIndexForField,\n optimizeExpressionWithIndexes,\n} from '../utils/index-optimization.js'\nimport { ensureIndexForField } from '../indexes/auto-index.js'\nimport { makeComparator } from '../utils/comparison.js'\nimport { buildCompareOptions } from '../query/compiler/order-by'\nimport type {\n ChangeMessage,\n CollectionLike,\n CurrentStateAsChangesOptions,\n SubscribeChangesOptions,\n} from '../types'\nimport type { CollectionImpl } from './index.js'\nimport type { SingleRowRefProxy } from '../query/builder/ref-proxy'\nimport type { BasicExpression, OrderBy } from '../query/ir.js'\n\n/**\n * Returns the current state of the collection as an array of changes\n * @param collection - The collection to get changes from\n * @param options - Options including optional where filter, orderBy, and limit\n * @returns An array of changes\n * @example\n * // Get all items as changes\n * const allChanges = currentStateAsChanges(collection)\n *\n * // Get only items matching a condition\n * const activeChanges = currentStateAsChanges(collection, {\n * where: (row) => row.status === 'active'\n * })\n *\n * // Get only items using a pre-compiled expression\n * const activeChanges = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active')\n * })\n *\n * // Get items ordered by name with limit\n * const topUsers = currentStateAsChanges(collection, {\n * orderBy: [{ expression: row.name, compareOptions: { direction: 'asc' } }],\n * limit: 10\n * })\n *\n * // Get active users ordered by score (highest score first)\n * const topActiveUsers = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active'),\n * orderBy: [{ expression: row.score, compareOptions: { direction: 'desc' } }],\n * })\n */\nexport function currentStateAsChanges<\n T extends object,\n TKey extends string | number,\n>(\n collection: CollectionLike<T, TKey>,\n options: CurrentStateAsChangesOptions = {},\n): Array<ChangeMessage<T>> | void {\n // Helper function to collect filtered results\n const collectFilteredResults = (\n filterFn?: (value: T) => boolean,\n ): Array<ChangeMessage<T>> => {\n const result: Array<ChangeMessage<T>> = []\n for (const [key, value] of collection.entries()) {\n // If no filter function is provided, include all items\n if (filterFn?.(value) ?? true) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // Validate that limit without orderBy doesn't happen\n if (options.limit !== undefined && !options.orderBy) {\n throw new Error(`limit cannot be used without orderBy`)\n }\n\n // First check if orderBy is present (optionally with limit)\n if (options.orderBy) {\n // Create where filter function if present\n const whereFilter = options.where\n ? createFilterFunctionFromExpression(options.where)\n : undefined\n\n // Get ordered keys using index optimization when possible\n const orderedKeys = getOrderedKeys(\n collection,\n options.orderBy,\n options.limit,\n whereFilter,\n options.optimizedOnly,\n )\n\n if (orderedKeys === undefined) {\n // `getOrderedKeys` returned undefined because we asked for `optimizedOnly` and there was no index to use\n return\n }\n\n // Convert keys to change messages\n const result: Array<ChangeMessage<T>> = []\n for (const key of orderedKeys) {\n const value = collection.get(key)\n if (value !== undefined) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // If no orderBy OR orderBy optimization failed, use where clause optimization\n if (!options.where) {\n // No filtering, return all items\n return collectFilteredResults()\n }\n\n // There's a where clause, let's see if we can use an index\n try {\n const expression: BasicExpression<boolean> = options.where\n\n // Try to optimize the query using indexes\n const optimizationResult = optimizeExpressionWithIndexes(\n expression,\n collection,\n )\n\n if (optimizationResult.canOptimize) {\n // Use index optimization\n const result: Array<ChangeMessage<T>> = []\n for (const key of optimizationResult.matchingKeys) {\n const value = collection.get(key)\n if (value !== undefined) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n } else {\n if (options.optimizedOnly) {\n return\n }\n\n const filterFn = createFilterFunctionFromExpression(expression)\n return collectFilteredResults(filterFn)\n }\n } catch (error) {\n // If anything goes wrong with the where clause, fall back to full scan\n console.warn(\n `${collection.id ? `[${collection.id}] ` : ``}Error processing where clause, falling back to full scan:`,\n error,\n )\n\n const filterFn = createFilterFunctionFromExpression(options.where)\n\n if (options.optimizedOnly) {\n return\n }\n\n return collectFilteredResults(filterFn)\n }\n}\n\n/**\n * Creates a filter function from a where callback\n * @param whereCallback - The callback function that defines the filter condition\n * @returns A function that takes an item and returns true if it matches the filter\n */\nexport function createFilterFunction<T extends object>(\n whereCallback: (row: SingleRowRefProxy<T>) => any,\n): (item: T) => boolean {\n return (item: T): boolean => {\n try {\n // First try the RefProxy approach for query builder functions\n const singleRowRefProxy = createSingleRowRefProxy<T>()\n const whereExpression = whereCallback(singleRowRefProxy)\n const expression = toExpression(whereExpression)\n const evaluator = compileSingleRowExpression(expression)\n const result = evaluator(item as Record<string, unknown>)\n // WHERE clauses should always evaluate to boolean predicates (Kevin's feedback)\n return toBooleanPredicate(result)\n } catch {\n // If RefProxy approach fails (e.g., arithmetic operations), fall back to direct evaluation\n try {\n // Create a simple proxy that returns actual values for arithmetic operations\n const simpleProxy = new Proxy(item as any, {\n get(target, prop) {\n return target[prop]\n },\n }) as SingleRowRefProxy<T>\n\n const result = whereCallback(simpleProxy)\n return toBooleanPredicate(result)\n } catch {\n // If both approaches fail, exclude the item\n return false\n }\n }\n }\n}\n\n/**\n * Creates a filter function from a pre-compiled expression\n * @param expression - The pre-compiled expression to evaluate\n * @returns A function that takes an item and returns true if it matches the filter\n */\nexport function createFilterFunctionFromExpression<T extends object>(\n expression: BasicExpression<boolean>,\n): (item: T) => boolean {\n // Compile expression once when filter function is created, not on every invocation\n const evaluator = compileSingleRowExpression(expression)\n\n return (item: T): boolean => {\n try {\n const result = evaluator(item as Record<string, unknown>)\n return toBooleanPredicate(result)\n } catch {\n // If evaluation fails, exclude the item\n return false\n }\n }\n}\n\n/**\n * Creates a filtered callback that only calls the original callback with changes that match the where clause\n * @param originalCallback - The original callback to filter\n * @param options - The subscription options containing the where clause\n * @returns A filtered callback function\n */\nexport function createFilteredCallback<T extends object>(\n originalCallback: (changes: Array<ChangeMessage<T>>) => void,\n options: SubscribeChangesOptions,\n): (changes: Array<ChangeMessage<T>>) => void {\n const filterFn = createFilterFunctionFromExpression(options.whereExpression!)\n\n return (changes: Array<ChangeMessage<T>>) => {\n const filteredChanges: Array<ChangeMessage<T>> = []\n\n for (const change of changes) {\n if (change.type === `insert`) {\n // For inserts, check if the new value matches the filter\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n } else if (change.type === `update`) {\n // For updates, we need to check both old and new values\n const newValueMatches = filterFn(change.value)\n const oldValueMatches = change.previousValue\n ? filterFn(change.previousValue)\n : false\n\n if (newValueMatches && oldValueMatches) {\n // Both old and new match: emit update\n filteredChanges.push(change)\n } else if (newValueMatches && !oldValueMatches) {\n // New matches but old didn't: emit insert\n filteredChanges.push({\n ...change,\n type: `insert`,\n })\n } else if (!newValueMatches && oldValueMatches) {\n // Old matched but new doesn't: emit delete\n filteredChanges.push({\n ...change,\n type: `delete`,\n value: change.previousValue!, // Use the previous value for the delete\n })\n }\n // If neither matches, don't emit anything\n } else {\n // For deletes, include if the previous value would have matched\n // (so subscribers know something they were tracking was deleted)\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n }\n }\n\n // Always call the original callback if we have filtered changes OR\n // if the original changes array was empty (which indicates a ready signal)\n if (filteredChanges.length > 0 || changes.length === 0) {\n originalCallback(filteredChanges)\n }\n }\n}\n\n/**\n * Gets ordered keys from a collection using index optimization when possible\n * @param collection - The collection to get keys from\n * @param orderBy - The order by clause\n * @param limit - Optional limit on number of keys to return\n * @param whereFilter - Optional filter function to apply while traversing\n * @returns Array of keys in sorted order\n */\nfunction getOrderedKeys<T extends object, TKey extends string | number>(\n collection: CollectionLike<T, TKey>,\n orderBy: OrderBy,\n limit?: number,\n whereFilter?: (item: T) => boolean,\n optimizedOnly?: boolean,\n): Array<TKey> | undefined {\n // For single-column orderBy on a ref expression, try index optimization\n if (orderBy.length === 1) {\n const clause = orderBy[0]!\n const orderByExpression = clause.expression\n\n if (orderByExpression.type === `ref`) {\n const propRef = orderByExpression\n const fieldPath = propRef.path\n const compareOpts = buildCompareOptions(clause, collection)\n\n // Ensure index exists for this field\n ensureIndexForField(\n fieldPath[0]!,\n fieldPath,\n collection as CollectionImpl<T, TKey>,\n compareOpts,\n )\n\n // Find the index\n const index = findIndexForField(collection, fieldPath, compareOpts)\n\n if (index && index.supports(`gt`)) {\n // Use index optimization\n const filterFn = (key: TKey): boolean => {\n const value = collection.get(key)\n if (value === undefined) {\n return false\n }\n return whereFilter?.(value) ?? true\n }\n\n // Take the keys that match the filter and limit\n // if no limit is provided `index.keyCount` is used,\n // i.e. we will take all keys that match the filter\n return index.take(limit ?? index.keyCount, undefined, filterFn)\n }\n }\n }\n\n if (optimizedOnly) {\n return\n }\n\n // Fallback: collect all items and sort in memory\n const allItems: Array<{ key: TKey; value: T }> = []\n for (const [key, value] of collection.entries()) {\n if (whereFilter?.(value) ?? true) {\n allItems.push({ key, value })\n }\n }\n\n // Sort using makeComparator\n const compare = (a: { key: TKey; value: T }, b: { key: TKey; value: T }) => {\n for (const clause of orderBy) {\n const compareFn = makeComparator(clause.compareOptions)\n\n // Extract values for comparison\n const aValue = extractValueFromItem(a.value, clause.expression)\n const bValue = extractValueFromItem(b.value, clause.expression)\n\n const result = compareFn(aValue, bValue)\n if (result !== 0) {\n return result\n }\n }\n return 0\n }\n\n allItems.sort(compare)\n const sortedKeys = allItems.map((item) => item.key)\n\n // Apply limit if provided\n if (limit !== undefined) {\n return sortedKeys.slice(0, limit)\n }\n\n // if no limit is provided, we will return all keys\n return sortedKeys\n}\n\n/**\n * Helper function to extract a value from an item based on an expression\n */\nfunction extractValueFromItem(item: any, expression: BasicExpression): any {\n if (expression.type === `ref`) {\n const propRef = expression\n let value = item\n for (const pathPart of propRef.path) {\n value = value?.[pathPart]\n }\n return value\n } else if (expression.type === `val`) {\n return expression.value\n } else {\n // It must be a function\n const evaluator = compileSingleRowExpression(expression)\n return evaluator(item as Record<string, unknown>)\n }\n}\n"],"names":[],"mappings":";;;;;AAwDO,SAAS,sBAId,YACA,UAAwC,IACR;AAEhC,QAAM,yBAAyB,CAC7B,aAC4B;AAC5B,UAAM,SAAkC,CAAA;AACxC,eAAW,CAAC,KAAK,KAAK,KAAK,WAAW,WAAW;AAE/C,UAAI,WAAW,KAAK,KAAK,MAAM;AAC7B,eAAO,KAAK;AAAA,UAC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U,QAAQ,MAAM;AACvC,UAAI,WAAW,GAAG;AAChB,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,WAAS,KAAK,OAAO;AACrB,QAAM,aAAa,SAAS,IAAI,CAAC,SAAS,KAAK,GAAG;AAGlD,MAAI,UAAU,QAAW;AACvB,WAAO,WAAW,MAAM,GAAG,KAAK;AAAA,EAClC;AAGA,SAAO;AACT;AAKA,SAAS,qBAAqB,MAAW,YAAkC;AACzE,MAAI,WAAW,SAAS,OAAO;AAC7B,UAAM,UAAU;AAChB,QAAI,QAAQ;AACZ,eAAW,YAAY,QAAQ,MAAM;AACnC,cAAQ,QAAQ,QAAQ;AAAA,IAC1B;AACA,WAAO;AAAA,EACT,WAAW,WAAW,SAAS,OAAO;AACpC,WAAO,WAAW;AAAA,EACpB,OAAO;AAEL,UAAM,YAAY,2BAA2B,UAAU;AACvD,WAAO,UAAU,IAA+B;AAAA,EAClD;AACF;"}
|
|
1
|
+
{"version":3,"file":"change-events.js","sources":["../../../src/collection/change-events.ts"],"sourcesContent":["import {\n createSingleRowRefProxy,\n toExpression,\n} from '../query/builder/ref-proxy'\nimport {\n compileSingleRowExpression,\n toBooleanPredicate,\n} from '../query/compiler/evaluators.js'\nimport {\n findIndexForField,\n optimizeExpressionWithIndexes,\n} from '../utils/index-optimization.js'\nimport { ensureIndexForField } from '../indexes/auto-index.js'\nimport { makeComparator } from '../utils/comparison.js'\nimport { buildCompareOptions } from '../query/compiler/order-by'\nimport type {\n ChangeMessage,\n CollectionLike,\n CurrentStateAsChangesOptions,\n SubscribeChangesOptions,\n} from '../types'\nimport type { CollectionImpl } from './index.js'\nimport type { SingleRowRefProxy } from '../query/builder/ref-proxy'\nimport type { BasicExpression, OrderBy } from '../query/ir.js'\n\n/**\n * Returns the current state of the collection as an array of changes\n * @param collection - The collection to get changes from\n * @param options - Options including optional where filter, orderBy, and limit\n * @returns An array of changes\n * @example\n * // Get all items as changes\n * const allChanges = currentStateAsChanges(collection)\n *\n * // Get only items matching a condition\n * const activeChanges = currentStateAsChanges(collection, {\n * where: (row) => row.status === 'active'\n * })\n *\n * // Get only items using a pre-compiled expression\n * const activeChanges = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active')\n * })\n *\n * // Get items ordered by name with limit\n * const topUsers = currentStateAsChanges(collection, {\n * orderBy: [{ expression: row.name, compareOptions: { direction: 'asc' } }],\n * limit: 10\n * })\n *\n * // Get active users ordered by score (highest score first)\n * const topActiveUsers = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active'),\n * orderBy: [{ expression: row.score, compareOptions: { direction: 'desc' } }],\n * })\n */\nexport function currentStateAsChanges<\n T extends object,\n TKey extends string | number,\n>(\n collection: CollectionLike<T, TKey>,\n options: CurrentStateAsChangesOptions = {},\n): Array<ChangeMessage<T>> | void {\n // Helper function to collect filtered results\n const collectFilteredResults = (\n filterFn?: (value: T) => boolean,\n ): Array<ChangeMessage<T>> => {\n const result: Array<ChangeMessage<T>> = []\n for (const [key, value] of collection.entries()) {\n // If no filter function is provided, include all items\n if (filterFn?.(value) ?? true) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // Validate that limit without orderBy doesn't happen\n if (options.limit !== undefined && !options.orderBy) {\n throw new Error(`limit cannot be used without orderBy`)\n }\n\n // First check if orderBy is present (optionally with limit)\n if (options.orderBy) {\n // Create where filter function if present\n const whereFilter = options.where\n ? createFilterFunctionFromExpression(options.where)\n : undefined\n\n // Get ordered keys using index optimization when possible\n const orderedKeys = getOrderedKeys(\n collection,\n options.orderBy,\n options.limit,\n whereFilter,\n options.optimizedOnly,\n )\n\n if (orderedKeys === undefined) {\n // `getOrderedKeys` returned undefined because we asked for `optimizedOnly` and there was no index to use\n return\n }\n\n // Convert keys to change messages\n const result: Array<ChangeMessage<T>> = []\n for (const key of orderedKeys) {\n const value = collection.get(key)\n if (value !== undefined) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // If no orderBy OR orderBy optimization failed, use where clause optimization\n if (!options.where) {\n // No filtering, return all items\n return collectFilteredResults()\n }\n\n // There's a where clause, let's see if we can use an index\n try {\n const expression: BasicExpression<boolean> = options.where\n\n // Try to optimize the query using indexes\n const optimizationResult = optimizeExpressionWithIndexes(\n expression,\n collection,\n )\n\n if (optimizationResult.canOptimize) {\n // Use index optimization\n const result: Array<ChangeMessage<T>> = []\n for (const key of optimizationResult.matchingKeys) {\n const value = collection.get(key)\n if (value !== undefined) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n } else {\n if (options.optimizedOnly) {\n return\n }\n\n const filterFn = createFilterFunctionFromExpression(expression)\n return collectFilteredResults(filterFn)\n }\n } catch (error) {\n // If anything goes wrong with the where clause, fall back to full scan\n console.warn(\n `${collection.id ? `[${collection.id}] ` : ``}Error processing where clause, falling back to full scan:`,\n error,\n )\n\n const filterFn = createFilterFunctionFromExpression(options.where)\n\n if (options.optimizedOnly) {\n return\n }\n\n return collectFilteredResults(filterFn)\n }\n}\n\n/**\n * Creates a filter function from a where callback\n * @param whereCallback - The callback function that defines the filter condition\n * @returns A function that takes an item and returns true if it matches the filter\n */\nexport function createFilterFunction<T extends object>(\n whereCallback: (row: SingleRowRefProxy<T>) => any,\n): (item: T) => boolean {\n return (item: T): boolean => {\n try {\n // First try the RefProxy approach for query builder functions\n const singleRowRefProxy = createSingleRowRefProxy<T>()\n const whereExpression = whereCallback(singleRowRefProxy)\n const expression = toExpression(whereExpression)\n const evaluator = compileSingleRowExpression(expression)\n const result = evaluator(item as Record<string, unknown>)\n // WHERE clauses should always evaluate to boolean predicates (Kevin's feedback)\n return toBooleanPredicate(result)\n } catch {\n // If RefProxy approach fails (e.g., arithmetic operations), fall back to direct evaluation\n try {\n // Create a simple proxy that returns actual values for arithmetic operations\n const simpleProxy = new Proxy(item as any, {\n get(target, prop) {\n return target[prop]\n },\n }) as SingleRowRefProxy<T>\n\n const result = whereCallback(simpleProxy)\n return toBooleanPredicate(result)\n } catch {\n // If both approaches fail, exclude the item\n return false\n }\n }\n }\n}\n\n/**\n * Creates a filter function from a pre-compiled expression\n * @param expression - The pre-compiled expression to evaluate\n * @returns A function that takes an item and returns true if it matches the filter\n */\nexport function createFilterFunctionFromExpression<T extends object>(\n expression: BasicExpression<boolean>,\n): (item: T) => boolean {\n // Compile expression once when filter function is created, not on every invocation\n const evaluator = compileSingleRowExpression(expression)\n\n return (item: T): boolean => {\n try {\n const result = evaluator(item as Record<string, unknown>)\n return toBooleanPredicate(result)\n } catch {\n // If evaluation fails, exclude the item\n return false\n }\n }\n}\n\n/**\n * Creates a filtered callback that only calls the original callback with changes that match the where clause\n * @param originalCallback - The original callback to filter\n * @param options - The subscription options containing the where clause\n * @returns A filtered callback function\n */\nexport function createFilteredCallback<T extends object>(\n originalCallback: (changes: Array<ChangeMessage<T>>) => void,\n options: SubscribeChangesOptions,\n): (changes: Array<ChangeMessage<T>>) => void {\n const filterFn = createFilterFunctionFromExpression(options.whereExpression!)\n\n return (changes: Array<ChangeMessage<T>>) => {\n const filteredChanges: Array<ChangeMessage<T>> = []\n\n for (const change of changes) {\n if (change.type === `insert`) {\n // For inserts, check if the new value matches the filter\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n } else if (change.type === `update`) {\n // For updates, we need to check both old and new values\n const newValueMatches = filterFn(change.value)\n const oldValueMatches = change.previousValue\n ? filterFn(change.previousValue)\n : false\n\n if (newValueMatches && oldValueMatches) {\n // Both old and new match: emit update\n filteredChanges.push(change)\n } else if (newValueMatches && !oldValueMatches) {\n // New matches but old didn't: emit insert\n filteredChanges.push({\n ...change,\n type: `insert`,\n })\n } else if (!newValueMatches && oldValueMatches) {\n // Old matched but new doesn't: emit delete\n filteredChanges.push({\n ...change,\n type: `delete`,\n value: change.previousValue!, // Use the previous value for the delete\n })\n }\n // If neither matches, don't emit anything\n } else {\n // For deletes, include if the previous value would have matched\n // (so subscribers know something they were tracking was deleted)\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n }\n }\n\n // Always call the original callback if we have filtered changes OR\n // if the original changes array was empty (which indicates a ready signal)\n if (filteredChanges.length > 0 || changes.length === 0) {\n originalCallback(filteredChanges)\n }\n }\n}\n\n/**\n * Gets ordered keys from a collection using index optimization when possible\n * @param collection - The collection to get keys from\n * @param orderBy - The order by clause\n * @param limit - Optional limit on number of keys to return\n * @param whereFilter - Optional filter function to apply while traversing\n * @returns Array of keys in sorted order\n */\nfunction getOrderedKeys<T extends object, TKey extends string | number>(\n collection: CollectionLike<T, TKey>,\n orderBy: OrderBy,\n limit?: number,\n whereFilter?: (item: T) => boolean,\n optimizedOnly?: boolean,\n): Array<TKey> | undefined {\n // For single-column orderBy on a ref expression, try index optimization\n if (orderBy.length === 1) {\n const clause = orderBy[0]!\n const orderByExpression = clause.expression\n\n if (orderByExpression.type === `ref`) {\n const propRef = orderByExpression\n const fieldPath = propRef.path\n const compareOpts = buildCompareOptions(clause, collection)\n\n // Ensure index exists for this field\n ensureIndexForField(\n fieldPath[0]!,\n fieldPath,\n collection as CollectionImpl<T, TKey>,\n compareOpts,\n )\n\n // Find the index\n const index = findIndexForField(collection, fieldPath, compareOpts)\n\n if (index && index.supports(`gt`)) {\n // Use index optimization\n const filterFn = (key: TKey): boolean => {\n const value = collection.get(key)\n if (value === undefined) {\n return false\n }\n return whereFilter?.(value) ?? true\n }\n\n // Take the keys that match the filter and limit\n // if no limit is provided `index.keyCount` is used,\n // i.e. we will take all keys that match the filter\n return index.takeFromStart(limit ?? index.keyCount, filterFn)\n }\n }\n }\n\n if (optimizedOnly) {\n return\n }\n\n // Fallback: collect all items and sort in memory\n const allItems: Array<{ key: TKey; value: T }> = []\n for (const [key, value] of collection.entries()) {\n if (whereFilter?.(value) ?? true) {\n allItems.push({ key, value })\n }\n }\n\n // Sort using makeComparator\n const compare = (a: { key: TKey; value: T }, b: { key: TKey; value: T }) => {\n for (const clause of orderBy) {\n const compareFn = makeComparator(clause.compareOptions)\n\n // Extract values for comparison\n const aValue = extractValueFromItem(a.value, clause.expression)\n const bValue = extractValueFromItem(b.value, clause.expression)\n\n const result = compareFn(aValue, bValue)\n if (result !== 0) {\n return result\n }\n }\n return 0\n }\n\n allItems.sort(compare)\n const sortedKeys = allItems.map((item) => item.key)\n\n // Apply limit if provided\n if (limit !== undefined) {\n return sortedKeys.slice(0, limit)\n }\n\n // if no limit is provided, we will return all keys\n return sortedKeys\n}\n\n/**\n * Helper function to extract a value from an item based on an expression\n */\nfunction extractValueFromItem(item: any, expression: BasicExpression): any {\n if (expression.type === `ref`) {\n const propRef = expression\n let value = item\n for (const pathPart of propRef.path) {\n value = value?.[pathPart]\n }\n return value\n } else if (expression.type === `val`) {\n return expression.value\n } else {\n // It must be a function\n const evaluator = compileSingleRowExpression(expression)\n return evaluator(item as Record<string, unknown>)\n }\n}\n"],"names":[],"mappings":";;;;;AAwDO,SAAS,sBAId,YACA,UAAwC,IACR;AAEhC,QAAM,yBAAyB,CAC7B,aAC4B;AAC5B,UAAM,SAAkC,CAAA;AACxC,eAAW,CAAC,KAAK,KAAK,KAAK,WAAW,WAAW;AAE/C,UAAI,WAAW,KAAK,KAAK,MAAM;AAC7B,eAAO,KAAK;AAAA,UACV,MAAM;AAAA,UACN;AAAA,UACA;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAGA,MAAI,QAAQ,UAAU,UAAa,CAAC,QAAQ,SAAS;AACnD,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAGA,MAAI,QAAQ,SAAS;AAEnB,UAAM,cAAc,QAAQ,QACxB,mCAAmC,QAAQ,KAAK,IAChD;AAGJ,UAAM,cAAc;AAAA,MAClB;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA,QAAQ;AAAA,IAAA;AAGV,QAAI,gBAAgB,QAAW;AAE7B;AAAA,IACF;AAGA,UAAM,SAAkC,CAAA;AACxC,eAAW,OAAO,aAAa;AAC7B,YAAM,QAAQ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