From 6b34f356fadaee0593c2282ca69a0ca31cee4162 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 11 Jun 2025 11:06:45 -0600 Subject: [PATCH 1/3] Expose utilities on collection instances --- .changeset/angry-chairs-tan.md | 21 +++ docs/overview.md | 8 +- examples/react/todo/src/App.tsx | 8 +- packages/db-collections/src/electric.ts | 39 ++++-- packages/db-collections/src/query.ts | 38 ++++-- .../db-collections/tests/electric.test.ts | 34 ++--- packages/db-collections/tests/query.test.ts | 50 +++---- packages/db/src/collection.ts | 60 ++++++--- packages/db/src/index.ts | 2 +- packages/db/src/query/compiled-query.ts | 7 +- packages/db/src/types.ts | 10 ++ packages/db/tests/collection-getters.test.ts | 9 +- .../collection-subscribe-changes.test.ts | 14 +- packages/db/tests/collection.test.ts | 26 ++-- .../db/tests/query/query-collection.test.ts | 38 +++--- packages/db/tests/transactions.test.ts | 16 +-- packages/db/tests/utility-exposure.test.ts | 122 ++++++++++++++++++ packages/react-db/src/index.ts | 2 +- packages/react-db/tests/useLiveQuery.test.tsx | 18 +-- packages/vue-db/src/index.ts | 2 +- packages/vue-db/tests/useLiveQuery.test.ts | 18 +-- 21 files changed, 374 insertions(+), 168 deletions(-) create mode 100644 .changeset/angry-chairs-tan.md create mode 100644 packages/db/tests/utility-exposure.test.ts diff --git a/.changeset/angry-chairs-tan.md b/.changeset/angry-chairs-tan.md new file mode 100644 index 0000000000..d3e38489d1 --- /dev/null +++ b/.changeset/angry-chairs-tan.md @@ -0,0 +1,21 @@ +--- +"@tanstack/db-collections": patch +"@tanstack/react-db": patch +"@tanstack/vue-db": patch +"@tanstack/db": patch +--- + +Expose utilities on collection instances + +Implemented a utility exposure pattern for TanStack DB collections that allows utility functions to be passed as part of collection options and exposes them under a `.utils` namespace, with full TypeScript typing. + +- Refactored `createCollection` in packages/db/src/collection.ts to accept options with utilities directly +- Added `utils` property to CollectionImpl +- Added TypeScript types for utility functions and utility records +- Changed Collection from a class to a type, updating all usages to use createCollection() instead +- Updated Electric/Query implementations + +- Utilities are now ergonomically accessible under `.utils` +- Full TypeScript typing is preserved for both collection data and utilities +- API is clean and straightforward - users can call `createCollection(optionsCreator(config))` directly +- Zero-boilerplate TypeScript pattern that infers utility types automatically diff --git a/docs/overview.md b/docs/overview.md index 6dd640a7ad..13defee117 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -200,7 +200,7 @@ export const todoCollection = createCollection(electricCollectionOptions({ }, getId: (item) => item.id, schema: todoSchema -}).options) +})) ``` The Electric collection requires two Electric-specific options: @@ -230,7 +230,7 @@ export const myPendingTodos = createCollection(electricCollectionOptions({ }, getId: (item) => item.id, schema: todoSchema -}).options) +})) ``` > [!TIP] @@ -524,7 +524,7 @@ const todoCollection = createCollection(queryCollectionOptions({ await api.todos.create(newTodo) } // also add onUpdate, onDelete as needed. -}).options) +})) const listCollection = createCollection(queryCollectionOptions({ queryKey: ["todo-lists"], queryFn: async () => fetch("/api/todo-lists"), @@ -537,7 +537,7 @@ const listCollection = createCollection(queryCollectionOptions({ await api.todoLists.create(newTodo) } // also add onUpdate, onDelete as needed. -}).options) +})) const Todos = () => { // Read the data using live queries. Here we show a live diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index 21a6bc3941..ad0b5b1697 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -179,7 +179,7 @@ const createTodoCollection = (type: CollectionType) => { return { txid: String(txids[0].txid) } }, - }).options + }) ) } else { // Query collection using our API helper @@ -224,7 +224,7 @@ const createTodoCollection = (type: CollectionType) => { }) ) }, - }).options + }) ) } collectionsCache.set(`todo`, newCollection) @@ -275,7 +275,7 @@ const createConfigCollection = (type: CollectionType) => { return { txid: String(txids[0]) } }, - }).options + }) ) } else { // Query collection using our API helper @@ -319,7 +319,7 @@ const createConfigCollection = (type: CollectionType) => { return { txid: String(txids[0]) } }, - }).options + }) ) } collectionsCache.set(`config`, newCollection) diff --git a/packages/db-collections/src/electric.ts b/packages/db-collections/src/electric.ts index 7e6b21ec4e..005e230d75 100644 --- a/packages/db-collections/src/electric.ts +++ b/packages/db-collections/src/electric.ts @@ -8,6 +8,7 @@ import type { CollectionConfig, MutationFnParams, SyncConfig, + UtilsRecord, } from "@tanstack/db" import type { ControlMessage, @@ -75,18 +76,27 @@ function hasTxids = Row>( ) } +/** + * Type for the awaitTxId utility function + */ +export type AwaitTxIdFn = (txId: string, timeout?: number) => Promise + +/** + * Electric collection utilities type + */ +export interface ElectricCollectionUtils extends UtilsRecord { + awaitTxId: AwaitTxIdFn +} + /** * Creates Electric collection options for use with a standard Collection * * @param config - Configuration options for the Electric collection - * @returns Object containing collection options and utility functions + * @returns Collection options with utilities */ export function electricCollectionOptions>( config: ElectricCollectionConfig -): { - options: CollectionConfig - awaitTxId: (txId: string, timeout?: number) => Promise -} { +) { const seenTxids = new Store>(new Set([`${Math.random()}`])) const sync = createElectricSync(config.shapeOptions, { seenTxids, @@ -98,7 +108,10 @@ export function electricCollectionOptions>( * @param timeout Optional timeout in milliseconds (defaults to 30000ms) * @returns Promise that resolves when the txId is synced */ - const awaitTxId = async (txId: string, timeout = 30000): Promise => { + const awaitTxId: AwaitTxIdFn = async ( + txId: string, + timeout = 30000 + ): Promise => { const hasTxid = seenTxids.state.has(txId) if (hasTxid) return true @@ -171,14 +184,14 @@ export function electricCollectionOptions>( const { shapeOptions, onInsert, onUpdate, onDelete, ...restConfig } = config return { - options: { - ...restConfig, - sync, - onInsert: wrappedOnInsert, - onUpdate: wrappedOnUpdate, - onDelete: wrappedOnDelete, + ...restConfig, + sync, + onInsert: wrappedOnInsert, + onUpdate: wrappedOnUpdate, + onDelete: wrappedOnDelete, + utils: { + awaitTxId, }, - awaitTxId, } } diff --git a/packages/db-collections/src/query.ts b/packages/db-collections/src/query.ts index 50579e8dac..ce45353a96 100644 --- a/packages/db-collections/src/query.ts +++ b/packages/db-collections/src/query.ts @@ -9,6 +9,7 @@ import type { CollectionConfig, MutationFnParams, SyncConfig, + UtilsRecord, } from "@tanstack/db" export interface QueryCollectionConfig< @@ -80,11 +81,23 @@ export interface QueryCollectionConfig< onDelete?: CollectionConfig[`onDelete`] } +/** + * Type for the refetch utility function + */ +export type RefetchFn = () => Promise + +/** + * Query collection utilities type + */ +export interface QueryCollectionUtils extends UtilsRecord { + refetch: RefetchFn +} + /** * Creates query collection options for use with a standard Collection * * @param config - Configuration options for the Query collection - * @returns Object containing collection options and utility functions + * @returns Collection options with utilities */ export function queryCollectionOptions< TItem extends object, @@ -92,10 +105,7 @@ export function queryCollectionOptions< TQueryKey extends QueryKey = QueryKey, >( config: QueryCollectionConfig -): { - options: CollectionConfig - refetch: () => Promise -} { +): CollectionConfig & { utils: QueryCollectionUtils } { const { queryKey, queryFn, @@ -254,7 +264,7 @@ export function queryCollectionOptions< * Refetch the query data * @returns Promise that resolves when the refetch is complete */ - const refetch = async (): Promise => { + const refetch: RefetchFn = async (): Promise => { console.log(`[QueryCollection] refetch() called for ${String(queryKey)}`) try { await queryClient.refetchQueries({ @@ -316,14 +326,14 @@ export function queryCollectionOptions< : undefined return { - options: { - ...baseCollectionConfig, - getId, - sync: { sync: internalSync }, - onInsert: wrappedOnInsert, - onUpdate: wrappedOnUpdate, - onDelete: wrappedOnDelete, + ...baseCollectionConfig, + getId, + sync: { sync: internalSync }, + onInsert: wrappedOnInsert, + onUpdate: wrappedOnUpdate, + onDelete: wrappedOnDelete, + utils: { + refetch, }, - refetch, } } diff --git a/packages/db-collections/tests/electric.test.ts b/packages/db-collections/tests/electric.test.ts index 316528c659..425f22fe8f 100644 --- a/packages/db-collections/tests/electric.test.ts +++ b/packages/db-collections/tests/electric.test.ts @@ -1,7 +1,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest" -import { Collection, createTransaction } from "@tanstack/db" +import { createCollection, createTransaction } from "@tanstack/db" import { electricCollectionOptions } from "../src/electric" +import type { ElectricCollectionUtils } from "../src/electric" import type { + Collection, MutationFnParams, PendingMutation, Transaction, @@ -23,8 +25,7 @@ vi.mock(`@electric-sql/client`, async () => { }) describe(`Electric Integration`, () => { - let collection: Collection - let awaitTxId: (txId: string, timeout?: number) => Promise + let collection: Collection let subscriber: (messages: Array>) => void beforeEach(() => { @@ -48,9 +49,11 @@ describe(`Electric Integration`, () => { getId: (item: Row) => item.id, } - const { options, awaitTxId: txIdFn } = electricCollectionOptions(config) - collection = new Collection(options) - awaitTxId = txIdFn + // Get the options with utilities + const options = electricCollectionOptions(config) + + // Create collection with Electric configuration using the new utility exposure pattern + collection = createCollection(options) }) it(`should handle incoming insert messages and commit on up-to-date`, () => { @@ -210,7 +213,7 @@ describe(`Electric Integration`, () => { ]) // The txid should be tracked and awaitTxId should resolve immediately - await expect(awaitTxId(testTxid)).resolves.toBe(true) + await expect(collection.utils.awaitTxId(testTxid)).resolves.toBe(true) }) it(`should track multiple txids`, async () => { @@ -233,8 +236,8 @@ describe(`Electric Integration`, () => { ]) // Both txids should be tracked - await expect(awaitTxId(txid1)).resolves.not.toThrow() - await expect(awaitTxId(txid2)).resolves.not.toThrow() + await expect(collection.utils.awaitTxId(txid1)).resolves.not.toThrow() + await expect(collection.utils.awaitTxId(txid2)).resolves.not.toThrow() }) it(`should reject with timeout when waiting for unknown txid`, async () => { @@ -243,7 +246,7 @@ describe(`Electric Integration`, () => { const shortTimeout = 100 // Attempt to await a txid that hasn't been seen with a short timeout - const promise = awaitTxId(unknownTxid, shortTimeout) + const promise = collection.utils.awaitTxId(unknownTxid, shortTimeout) // The promise should reject with a timeout error await expect(promise).rejects.toThrow( @@ -255,7 +258,7 @@ describe(`Electric Integration`, () => { const laterTxid = `1000` // Start waiting for a txid that hasn't arrived yet - const promise = awaitTxId(laterTxid, 1000) + const promise = collection.utils.awaitTxId(laterTxid, 1000) // Send the txid after a short delay setTimeout(() => { @@ -345,7 +348,7 @@ describe(`Electric Integration`, () => { } // Start waiting for the txid - const promise = awaitTxId(txid, 1000) + const promise = collection.utils.awaitTxId(txid, 1000) // Simulate the server sending sync messages after a delay setTimeout(() => { @@ -402,7 +405,7 @@ describe(`Electric Integration`, () => { onDelete, } - const { options } = electricCollectionOptions(config) + const options = electricCollectionOptions(config) // Verify that the handlers were passed to the collection options expect(options.onInsert).toBeDefined() @@ -430,7 +433,7 @@ describe(`Electric Integration`, () => { onInsert, } - const { options } = electricCollectionOptions(config) + const options = electricCollectionOptions(config) // Call the wrapped handler and expect it to throw await expect(options.onInsert!(mockParams)).rejects.toThrow( @@ -514,8 +517,7 @@ describe(`Electric Integration`, () => { onInsert, } - const { options } = electricCollectionOptions(config) - const testCollection = new Collection(options) + const testCollection = createCollection(electricCollectionOptions(config)) // Insert data using the transaction const tx = testCollection.insert({ diff --git a/packages/db-collections/tests/query.test.ts b/packages/db-collections/tests/query.test.ts index 64db5f2fca..a3e490b43a 100644 --- a/packages/db-collections/tests/query.test.ts +++ b/packages/db-collections/tests/query.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { QueryClient } from "@tanstack/query-core" -import { Collection } from "@tanstack/db" +import { createCollection } from "@tanstack/db" import { queryCollectionOptions } from "../src/query" import type { MutationFnParams, Transaction } from "@tanstack/db" import type { QueryCollectionConfig } from "../src/query" @@ -54,8 +54,8 @@ describe(`QueryCollection`, () => { getId, } - const { options } = queryCollectionOptions(config) - const collection = new Collection(options) + const options = queryCollectionOptions(config) + const collection = createCollection(options) // Wait for the query to complete and collection to update await vi.waitFor( @@ -114,8 +114,8 @@ describe(`QueryCollection`, () => { getId, } - const { options, refetch } = queryCollectionOptions(config) - const collection = new Collection(options) + const options = queryCollectionOptions(config) + const collection = createCollection(options) // Wait for initial data to load await vi.waitFor(() => { @@ -145,7 +145,7 @@ describe(`QueryCollection`, () => { ] // Refetch the query. - await refetch() + await collection.utils.refetch() expect(queryFn).toHaveBeenCalledTimes(2) // Check for update, addition, and removal @@ -164,7 +164,7 @@ describe(`QueryCollection`, () => { currentItems = [...currentItems, item4] // Refetch the query to trigger a refetch. - await refetch() + await collection.utils.refetch() // Verify expected. expect(queryFn).toHaveBeenCalledTimes(3) @@ -187,7 +187,7 @@ describe(`QueryCollection`, () => { .mockResolvedValueOnce([initialItem]) .mockRejectedValueOnce(testError) - const { options, refetch } = queryCollectionOptions({ + const options = queryCollectionOptions({ id: `test`, queryClient, queryKey, @@ -195,7 +195,7 @@ describe(`QueryCollection`, () => { getId, retry: 0, // Disable retries for this test case }) - const collection = new Collection(options) + const collection = createCollection(options) // Wait for initial data to load await vi.waitFor(() => { @@ -207,7 +207,7 @@ describe(`QueryCollection`, () => { }) // Trigger an error by refetching - await refetch() + await collection.utils.refetch() // Wait for the error to be logged expect(queryFn).toHaveBeenCalledTimes(2) @@ -237,14 +237,14 @@ describe(`QueryCollection`, () => { // Mock queryFn to return invalid data (not an array of objects) const queryFn = vi.fn().mockResolvedValue(`not an array` as any) - const { options } = queryCollectionOptions({ + const options = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId, }) - const collection = new Collection(options) + const collection = createCollection(options) // Wait for the query to execute await vi.waitFor(() => { @@ -285,14 +285,14 @@ describe(`QueryCollection`, () => { // Spy on console.log to detect when commits happen const consoleSpy = vi.spyOn(console, `log`) - const { options, refetch } = queryCollectionOptions({ + const options = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId, }) - const collection = new Collection(options) + const collection = createCollection(options) // Wait for initial data to load await vi.waitFor(() => { @@ -308,7 +308,7 @@ describe(`QueryCollection`, () => { consoleSpy.mockClear() // Trigger first refetch - should not cause an update due to shallow equality - await refetch() + await collection.utils.refetch() expect(queryFn).toHaveBeenCalledTimes(2) // Verify refetch was logged @@ -331,7 +331,7 @@ describe(`QueryCollection`, () => { consoleSpy.mockClear() // Trigger second refetch - should cause an update due to actual data change - await refetch() + await collection.utils.refetch() expect(queryFn).toHaveBeenCalledTimes(3) // Verify refetch was logged @@ -367,14 +367,14 @@ describe(`QueryCollection`, () => { // Create a spy for the getId function const getIdSpy = vi.fn((item: any) => item.customId) - const { options, refetch } = queryCollectionOptions({ + const options = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId: getIdSpy, }) - const collection = new Collection(options) + const collection = createCollection(options) // Wait for initial data to load await vi.waitFor(() => { @@ -410,7 +410,7 @@ describe(`QueryCollection`, () => { queryFn.mockResolvedValueOnce(updatedItems) // Trigger a refetch - await refetch() + await collection.utils.refetch() expect(queryFn).toHaveBeenCalledTimes(2) expect(collection.state.size).toBe(updatedItems.length) @@ -435,7 +435,7 @@ describe(`QueryCollection`, () => { }) describe(`Direct persistence handlers`, () => { - it(`should pass through direct persistence handlers to collection options`, async () => { + it(`should pass through direct persistence handlers to collection options`, () => { const queryKey = [`directPersistenceTest`] const items = [{ id: `1`, name: `Item 1` }] const queryFn = vi.fn().mockResolvedValue(items) @@ -456,7 +456,7 @@ describe(`QueryCollection`, () => { onDelete, } - const { options } = queryCollectionOptions(config) + const options = queryCollectionOptions(config) // Verify that the handlers were passed to the collection options expect(options.onInsert).toBeDefined() @@ -489,7 +489,7 @@ describe(`QueryCollection`, () => { onDelete, } - const { options } = queryCollectionOptions(config) + const options = queryCollectionOptions(config) // Call the wrapped handlers await options.onInsert!(mockParams) @@ -533,11 +533,11 @@ describe(`QueryCollection`, () => { onInsert: onInsertFalse, } - // Mock the queryClient.refetchQueries method which is called by refetch() + // Mock the queryClient.refetchQueries method which is called by collection.utils.refetch() vi.spyOn(queryClient, `refetchQueries`).mockImplementation(refetchSpy) // Test case 1: Default behavior (undefined return) should trigger refetch - const { options: optionsDefault } = queryCollectionOptions(configDefault) + const optionsDefault = queryCollectionOptions(configDefault) await optionsDefault.onInsert!(mockParams) // Verify handler was called and refetch was triggered @@ -548,7 +548,7 @@ describe(`QueryCollection`, () => { refetchSpy.mockClear() // Test case 2: Explicit { refetch: false } should not trigger refetch - const { options: optionsFalse } = queryCollectionOptions(configFalse) + const optionsFalse = queryCollectionOptions(configFalse) await optionsFalse.onInsert!(mockParams) // Verify handler was called but refetch was NOT triggered diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index 3179a2170f..252294dffa 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -5,22 +5,26 @@ import { SortedMap } from "./SortedMap" import type { ChangeMessage, CollectionConfig, + Fn, InsertConfig, OperationConfig, OptimisticChangeMessage, PendingMutation, StandardSchema, Transaction as TransactionType, + UtilsRecord, } from "./types" // Store collections in memory using Tanstack store -export const collectionsStore = new Store(new Map>()) +export const collectionsStore = new Store( + new Map>() +) // Map to track loading collections const loadingCollections = new Map< string, - Promise>> + Promise>> >() interface PendingSyncedTransaction> { @@ -28,17 +32,38 @@ interface PendingSyncedTransaction> { operations: Array> } +/** + * Enhanced Collection type that includes both data type T and utilities U + * @template T - The type of items in the collection + * @template TUtils - The utilities record type + */ +export type Collection< + T extends object = Record, + TUtils extends UtilsRecord = {}, +> = CollectionImpl & { readonly utils: TUtils } + /** * Creates a new Collection instance with the given configuration * * @template T - The type of items in the collection - * @param config - Configuration for the collection, including id and sync - * @returns A new Collection instance + * @template TUtils - The utilities record type + * @param options - Collection options with optional utilities + * @returns A new Collection with utilities exposed both at top level and under .utils */ -export function createCollection>( - config: CollectionConfig -): Collection { - return new Collection(config) +export function createCollection< + T extends object = Record, + TUtils extends UtilsRecord = {}, +>(options: CollectionConfig & { utils?: TUtils }): Collection { + const collection = new CollectionImpl(options) + + // Copy utils to both top level and .utils namespace + if (options.utils) { + collection.utils = { ...options.utils } + } else { + collection.utils = {} as TUtils + } + + return collection as Collection } /** @@ -69,7 +94,7 @@ export function createCollection>( */ export function preloadCollection>( config: CollectionConfig -): Promise> { +): Promise> { if (!config.id) { throw new Error(`The id property is required for preloadCollection`) } @@ -86,7 +111,7 @@ export function preloadCollection>( // If the collection is in the process of loading, return its promise if (loadingCollections.has(config.id)) { - return loadingCollections.get(config.id)! as Promise> + return loadingCollections.get(config.id)! as Promise> } // Create a new collection instance if it doesn't exist @@ -98,7 +123,7 @@ export function preloadCollection>( } next.set( config.id, - new Collection({ + createCollection({ id: config.id, getId: config.getId, sync: config.sync, @@ -113,9 +138,9 @@ export function preloadCollection>( // Create a promise that will resolve after the first commit let resolveFirstCommit: () => void - const firstCommitPromise = new Promise>((resolve) => { + const firstCommitPromise = new Promise>((resolve) => { resolveFirstCommit = () => { - resolve(collection) + resolve(collection as CollectionImpl) } }) @@ -133,7 +158,7 @@ export function preloadCollection>( // Store the loading promise loadingCollections.set( config.id, - firstCommitPromise as Promise>> + firstCommitPromise as Promise>> ) return firstCommitPromise @@ -168,7 +193,12 @@ export class SchemaValidationError extends Error { } } -export class Collection> { +export class CollectionImpl> { + /** + * Utilities namespace + * This is populated by createCollection + */ + public utils: Record = {} public transactions: Store> public optimisticOperations: Derived>> public derivedState: Derived> diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 31e3362df5..67efce2fcb 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -9,4 +9,4 @@ export * from "./proxy" export * from "./query/index.js" // Re-export some stuff explicitly to ensure the type & value is exported -export { Collection } from "./collection" +export type { Collection } from "./collection" diff --git a/packages/db/src/query/compiled-query.ts b/packages/db/src/query/compiled-query.ts index 691986b8c5..e3216f67d0 100644 --- a/packages/db/src/query/compiled-query.ts +++ b/packages/db/src/query/compiled-query.ts @@ -1,7 +1,8 @@ import { D2, MessageType, MultiSet, output } from "@electric-sql/d2ts" import { Effect, batch } from "@tanstack/store" -import { Collection } from "../collection.js" +import { createCollection } from "../collection.js" import { compileQueryPipeline } from "./pipeline-compiler.js" +import type { Collection } from "../collection.js" import type { ChangeMessage, SyncConfig } from "../types.js" import type { IStreamBuilder, @@ -97,9 +98,9 @@ export class CompiledQuery> { this.graph = graph this.inputs = inputs - this.resultCollection = new Collection({ + this.resultCollection = createCollection({ id: crypto.randomUUID(), // TODO: remove when we don't require any more - getId: (val) => { + getId: (val: unknown) => { return (val as any)._key }, sync: { diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index b86415e9c9..6cc5a188f2 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -5,6 +5,16 @@ import type { Transaction } from "./transactions" export type TransactionState = `pending` | `persisting` | `completed` | `failed` +/** + * Represents a utility function that can be attached to a collection + */ +export type Fn = (...args: Array) => any + +/** + * A record of utility functions that can be attached to a collection + */ +export type UtilsRecord = Record + /** * Represents a pending mutation within a transaction * Contains information about the original and modified data, as well as metadata diff --git a/packages/db/tests/collection-getters.test.ts b/packages/db/tests/collection-getters.test.ts index 94ed1677df..2bc93523d2 100644 --- a/packages/db/tests/collection-getters.test.ts +++ b/packages/db/tests/collection-getters.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest" -import { Collection } from "../src/collection" +import { createCollection } from "../src/collection" +import type { Collection } from "../src/collection" import type { ChangeMessage, CollectionConfig } from "../src/types" describe(`Collection getters`, () => { @@ -42,7 +43,7 @@ describe(`Collection getters`, () => { sync: mockSync, } - collection = new Collection(config) + collection = createCollection(config) }) describe(`state getter`, () => { @@ -86,7 +87,7 @@ describe(`Collection getters`, () => { }), } - const delayedCollection = new Collection({ + const delayedCollection = createCollection({ id: `delayed-collection`, getId: (val) => val.id, sync: delayedSyncMock, @@ -146,7 +147,7 @@ describe(`Collection getters`, () => { }), } - const delayedCollection = new Collection({ + const delayedCollection = createCollection({ id: `delayed-collection`, getId: (val) => val.id, sync: delayedSyncMock, diff --git a/packages/db/tests/collection-subscribe-changes.test.ts b/packages/db/tests/collection-subscribe-changes.test.ts index e15d68b880..6e5ae75cb5 100644 --- a/packages/db/tests/collection-subscribe-changes.test.ts +++ b/packages/db/tests/collection-subscribe-changes.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest" import mitt from "mitt" -import { Collection } from "../src/collection" +import { createCollection } from "../src/collection" import { createTransaction } from "../src/transactions" import type { ChangeMessage, @@ -18,7 +18,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection with pre-populated data - const collection = new Collection<{ value: string }>({ + const collection = createCollection<{ value: string }>({ id: `initial-state-test`, getId: (item) => item.value, sync: { @@ -67,7 +67,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection with sync capability using the mitt pattern from collection.test.ts - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `sync-changes-test-with-mitt`, getId: (item) => item.id, sync: { @@ -181,7 +181,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection with mutation capability - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string updated?: boolean @@ -312,7 +312,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection with both sync and mutation capabilities - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `mixed-changes-test`, getId: (item) => item.id, sync: { @@ -470,7 +470,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection with initial data - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `diff-changes-test`, getId: (item) => item.id, sync: { @@ -586,7 +586,7 @@ describe(`Collection.subscribeChanges`, () => { const callback = vi.fn() // Create collection - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `unsubscribe-test`, getId: (item) => item.id, sync: { diff --git a/packages/db/tests/collection.test.ts b/packages/db/tests/collection.test.ts index 71abaeff0a..52ead3c9c3 100644 --- a/packages/db/tests/collection.test.ts +++ b/packages/db/tests/collection.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest" import mitt from "mitt" import { z } from "zod" -import { Collection, SchemaValidationError } from "../src/collection" +import { SchemaValidationError, createCollection } from "../src/collection" import { createTransaction } from "../src/transactions" import type { ChangeMessage, @@ -12,12 +12,12 @@ import type { describe(`Collection`, () => { it(`should throw if there's no sync config`, () => { - expect(() => new Collection()).toThrow(`Collection requires a config`) + expect(() => createCollection()).toThrow(`Collection requires a config`) }) it(`should throw an error when trying to use mutation operations outside of a transaction`, async () => { // Create a collection with sync but no mutationFn - const collection = new Collection<{ value: string }>({ + const collection = createCollection<{ value: string }>({ id: `foo`, getId: (item) => item.value, sync: { @@ -66,7 +66,7 @@ describe(`Collection`, () => { }) it(`should throw an error when trying to update an item's ID`, async () => { - const collection = new Collection<{ id: string; value: string }>({ + const collection = createCollection<{ id: string; value: string }>({ id: `id-update-test`, getId: (item) => item.id, sync: { @@ -103,7 +103,7 @@ describe(`Collection`, () => { it(`It shouldn't expose any state until the initial sync is finished`, () => { // Create a collection with a mock sync plugin - new Collection<{ name: string }>({ + createCollection<{ name: string }>({ id: `foo`, getId: (item) => item.name, sync: { @@ -146,7 +146,7 @@ describe(`Collection`, () => { const syncMock = vi.fn() // new collection w/ mock sync/mutation - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string boolean?: boolean @@ -427,7 +427,7 @@ describe(`Collection`, () => { const emitter = mitt() // new collection w/ mock sync/mutation - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `mock`, getId: (item) => { return item.id @@ -508,7 +508,7 @@ describe(`Collection`, () => { }) it(`should throw errors when deleting items not in the collection`, () => { - const collection = new Collection<{ name: string }>({ + const collection = createCollection<{ name: string }>({ id: `delete-errors`, getId: (val) => val.name, sync: { @@ -549,7 +549,7 @@ describe(`Collection`, () => { }) it(`should not allow inserting documents with IDs that already exist`, async () => { - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `duplicate-id-test`, getId: (item) => item.id, sync: { @@ -590,7 +590,7 @@ describe(`Collection`, () => { const onDeleteMock = vi.fn() // Create a collection with handler functions - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `handlers-test`, getId: (item) => item.id, sync: { @@ -654,7 +654,7 @@ describe(`Collection`, () => { }) // Create a collection with handler functions - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `direct-operations-test`, getId: (item) => item.id, sync: { @@ -707,7 +707,7 @@ describe(`Collection`, () => { it(`should throw errors when operations are called outside transactions without handlers`, async () => { // Create a collection without handler functions - const collection = new Collection<{ id: number; value: string }>({ + const collection = createCollection<{ id: number; value: string }>({ id: `no-handlers-test`, getId: (item) => item.id, sync: { @@ -760,7 +760,7 @@ describe(`Collection with schema validation`, () => { }) // Create a collection with the schema - const collection = new Collection>({ + const collection = createCollection>({ id: `test`, getId: (item) => item.name, sync: { diff --git a/packages/db/tests/query/query-collection.test.ts b/packages/db/tests/query/query-collection.test.ts index 30a4cc50b3..2a8ece3016 100644 --- a/packages/db/tests/query/query-collection.test.ts +++ b/packages/db/tests/query/query-collection.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest" import mitt from "mitt" -import { Collection } from "../../src/collection.js" +import { createCollection } from "../../src/collection.js" import { queryBuilder } from "../../src/query/query-builder.js" import { compileQuery } from "../../src/query/compiled-query.js" import { createTransaction } from "../../src/transactions.js" @@ -71,7 +71,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -187,7 +187,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -314,7 +314,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test`, getId: (item) => item.id, sync: { @@ -334,7 +334,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test`, getId: (item) => item.id, sync: { @@ -475,7 +475,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test`, getId: (item) => item.id, sync: { @@ -495,7 +495,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test`, getId: (item) => item.id, sync: { @@ -685,7 +685,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `order-by-test`, getId: (item) => item.id, sync: { @@ -802,7 +802,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `order-update-test`, getId: (val) => val.id, sync: { @@ -919,7 +919,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test-bug`, getId: (val) => val.id, sync: { @@ -940,7 +940,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test-bug`, getId: (val) => val.id, sync: { @@ -1054,7 +1054,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `select-callback-test`, getId: (item) => item.id, sync: { @@ -1085,16 +1085,12 @@ describe(`Query Collections`, () => { const query = queryBuilder() .from({ collection }) - .select(({ collection }) => ({ - displayName: `${collection.name} (Age: ${collection.age})`, - status: collection.isActive ? `Active` : `Inactive`, + .select(({ collection: result }) => ({ + displayName: `${result.name} (Age: ${result.age})`, + status: result.isActive ? `Active` : `Inactive`, ageGroup: - collection.age < 30 - ? `Young` - : collection.age < 40 - ? `Middle` - : `Senior`, - emailDomain: collection.email.split(`@`)[1], + result.age < 30 ? `Young` : result.age < 40 ? `Middle` : `Senior`, + emailDomain: result.email.split(`@`)[1], })) const compiledQuery = compileQuery(query) diff --git a/packages/db/tests/transactions.test.ts b/packages/db/tests/transactions.test.ts index 4c2580458c..7c07d79fa1 100644 --- a/packages/db/tests/transactions.test.ts +++ b/packages/db/tests/transactions.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest" import { createTransaction } from "../src/transactions" -import { Collection } from "../src/collection" +import { Collection, createCollection } from "../src/collection" describe(`Transactions`, () => { it(`calling createTransaction creates a transaction`, () => { @@ -48,7 +48,7 @@ describe(`Transactions`, () => { mutationFn: async () => Promise.resolve(), autoCommit: false, }) - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string newProp?: string @@ -84,7 +84,7 @@ describe(`Transactions`, () => { mutationFn: async () => Promise.resolve(), autoCommit: false, }) - const collection1 = new Collection<{ + const collection1 = createCollection<{ id: number value: string newProp?: string @@ -95,7 +95,7 @@ describe(`Transactions`, () => { sync: () => {}, }, }) - const collection2 = new Collection<{ + const collection2 = createCollection<{ id: number value: string newProp?: string @@ -129,7 +129,7 @@ describe(`Transactions`, () => { mutationFn: async () => Promise.resolve(), autoCommit: false, }) - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string newProp?: string @@ -162,7 +162,7 @@ describe(`Transactions`, () => { }, autoCommit: false, }) - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string newProp?: string @@ -198,7 +198,7 @@ describe(`Transactions`, () => { }, autoCommit: false, }) - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string newProp?: string @@ -239,7 +239,7 @@ describe(`Transactions`, () => { mutationFn: async () => Promise.resolve(), autoCommit: false, }) - const collection = new Collection<{ + const collection = createCollection<{ id: number value: string newProp?: string diff --git a/packages/db/tests/utility-exposure.test.ts b/packages/db/tests/utility-exposure.test.ts new file mode 100644 index 0000000000..e46a007013 --- /dev/null +++ b/packages/db/tests/utility-exposure.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, test } from "vitest" +import { createCollection } from "../src/collection" +import type { CollectionConfig, SyncConfig, UtilsRecord } from "../src/types" + +// Mock utility functions for testing +interface TestUtils extends UtilsRecord { + testFn: (input: string) => string + asyncFn: (input: number) => Promise +} + +describe(`Utility exposure pattern`, () => { + test(`exposes utilities at top level and under .utils namespace`, () => { + // Create mock utility functions + const testFn = (input: string) => `processed: ${input}` + const asyncFn = (input: number) => input * 2 + + // Create a mock sync config + const mockSync: SyncConfig = { + sync: () => { + return { + unsubscribe: () => {}, + } + }, + } + + // Create collection options with utilities + const options: CollectionConfig<{ id: string }> & { utils: TestUtils } = { + getId: (item) => item.id, + sync: mockSync, + utils: { + testFn, + asyncFn, + }, + } + + // Create collection with utilities + const collection = createCollection(options) + + // Verify utilities are exposed at top level + expect(collection.testFn).toBeDefined() + expect(collection.testFn(`test`)).toBe(`processed: test`) + expect(collection.asyncFn).toBeDefined() + + // Verify utilities are also exposed under .utils namespace + expect(collection.utils).toBeDefined() + expect(collection.utils.testFn).toBeDefined() + expect(collection.utils.testFn(`test`)).toBe(`processed: test`) + expect(collection.utils.asyncFn).toBeDefined() + + // Verify both references point to the same function + expect(collection.testFn).toBe(collection.utils.testFn) + expect(collection.asyncFn).toBe(collection.utils.asyncFn) + }) + + test(`supports collections without utilities`, () => { + // Create a mock sync config + const mockSync: SyncConfig = { + sync: () => { + return { + unsubscribe: () => {}, + } + }, + } + + // Create collection without utilities + const collection = createCollection({ + getId: (item: { id: string }) => item.id, + sync: mockSync, + }) + + // Verify .utils exists but is empty + expect(collection.utils).toBeDefined() + expect(Object.keys(collection.utils).length).toBe(0) + }) + + test(`preserves type information for collection data`, async () => { + // Define a type for our collection items + type TestItem = { + id: string + name: string + value: number + } + + // Create mock utility functions + const testFn = (input: string) => `processed: ${input}` + const asyncFn = (input: number) => input * 2 + + // Create a mock sync config + const mockSync: SyncConfig = { + sync: () => { + return { + unsubscribe: () => {}, + } + }, + } + + // Create collection options with utilities + const options: CollectionConfig & { utils: TestUtils } = { + getId: (item) => item.id, + sync: mockSync, + utils: { + testFn, + asyncFn, + }, + } + + // Create collection with utilities + const collection = createCollection(options) + + // Create an item for the collection + const testItem: TestItem = { id: `1`, name: `Test`, value: 42 } + + // Let's verify utilities work with the collection + expect(collection.testFn(`test`)).toBe(`processed: test`) + const asyncResult = await collection.asyncFn(21) + expect(asyncResult).toBe(42) + + // TypeScript knows the collection is for TestItem type + // This is a compile-time check that we can't verify at runtime directly + // But we've verified the utilities work + }) +}) diff --git a/packages/react-db/src/index.ts b/packages/react-db/src/index.ts index e5e496ce07..991790fea0 100644 --- a/packages/react-db/src/index.ts +++ b/packages/react-db/src/index.ts @@ -6,5 +6,5 @@ export * from "./useLiveQuery" export * from "@tanstack/db" // Re-export some stuff explicitly to ensure the type & value is exported -export { Collection } from "@tanstack/db" +export type { Collection } from "@tanstack/db" export { createTransaction } from "@tanstack/db" diff --git a/packages/react-db/tests/useLiveQuery.test.tsx b/packages/react-db/tests/useLiveQuery.test.tsx index 4773471aad..cc573717b4 100644 --- a/packages/react-db/tests/useLiveQuery.test.tsx +++ b/packages/react-db/tests/useLiveQuery.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest" import mitt from "mitt" import { act, renderHook } from "@testing-library/react" -import { Collection, createTransaction } from "@tanstack/db" +import { createCollection, createTransaction } from "@tanstack/db" import { useEffect } from "react" import { useLiveQuery } from "../src/useLiveQuery" import type { @@ -80,7 +80,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -252,7 +252,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test`, getId: (item) => item.id, sync: { @@ -272,7 +272,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test`, getId: (item) => item.id, sync: { @@ -435,7 +435,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `params-change-test`, getId: (item) => item.id, sync: { @@ -541,7 +541,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `stop-query-test`, getId: (item) => item.id, sync: { @@ -643,7 +643,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -772,7 +772,7 @@ describe(`Query Collections`, () => { }> = [] // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test-bug`, getId: (item) => item.id, sync: { @@ -793,7 +793,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test-bug`, getId: (item) => item.id, sync: { diff --git a/packages/vue-db/src/index.ts b/packages/vue-db/src/index.ts index e5e496ce07..991790fea0 100644 --- a/packages/vue-db/src/index.ts +++ b/packages/vue-db/src/index.ts @@ -6,5 +6,5 @@ export * from "./useLiveQuery" export * from "@tanstack/db" // Re-export some stuff explicitly to ensure the type & value is exported -export { Collection } from "@tanstack/db" +export type { Collection } from "@tanstack/db" export { createTransaction } from "@tanstack/db" diff --git a/packages/vue-db/tests/useLiveQuery.test.ts b/packages/vue-db/tests/useLiveQuery.test.ts index 49ff077ea5..9538ab8ef0 100644 --- a/packages/vue-db/tests/useLiveQuery.test.ts +++ b/packages/vue-db/tests/useLiveQuery.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest" import mitt from "mitt" -import { Collection, createTransaction } from "@tanstack/db" +import { createCollection, createTransaction } from "@tanstack/db" import { ref, watch, watchEffect } from "vue" import { useLiveQuery } from "../src/useLiveQuery" import type { Ref } from "vue" @@ -80,7 +80,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -239,7 +239,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test`, getId: (item) => item.id, sync: { @@ -259,7 +259,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test`, getId: (item) => item.id, sync: { @@ -397,7 +397,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `params-change-test`, getId: (item) => item.id, sync: { @@ -484,7 +484,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `stop-query-test`, getId: (item) => item.id, sync: { @@ -579,7 +579,7 @@ describe(`Query Collections`, () => { const emitter = mitt() // Create collection with mutation capability - const collection = new Collection({ + const collection = createCollection({ id: `optimistic-changes-test`, getId: (item) => item.id, sync: { @@ -701,7 +701,7 @@ describe(`Query Collections`, () => { }> = [] // Create person collection - const personCollection = new Collection({ + const personCollection = createCollection({ id: `person-collection-test-bug`, getId: (item) => item.id, sync: { @@ -722,7 +722,7 @@ describe(`Query Collections`, () => { }) // Create issue collection - const issueCollection = new Collection({ + const issueCollection = createCollection({ id: `issue-collection-test-bug`, getId: (item) => item.id, sync: { From b077ad5020bc5550d3818cf8baae9cc1d1b706bd Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 11 Jun 2025 11:12:30 -0600 Subject: [PATCH 2/3] Fix --- packages/db/tests/utility-exposure.test.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/packages/db/tests/utility-exposure.test.ts b/packages/db/tests/utility-exposure.test.ts index e46a007013..0aa55c7a69 100644 --- a/packages/db/tests/utility-exposure.test.ts +++ b/packages/db/tests/utility-exposure.test.ts @@ -36,20 +36,11 @@ describe(`Utility exposure pattern`, () => { // Create collection with utilities const collection = createCollection(options) - // Verify utilities are exposed at top level - expect(collection.testFn).toBeDefined() - expect(collection.testFn(`test`)).toBe(`processed: test`) - expect(collection.asyncFn).toBeDefined() - // Verify utilities are also exposed under .utils namespace expect(collection.utils).toBeDefined() expect(collection.utils.testFn).toBeDefined() expect(collection.utils.testFn(`test`)).toBe(`processed: test`) expect(collection.utils.asyncFn).toBeDefined() - - // Verify both references point to the same function - expect(collection.testFn).toBe(collection.utils.testFn) - expect(collection.asyncFn).toBe(collection.utils.asyncFn) }) test(`supports collections without utilities`, () => { @@ -111,8 +102,8 @@ describe(`Utility exposure pattern`, () => { const testItem: TestItem = { id: `1`, name: `Test`, value: 42 } // Let's verify utilities work with the collection - expect(collection.testFn(`test`)).toBe(`processed: test`) - const asyncResult = await collection.asyncFn(21) + expect(collection.utils.testFn(`test`)).toBe(`processed: test`) + const asyncResult = await collection.utils.asyncFn(21) expect(asyncResult).toBe(42) // TypeScript knows the collection is for TestItem type From e2d1433b260da59f26a8b352e92ad77a6924c0f4 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Wed, 11 Jun 2025 12:01:49 -0600 Subject: [PATCH 3/3] Use interface and not an intersection --- packages/db/src/collection.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index 252294dffa..9d1f124a32 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -33,14 +33,16 @@ interface PendingSyncedTransaction> { } /** - * Enhanced Collection type that includes both data type T and utilities U + * Enhanced Collection interface that includes both data type T and utilities TUtils * @template T - The type of items in the collection * @template TUtils - The utilities record type */ -export type Collection< +export interface Collection< T extends object = Record, TUtils extends UtilsRecord = {}, -> = CollectionImpl & { readonly utils: TUtils } +> extends CollectionImpl { + readonly utils: TUtils +} /** * Creates a new Collection instance with the given configuration