@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 28.6 kB
Source Map (JSON)
{"version":3,"file":"mutations.cjs","names":["safeRandomUUID","MissingInsertHandlerError","DuplicateKeyError","MissingDeleteHandlerError","NoKeysPassedToDeleteError","DeleteKeyNotFoundError","getActiveTransaction","createTransaction","InvalidSchemaError","SchemaMustBeSynchronousError","SchemaValidationError","normalizeError","MissingUpdateArgumentError","MissingUpdateHandlerError","NoKeysPassedToUpdateError","UpdateKeyNotFoundError","withFlatChangeTracking","withArrayChangeTracking","withChangeTracking","KeyUpdateNotAllowedError","config","applyOwnedMutations","commitDirect","transactionScope","ensureStandardSchema","result","commitLocalOnlyDirect","transaction"],"sources":["../../../src/collection/mutations.ts"],"sourcesContent":["import {\n withArrayChangeTracking,\n withChangeTracking,\n withFlatChangeTracking,\n} from '../proxy'\nimport { assertCollectionKey } from '../utils'\nimport { normalizeError } from '../utils/error.js'\nimport { safeRandomUUID } from '../utils/uuid'\nimport { createTransaction, getActiveTransaction } from '../transactions'\nimport {\n DeleteKeyNotFoundError,\n DuplicateKeyError,\n InvalidSchemaError,\n KeyUpdateNotAllowedError,\n MissingDeleteHandlerError,\n MissingInsertHandlerError,\n MissingUpdateArgumentError,\n MissingUpdateHandlerError,\n NoKeysPassedToDeleteError,\n NoKeysPassedToUpdateError,\n SchemaMustBeSynchronousError,\n SchemaValidationError,\n UpdateKeyNotFoundError,\n} from '../errors'\nimport type { Collection, CollectionImpl } from './index.js'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type {\n CollectionConfig,\n InsertConfig,\n OperationConfig,\n OperationType,\n PendingMutation,\n StandardSchema,\n TransactionConfig,\n Transaction as TransactionType,\n TransactionWithMutations,\n UtilsRecord,\n WritableDeep,\n} from '../types'\nimport type { TransactionScope } from '../transactions'\nimport type { CollectionLifecycleManager } from './lifecycle'\nimport type { CollectionStateManager } from './state'\n\n// One random prefix per runtime keeps mutation ids unique across tabs and\n// sessions; the counter avoids generating a random UUID per mutation. The\n// prefix waits for the first mutation, because some runtimes reject random\n// values at module scope.\nlet mutationIdPrefix: string | undefined\nlet mutationCount = 0\nfunction createMutationId(): string {\n mutationIdPrefix ??= safeRandomUUID()\n return `${mutationIdPrefix}-${++mutationCount}`\n}\n\nexport class CollectionMutationsManager<\n TOutput extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n TUtils extends UtilsRecord = {},\n TSchema extends StandardSchemaV1 = StandardSchemaV1,\n TInput extends object = TOutput,\n> {\n private lifecycle!: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n private collection!: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n private config!: CollectionConfig<TOutput, TKey, TSchema, TUtils>\n private transactionScope?: TransactionScope\n private id: string\n\n constructor(\n config: CollectionConfig<TOutput, TKey, TSchema, TUtils>,\n id: string,\n ) {\n this.id = id\n this.config = config\n }\n\n setDeps(deps: {\n lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n state: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n collection: CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n }) {\n this.lifecycle = deps.lifecycle\n this.state = deps.state\n this.collection = deps.collection\n }\n\n setTransactionScope(transactionScope: TransactionScope): void {\n this.transactionScope = transactionScope\n }\n\n private getActiveTransaction() {\n return this.transactionScope\n ? this.transactionScope.getActiveTransactionForCollection()\n : getActiveTransaction()\n }\n\n private createTransaction<T extends object>(config: TransactionConfig<T>) {\n return this.transactionScope\n ? this.transactionScope.createTransaction(config)\n : createTransaction(config)\n }\n\n private ensureStandardSchema(schema: unknown): StandardSchema<TOutput> {\n // If the schema already implements the standard-schema interface, return it\n if (schema && `~standard` in (schema as {})) {\n return schema as StandardSchema<TOutput>\n }\n\n throw new InvalidSchemaError()\n }\n\n public validateData(\n data: unknown,\n type: `insert` | `update`,\n key?: TKey,\n ): TOutput | never {\n if (!this.config.schema) return data as TOutput\n\n const standardSchema = this.ensureStandardSchema(this.config.schema)\n\n // For updates, we need to merge with the existing data before validation\n if (type === `update` && key) {\n // Get the existing data for this key\n const existingData = this.state.get(key)\n\n if (\n existingData &&\n data &&\n typeof data === `object` &&\n typeof existingData === `object`\n ) {\n // Merge the update with the existing data\n const mergedData = { ...existingData, ...data }\n\n // Validate the merged data\n const result = standardSchema[`~standard`].validate(mergedData)\n\n // Ensure validation is synchronous\n if (result instanceof Promise) {\n throw new SchemaMustBeSynchronousError()\n }\n\n // If validation fails, throw a SchemaValidationError with the issues\n if (`issues` in result && result.issues) {\n const typedIssues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((p) => String(p)),\n }))\n throw new SchemaValidationError(type, typedIssues)\n }\n\n // Extract only the modified keys from the validated result\n const validatedMergedData = result.value as TOutput\n const modifiedKeys = Object.keys(data)\n const extractedChanges = Object.fromEntries(\n modifiedKeys.map((k) => [k, validatedMergedData[k as keyof TOutput]]),\n ) as TOutput\n\n return extractedChanges\n }\n }\n\n // For inserts or updates without existing data, validate the data directly\n const result = standardSchema[`~standard`].validate(data)\n\n // Ensure validation is synchronous\n if (result instanceof Promise) {\n throw new SchemaMustBeSynchronousError()\n }\n\n // If validation fails, throw a SchemaValidationError with the issues\n if (`issues` in result && result.issues) {\n const typedIssues = result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((p) => String(p)),\n }))\n throw new SchemaValidationError(type, typedIssues)\n }\n\n return result.value as TOutput\n }\n\n public generateGlobalKey(key: any, item: any): string {\n assertCollectionKey(key, item)\n return `KEY::${JSON.stringify([this.id, typeof key, String(key)])}`\n }\n\n /**\n * A local-only Collection confirms its own writes. Without a user handler\n * for this operation type, and with no other transaction unsettled, write\n * the mutations as synced rows and return a completed transaction instead\n * of publishing an optimistic overlay and confirming it a tick later.\n */\n private commitLocalOnlyDirect(\n mutations: Array<PendingMutation<TOutput>>,\n type: OperationType,\n ): TransactionType<TOutput> | undefined {\n const direct = this.state.localOnlyDirectWrite\n if (!direct?.types.has(type)) return undefined\n for (const transaction of this.state.transactions.values()) {\n // A persisting transaction holds sync commits, and a pending one\n // overlays them.\n if (\n transaction.state === `pending` ||\n transaction.state === `persisting`\n ) {\n return undefined\n }\n }\n const transaction = this.createTransaction<TOutput>({\n autoCommit: false,\n mutationFn: () => Promise.resolve(),\n })\n transaction.applyMutations(mutations)\n // The rows are stored when `write` publishes them, so a throwing\n // subscriber cannot undo the write; the transaction still completes.\n try {\n direct.write(mutations)\n } finally {\n transaction.completeWithoutCommit()\n }\n return transaction\n }\n\n /** Own a transaction's new mutations and show them optimistically. */\n private applyOwnedMutations(\n transaction: TransactionType<any>,\n mutations: Array<PendingMutation<TOutput>>,\n ): void {\n // The Collection owns the request before its handler can write through\n // sync, so a confirmation written by the handler waits for settlement.\n this.state.trackTransaction(transaction)\n transaction.applyMutations(mutations)\n this.state.recomputeOptimisticState(true)\n }\n\n /** Commit mutations in a new transaction that calls the operation's handler. */\n private commitDirect<TOperation extends OperationType>(\n type: TOperation,\n handler: (params: {\n transaction: TransactionWithMutations<\n TOutput,\n TOperation,\n Collection<TOutput, TKey, TUtils>\n >\n collection: Collection<TOutput, TKey, TUtils>\n }) => unknown,\n mutations: Array<PendingMutation<TOutput>>,\n ): TransactionType<TOutput> {\n const localOnly = this.commitLocalOnlyDirect(mutations, type)\n if (localOnly) return localOnly\n const transaction = this.createTransaction<TOutput>({\n mutationFn: async (params) =>\n await handler({\n transaction:\n params.transaction as unknown as TransactionWithMutations<\n TOutput,\n TOperation,\n Collection<TOutput, TKey, TUtils>\n >,\n collection: this.collection as unknown as Collection<\n TOutput,\n TKey,\n TUtils\n >,\n }),\n })\n try {\n this.applyOwnedMutations(transaction, mutations)\n } catch (error) {\n // A subscriber threw before the handler could run. Roll back only this\n // write, so no Collection keeps a transaction that nothing will settle.\n // The admission error is the reported cause.\n try {\n transaction.rollback({\n isSecondaryRollback: true,\n error: normalizeError(error),\n })\n } catch {\n // Settlement still ran every step.\n }\n throw error\n }\n // Errors still reject `when('settled')`. This catch only prevents an\n // unhandled rejection from the fire-and-forget commit.\n transaction.commit().catch(() => undefined)\n return transaction\n }\n\n /**\n * Inserts one or more items into the collection\n */\n insert = (data: TInput | Array<TInput>, config?: InsertConfig) => {\n this.lifecycle.validateCollectionUsable(`insert`)\n const state = this.state\n const ambientTransaction = this.getActiveTransaction()\n\n // If no ambient transaction exists, check for an onInsert handler early\n if (!ambientTransaction && !this.config.onInsert) {\n throw new MissingInsertHandlerError()\n }\n\n const items = Array.isArray(data) ? data : [data]\n // One timestamp per call; mutations replace these rather than mutate them.\n const now = new Date()\n const mutations: Array<PendingMutation<TOutput>> = []\n const keysInCurrentBatch = new Set<TKey>()\n\n // Create mutations for each item\n items.forEach((item) => {\n // Validate the data against the schema if one exists\n const validatedData = this.validateData(item, `insert`)\n\n // Reject duplicate keys within this batch before starting sync.\n const key = this.config.getKey(validatedData)\n if (keysInCurrentBatch.has(key)) {\n throw new DuplicateKeyError(key)\n }\n keysInCurrentBatch.add(key)\n const globalKey = this.generateGlobalKey(key, item)\n\n const mutation: PendingMutation<TOutput, `insert`> = {\n mutationId: createMutationId(),\n original: {},\n modified: validatedData,\n // Pick the values from validatedData based on what's passed in - this is for cases\n // where a schema has default values. The validated data has the extra default\n // values but for changes, we just want to show the data that was actually passed in.\n changes: Object.fromEntries(\n Object.keys(item).map((k) => [\n k,\n validatedData[k as keyof typeof validatedData],\n ]),\n ) as TInput,\n globalKey,\n key,\n metadata: config?.metadata as unknown,\n syncMetadata: this.config.sync.getSyncMetadata?.() || {},\n optimistic: config?.optimistic ?? true,\n type: `insert`,\n createdAt: now,\n updatedAt: now,\n collection: this.collection,\n }\n\n mutations.push(mutation)\n })\n\n // Reject duplicates already visible before explicitly starting sync; startup may\n // synchronously reveal additional keys, so check again afterward.\n let duplicate = mutations.find(({ key }) => state.has(key))\n if (duplicate) throw new DuplicateKeyError(duplicate.key)\n this.collection._sync.startSync()\n duplicate = mutations.find(({ key }) => state.has(key))\n if (duplicate) throw new DuplicateKeyError(duplicate.key)\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n this.applyOwnedMutations(ambientTransaction, mutations)\n return ambientTransaction\n }\n\n // Call each handler through the config so a method keeps its `this`.\n return this.commitDirect(\n `insert`,\n (params) => this.config.onInsert!(params),\n mutations,\n )\n }\n\n /**\n * Updates one or more items in the collection using a callback function\n */\n update(\n keys: TKey | Array<TKey>,\n configOrCallback:\n | ((draft: WritableDeep<TInput>) => void)\n | ((drafts: Array<WritableDeep<TInput>>) => void)\n | OperationConfig,\n maybeCallback?:\n | ((draft: WritableDeep<TInput>) => void)\n | ((drafts: Array<WritableDeep<TInput>>) => void),\n ) {\n if (typeof keys === `undefined`) {\n throw new MissingUpdateArgumentError()\n }\n\n const state = this.state\n this.lifecycle.validateCollectionUsable(`update`)\n\n const ambientTransaction = this.getActiveTransaction()\n\n // If no ambient transaction exists, check for an onUpdate handler early\n if (!ambientTransaction && !this.config.onUpdate) {\n throw new MissingUpdateHandlerError()\n }\n\n const isArray = Array.isArray(keys)\n const keysArray = isArray ? keys : [keys]\n\n if (isArray && keysArray.length === 0) {\n throw new NoKeysPassedToUpdateError()\n }\n\n const callback =\n typeof configOrCallback === `function` ? configOrCallback : maybeCallback\n if (typeof callback !== `function`) throw new TypeError()\n const config =\n typeof configOrCallback === `function` ? {} : configOrCallback\n\n this.collection._sync.startSync()\n\n // Get the current objects or empty objects if they don't exist\n const currentObjects = keysArray.map((key) => {\n const item = this.state.get(key)\n if (!item) {\n throw new UpdateKeyNotFoundError(key)\n }\n\n return item\n }) as unknown as Array<TInput>\n\n // Flat rows need no proxy; nested rows track changes through drafts.\n const changesArray =\n withFlatChangeTracking(\n currentObjects,\n callback as (drafts: Array<TInput> | TInput) => void,\n isArray,\n ) ??\n (isArray\n ? withArrayChangeTracking(\n currentObjects,\n callback as (draft: Array<TInput>) => void,\n )\n : [\n withChangeTracking(\n currentObjects[0]!,\n callback as (draft: TInput) => void,\n ),\n ])\n\n // Create mutations for each object that has changes\n // One timestamp per call; mutations replace these rather than mutate them.\n const now = new Date()\n const mutations: Array<\n PendingMutation<\n TOutput,\n `update`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n > = keysArray\n .map((key, index) => {\n const itemChanges = changesArray[index] // A fresh object the tracker recorded for this item\n\n // Skip items with no changes\n if (!itemChanges || Object.keys(itemChanges).length === 0) {\n return null\n }\n\n const originalItem = currentObjects[index] as unknown as TOutput\n // Validate the user-provided changes for this item\n const validatedUpdatePayload = this.validateData(\n itemChanges,\n `update`,\n key,\n )\n\n // Construct the full modified item by applying the validated update payload to the original item\n const modifiedItem = { ...originalItem, ...validatedUpdatePayload }\n\n // Check if the ID of the item is being changed\n const originalItemId = this.config.getKey(originalItem)\n const modifiedItemId = this.config.getKey(modifiedItem)\n\n if (originalItemId !== modifiedItemId) {\n throw new KeyUpdateNotAllowedError(originalItemId, modifiedItemId)\n }\n\n const globalKey = this.generateGlobalKey(modifiedItemId, modifiedItem)\n\n return {\n mutationId: createMutationId(),\n original: originalItem,\n modified: modifiedItem,\n // Pick the values from modifiedItem based on what's passed in - this is for cases\n // where a schema has default values or transforms. The modified data has the extra\n // default or transformed values but for changes, we just want to show the data that\n // was actually passed in.\n // Without a schema, validation returns the tracker's fresh change\n // object, which already holds exactly these values.\n changes: (validatedUpdatePayload === itemChanges\n ? itemChanges\n : Object.fromEntries(\n Object.keys(itemChanges).map((k) => [\n k,\n modifiedItem[k as keyof typeof modifiedItem],\n ]),\n )) as TInput,\n globalKey,\n key,\n metadata: config.metadata as unknown,\n syncMetadata: (state.syncedMetadata.get(key) || {}) as Record<\n string,\n unknown\n >,\n optimistic: config.optimistic ?? true,\n type: `update`,\n createdAt: now,\n updatedAt: now,\n collection: this.collection,\n }\n })\n .filter(Boolean) as Array<\n PendingMutation<\n TOutput,\n `update`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n >\n\n // If no changes were made, return an empty transaction early\n if (mutations.length === 0) {\n const emptyTransaction = this.createTransaction({\n mutationFn: async () => {},\n })\n // Errors still propagate through tx.when(`settled`); suppress the background commit from warning\n emptyTransaction.commit().catch(() => undefined)\n return emptyTransaction\n }\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n this.applyOwnedMutations(ambientTransaction, mutations)\n return ambientTransaction\n }\n\n return this.commitDirect(\n `update`,\n (params) => this.config.onUpdate!(params),\n mutations,\n )\n }\n\n /**\n * Deletes one or more items from the collection\n */\n delete = (\n keys: Array<TKey> | TKey,\n config?: OperationConfig,\n ): TransactionType<any> => {\n const state = this.state\n this.lifecycle.validateCollectionUsable(`delete`)\n\n const ambientTransaction = this.getActiveTransaction()\n\n // If no ambient transaction exists, check for an onDelete handler early\n if (!ambientTransaction && !this.config.onDelete) {\n throw new MissingDeleteHandlerError()\n }\n\n if (Array.isArray(keys) && keys.length === 0) {\n throw new NoKeysPassedToDeleteError()\n }\n\n const keysArray = Array.isArray(keys) ? keys : [keys]\n this.collection._sync.startSync()\n // One timestamp per call; mutations replace these rather than mutate them.\n const now = new Date()\n const mutations: Array<\n PendingMutation<\n TOutput,\n `delete`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n >\n > = []\n\n for (const key of keysArray) {\n if (!this.state.has(key)) {\n throw new DeleteKeyNotFoundError(key)\n }\n const globalKey = this.generateGlobalKey(key, this.state.get(key)!)\n const mutation: PendingMutation<\n TOutput,\n `delete`,\n CollectionImpl<TOutput, TKey, TUtils, TSchema, TInput>\n > = {\n mutationId: createMutationId(),\n original: this.state.get(key)!,\n modified: this.state.get(key)!,\n changes: this.state.get(key)!,\n globalKey,\n key,\n metadata: config?.metadata as unknown,\n syncMetadata: (state.syncedMetadata.get(key) || {}) as Record<\n string,\n unknown\n >,\n optimistic: config?.optimistic ?? true,\n type: `delete`,\n createdAt: now,\n updatedAt: now,\n collection: this.collection,\n }\n\n mutations.push(mutation)\n }\n\n // If an ambient transaction exists, use it\n if (ambientTransaction) {\n this.applyOwnedMutations(ambientTransaction, mutations)\n return ambientTransaction\n }\n\n return this.commitDirect(\n `delete`,\n (params) => this.config.onDelete!(params),\n mutations,\n )\n }\n}\n"],"mappings":";;;;;;AA+CA,IAAI;AACJ,IAAI,gBAAgB;AACpB,SAAS,mBAA2B;CAClC,qBAAqBA,aAAAA,eAAe;CACpC,OAAO,GAAG,iBAAA,GAAoB,EAAE;AAClC;AAEA,IAAa,6BAAb,MAME;CAQA,YACE,QACA,IACA;EA6NQ,KAAA,UAAA,MAA8BoB,YAA0B;GAChE,KAAK,UAAU,yBAAyB,QAAQ;GAChD,MAAM,QAAQ,KAAK;GACnB,MAAM,qBAAqB,KAAK,qBAAqB;GAGrD,IAAI,CAAC,sBAAsB,CAAC,KAAK,OAAO,UACtC,MAAM,IAAInB,eAAAA,0BAA0B;GAGtC,MAAM,QAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;GAEhD,MAAM,sBAAM,IAAI,KAAK;GACrB,MAAM,YAA6C,CAAC;GACpD,MAAM,qCAAqB,IAAI,IAAU;GAGzC,MAAM,SAAS,SAAS;IAEtB,MAAM,gBAAgB,KAAK,aAAa,MAAM,QAAQ;IAGtD,MAAM,MAAM,KAAK,OAAO,OAAO,aAAa;IAC5C,IAAI,mBAAmB,IAAI,GAAG,GAC5B,MAAM,IAAIC,eAAAA,kBAAkB,GAAG;IAEjC,mBAAmB,IAAI,GAAG;IAC1B,MAAM,YAAY,KAAK,kBAAkB,KAAK,IAAI;IAElD,MAAM,WAA+C;KACnD,YAAY,iBAAiB;KAC7B,UAAU,CAAC;KACX,UAAU;KAIV,SAAS,OAAO,YACd,OAAO,KAAK,IAAI,CAAA,CAAE,KAAK,MAAM,CAC3B,GACA,cAAc,EAChB,CAAC,CACH;KACA;KACA;KACA,UAAUkB,SAAQ;KAClB,cAAc,KAAK,OAAO,KAAK,kBAAkB,KAAK,CAAC;KACvD,YAAYA,SAAQ,cAAc;KAClC,MAAM;KACN,WAAW;KACX,WAAW;KACX,Y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