Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

virtual-props.ts

247 lines8.3 KB

1/**
2 * Virtual Properties for TanStack DB
3 *
4 * Virtual properties are computed, read-only properties that provide metadata about rows
5 * (sync status, source, selection state) without being part of the persisted data model.
6 *
7 * Virtual properties are prefixed with `$` to distinguish them from user data fields.
8 * User schemas should not include `$`-prefixed fields as they are reserved.
9 */
10​
11/**
12 * Collection attribution for a row's current value.
13 *
14 * - `'local'`: An optimistic row, or a source write attributed through a
15 * same-key local mutation
16 * - `'remote'`: A source write without that local attribution
17 *
18 * Synced Collections infer attribution from key and timing, without a source
19 * client ID. With one persisting local mutation and no truncate, the first queued
20 * same-key source transaction published at successful mutation settlement
21 * consumes local attribution. Its surviving row is `'local'`; later source
22 * transactions are `'remote'`. A failed mutation gives those queued
23 * writes no local attribution. A truncate can publish while a mutation remains
24 * active, leaving its same-key row `'local'` even if the mutation later fails.
25 * An unconsumed active mutation on a key omitted by the truncate retains
26 * attribution for its first later same-key source transaction, even in that
27 * drain. A truncate's write consumes attribution for its key, so a later
28 * same-key transaction in that drain is `'remote'` without a new local owner.
29 * A source write on a still-pending manual mutation's key applies immediately
30 * and can keep `'local'` attribution if that mutation rolls back.
31 * When two same-key mutations both persist before a source transaction is
32 * queued, with no truncate, a successful one retains one local attribution
33 * for the key even if its sibling fails; two failures retain none.
34 * An independent peer write can be labeled `'local'`, and a later confirmation
35 * from this client can be labeled `'remote'`. Local-only Collections always use
36 * `'local'`.
37 */
38export type VirtualOrigin = 'local' | 'remote'
39​
40/**
41 * Virtual properties recognized on TanStack DB rows.
42 *
43 * These properties are:
44 * - Computed (not stored in the data model)
45 * - Read-only (cannot be mutated directly)
46 * - Available in queries (WHERE, ORDER BY, SELECT)
47 * - Included when spreading rows (`...user`)
48 *
49 * Structured whole-row selections and spreads retain source metadata.
50 * A functional selection retains it only when returning a source row directly.
51 * New functional objects and other projections receive the output Collection's
52 * metadata. Selected virtual names cannot change that attribution.
53 *
54 * @template TKey - The type of the row's key (string or number)
55 *
56 * @example
57 * ```typescript
58 * // Accessing virtual properties on a row
59 * const user = collection.get('user-1')
60 * if (!user.$hasPendingWrites) {
61 * console.log('No pending local optimistic writes for this row')
62 * }
63 * if (user.$origin === 'local') {
64 * console.log('Row has local attribution')
65 * }
66 * ```
67 *
68 * @example
69 * ```typescript
70 * // Using virtual properties in queries
71 * const ordersWithoutLocalWrites = createLiveQueryCollection({
72 * query: (q) => q
73 * .from({ order: orders })
74 * .where(({ order }) => eq(order.$hasPendingWrites, false))
75 * })
76 * ```
77 */
78export interface VirtualRowProps<
79 TKey extends string | number = string | number,
80> {
81 /**
82 * Whether this row currently has pending local optimistic writes.
83 *
84 * This describes the row's local optimistic state, not backend upload or
85 * acknowledgement. It is always `false` for local-only collections.
86 */
87 readonly $hasPendingWrites: boolean
88​
89 /**
90 * Collection attribution for this row's current value. `'local'` covers
91 * optimistic rows and attributed source writes; `'remote'` covers source
92 * writes without local attribution. See {@link VirtualOrigin} for the
93 * key-and-timing rules, including truncate and overlapping mutations.
94 *
95 * For local-only collections, this is always `'local'`.
96 * Whole-row live queries preserve source attribution. Projected row roots
97 * otherwise use the live-query Collection's attribution.
98 */
99 readonly $origin: VirtualOrigin
100​
101 /**
102 * The row's key (primary identifier).
103 *
104 * This is the same value returned by `collection.config.getKey(row)`.
105 * Useful when you need the key in projections or computations.
106 */
107 readonly $key: TKey
108​
109 /**
110 * The ID of the source collection this row originated from.
111 *
112 * In joins, this can help identify which collection each row came from.
113 * Whole-row live queries preserve the upstream Collection's ID. Projected
114 * row roots otherwise use the live-query Collection's ID.
115 */
116 readonly $collectionId: string
118​
119/**
120 * Adds virtual properties to a row type.
121 *
122 * @template T - The base row type
123 * @template TKey - The type of the row's key
124 *
125 * @example
126 * ```typescript
127 * type User = { id: string; name: string }
128 * type UserWithVirtual = WithVirtualProps<User, string>
129 * // { id: string; name: string; $hasPendingWrites: boolean; $origin: 'local' | 'remote'; $key: string; $collectionId: string }
130 * ```
131 */
132export type WithVirtualProps<
133 T extends object,
134 TKey extends string | number = string | number,
135> = T & VirtualRowProps<TKey>
136​
137/**
138 * Extracts the base type from a type that may have virtual properties.
139 * Useful when you need to work with the raw data without virtual properties.
140 *
141 * @template T - The type that may include virtual properties
142 *
143 * @example
144 * ```typescript
145 * type UserWithVirtual = { id: string; name: string; $hasPendingWrites: boolean; $origin: 'local' | 'remote' }
146 * type User = WithoutVirtualProps<UserWithVirtual>
147 * // { id: string; name: string }
148 * ```
149 */
150export type WithoutVirtualProps<T> = T extends unknown
151 ? Omit<T, keyof VirtualRowProps>
152 : never
153​
154/**
155 * Checks if a value has all virtual properties attached.
156 *
157 * @param value - The value to check
158 * @returns true if the value has virtual properties
159 *
160 * @example
161 * ```typescript
162 * if (hasVirtualProps(row)) {
163 * console.log('Pending local writes:', row.$hasPendingWrites)
164 * }
165 * ```
166 */
167export function hasVirtualProps(
168 value: unknown,
169): value is VirtualRowProps<string | number> {
170 return (
171 typeof value === 'object' &&
172 value !== null &&
173 ['$hasPendingWrites', '$origin', '$key', '$collectionId'].every(
174 (name) => name in value,
175 )
176 )
178​
179/**
180 * Enriches a row with virtual properties using the "add-if-missing" pattern.
181 *
182 * If the row already has virtual properties (from an upstream collection),
183 * they are preserved. If not, new virtual properties are computed and added.
184 *
185 * This is the key function that enables pass-through semantics for nested
186 * live query collections.
187 *
188 * @param row - The row to enrich
189 * @param key - The row's key
190 * @param collectionId - The collection's ID
191 * @param computePendingWrites - Function to compute $hasPendingWrites if missing
192 * @param computeOrigin - Function to compute $origin if missing
193 * @returns The row with virtual properties (possibly the same object if already present)
194 *
195 * @internal
196 */
197export function enrichRowWithVirtualProps<
198 T extends object,
199 TKey extends string | number,
200>(
201 row: T,
202 key: TKey,
203 collectionId: string,
204 computePendingWrites: () => boolean,
205 computeOrigin: () => VirtualOrigin,
206): WithVirtualProps<T, TKey> {
207 // Use nullish coalescing to preserve existing virtual properties (pass-through)
208 // This is the "add-if-missing" pattern described in the RFC
209 const existingRow = row as Partial<VirtualRowProps<TKey>>
210 const hasPendingWrites =
211 existingRow.$hasPendingWrites ?? computePendingWrites()
212​
213 return {
214 ...row,
215 $hasPendingWrites: hasPendingWrites,
216 $origin: existingRow.$origin ?? computeOrigin(),
217 $key: existingRow.$key ?? key,
218 $collectionId: existingRow.$collectionId ?? collectionId,
219 } as WithVirtualProps<T, TKey>
221​
222/**
223 * List of virtual property names for iteration and checking.
224 * @internal
225 */
226export const VIRTUAL_PROP_NAMES = [
227 '$hasPendingWrites',
228 '$origin',
229 '$key',
230 '$collectionId',
231] as const
232​
233/**
234 * Checks if a property name is a virtual property.
235 * @internal
236 */
237export function isVirtualPropName(name: string): boolean {
238 return VIRTUAL_PROP_NAMES.includes(name as any)
240​
241/**
242 * Checks whether a property path references a virtual property.
243 * @internal
244 */
245export function hasVirtualPropPath(path: Array<string>): boolean {
246 return path.some((segment) => isVirtualPropName(segment))