@tldraw/store 5.3.0 → 5.4.0-next.ef99ab47e5ce

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.
Files changed (41) hide show
  1. package/dist-cjs/index.d.ts +1 -0
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/lib/RecordType.js +1 -1
  4. package/dist-cjs/lib/RecordType.js.map +2 -2
  5. package/dist-cjs/lib/RecordsDiff.js +45 -9
  6. package/dist-cjs/lib/RecordsDiff.js.map +3 -3
  7. package/dist-cjs/lib/Store.js +18 -29
  8. package/dist-cjs/lib/Store.js.map +2 -2
  9. package/dist-cjs/lib/StoreQueries.js +7 -54
  10. package/dist-cjs/lib/StoreQueries.js.map +2 -2
  11. package/dist-cjs/lib/StoreSchema.js +8 -12
  12. package/dist-cjs/lib/StoreSchema.js.map +3 -3
  13. package/dist-cjs/lib/executeQuery.js +5 -2
  14. package/dist-cjs/lib/executeQuery.js.map +2 -2
  15. package/dist-cjs/lib/migrate.js +5 -7
  16. package/dist-cjs/lib/migrate.js.map +2 -2
  17. package/dist-esm/index.d.mts +1 -0
  18. package/dist-esm/index.mjs +1 -1
  19. package/dist-esm/lib/RecordType.mjs +1 -1
  20. package/dist-esm/lib/RecordType.mjs.map +2 -2
  21. package/dist-esm/lib/RecordsDiff.mjs +45 -9
  22. package/dist-esm/lib/RecordsDiff.mjs.map +3 -3
  23. package/dist-esm/lib/Store.mjs +19 -30
  24. package/dist-esm/lib/Store.mjs.map +2 -2
  25. package/dist-esm/lib/StoreQueries.mjs +7 -54
  26. package/dist-esm/lib/StoreQueries.mjs.map +2 -2
  27. package/dist-esm/lib/StoreSchema.mjs +8 -12
  28. package/dist-esm/lib/StoreSchema.mjs.map +3 -3
  29. package/dist-esm/lib/executeQuery.mjs +5 -2
  30. package/dist-esm/lib/executeQuery.mjs.map +2 -2
  31. package/dist-esm/lib/migrate.mjs +5 -7
  32. package/dist-esm/lib/migrate.mjs.map +2 -2
  33. package/package.json +3 -3
  34. package/src/lib/RecordType.ts +1 -1
  35. package/src/lib/RecordsDiff.ts +66 -10
  36. package/src/lib/Store.ts +21 -36
  37. package/src/lib/StoreQueries.test.ts +24 -0
  38. package/src/lib/StoreQueries.ts +7 -60
  39. package/src/lib/StoreSchema.ts +11 -17
  40. package/src/lib/executeQuery.ts +5 -2
  41. package/src/lib/migrate.ts +8 -12
@@ -2398,6 +2398,7 @@ export declare class StoreSchema<R extends UnknownRecord, P = unknown> {
2398
2398
  * @public
2399
2399
  */
2400
2400
  getMigrationsSince(persistedSchema: SerializedSchema): Result<Migration[], string>;
2401
+ private computeMigrationsSince;
2401
2402
  /**
2402
2403
  * Migrates a single persisted record to match the current schema version.
2403
2404
  *
package/dist-cjs/index.js CHANGED
@@ -56,7 +56,7 @@ var import_StoreSchema = require("./lib/StoreSchema");
56
56
  var import_StoreSideEffects = require("./lib/StoreSideEffects");
57
57
  (0, import_utils.registerTldrawLibraryVersion)(
58
58
  "@tldraw/store",
59
- "5.3.0",
59
+ "5.4.0-next.ef99ab47e5ce",
60
60
  "cjs"
61
61
  );
62
62
  //# sourceMappingURL=index.js.map
@@ -101,7 +101,7 @@ class RecordType {
101
101
  ...this.createDefaultProperties(),
102
102
  id: properties.id ?? this.createId()
103
103
  };
104
- for (const [k, v] of Object.entries(properties)) {
104
+ for (const [k, v] of (0, import_utils.objectMapEntries)(properties)) {
105
105
  if (v !== void 0) {
106
106
  result[k] = v;
107
107
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/RecordType.ts"],
4
- "sourcesContent": ["import { Expand, objectMapEntries, structuredClone, uniqueId } from '@tldraw/utils'\nimport { IdOf, UnknownRecord } from './BaseRecord'\nimport { StoreValidator } from './Store'\n\n/**\n * Utility type that extracts the record type from a RecordType instance.\n *\n * @example\n * ```ts\n * const Book = createRecordType<BookRecord>('book', { scope: 'document' })\n * type BookFromType = RecordTypeRecord<typeof Book> // BookRecord\n * ```\n *\n * @public\n */\nexport type RecordTypeRecord<R extends RecordType<any, any>> = ReturnType<R['create']>\n\n/**\n * Defines the scope of the record\n *\n * session: The record belongs to a single instance of the store. It should not be synced, and any persistence logic should 'de-instance-ize' the record before persisting it, and apply the reverse when rehydrating.\n * document: The record is persisted and synced. It is available to all store instances.\n * presence: The record belongs to a single instance of the store. It may be synced to other instances, but other instances should not make changes to it. It should not be persisted.\n *\n * @public\n * */\nexport type RecordScope = 'session' | 'document' | 'presence'\n\n/**\n * A record type is a type that can be stored in a record store. It is created with\n * `createRecordType`.\n *\n * @public\n */\nexport class RecordType<\n\tR extends UnknownRecord,\n\tRequiredProperties extends keyof Omit<R, 'id' | 'typeName'>,\n> {\n\t/**\n\t * Factory function that creates default properties for new records.\n\t * @public\n\t */\n\treadonly createDefaultProperties: () => Exclude<Omit<R, 'id' | 'typeName'>, RequiredProperties>\n\n\t/**\n\t * Validator function used to validate records of this type.\n\t * @public\n\t */\n\treadonly validator: StoreValidator<R>\n\n\t/**\n\t * Optional configuration specifying which record properties are ephemeral.\n\t * Ephemeral properties are not included in snapshots or synchronization.\n\t * @public\n\t */\n\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\n\t/**\n\t * Set of property names that are marked as ephemeral for efficient lookup.\n\t * @public\n\t */\n\treadonly ephemeralKeySet: ReadonlySet<string>\n\n\t/**\n\t * The scope that determines how records of this type are persisted and synchronized.\n\t * @public\n\t */\n\treadonly scope: RecordScope\n\n\t/**\n\t * Creates a new RecordType instance.\n\t *\n\t * typeName - The unique type name for records created by this RecordType\n\t * config - Configuration object for the RecordType\n\t * - createDefaultProperties - Function that returns default properties for new records\n\t * - validator - Optional validator function for record validation\n\t * - scope - Optional scope determining persistence behavior (defaults to 'document')\n\t * - ephemeralKeys - Optional mapping of property names to ephemeral status\n\t * @public\n\t */\n\tconstructor(\n\t\t/**\n\t\t * The unique type associated with this record.\n\t\t *\n\t\t * @public\n\t\t * @readonly\n\t\t */\n\t\tpublic readonly typeName: R['typeName'],\n\t\tconfig: {\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly createDefaultProperties: () => Exclude<\n\t\t\t\tOmit<R, 'id' | 'typeName'>,\n\t\t\t\tRequiredProperties\n\t\t\t>\n\t\t\treadonly validator?: StoreValidator<R>\n\t\t\treadonly scope?: RecordScope\n\t\t\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t\t}\n\t) {\n\t\tthis.createDefaultProperties = config.createDefaultProperties\n\t\tthis.validator = config.validator ?? { validate: (r: unknown) => r as R }\n\t\tthis.scope = config.scope ?? 'document'\n\t\tthis.ephemeralKeys = config.ephemeralKeys\n\n\t\tconst ephemeralKeySet = new Set<string>()\n\t\tif (config.ephemeralKeys) {\n\t\t\tfor (const [key, isEphemeral] of objectMapEntries(config.ephemeralKeys)) {\n\t\t\t\tif (isEphemeral) ephemeralKeySet.add(key as string)\n\t\t\t}\n\t\t}\n\t\tthis.ephemeralKeySet = ephemeralKeySet\n\t}\n\n\t/**\n\t * Creates a new record of this type with the given properties.\n\t *\n\t * Properties are merged with default properties from the RecordType configuration.\n\t * If no id is provided, a unique id will be generated automatically.\n\t *\n\t * @example\n\t * ```ts\n\t * const book = Book.create({\n\t * title: 'The Great Gatsby',\n\t * author: 'F. Scott Fitzgerald'\n\t * })\n\t * // Result: { id: 'book:abc123', typeName: 'book', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', inStock: true }\n\t * ```\n\t *\n\t * @param properties - The properties for the new record, including both required and optional fields\n\t * @returns The newly created record with generated id and typeName\n\t * @public\n\t */\n\tcreate(\n\t\tproperties: Expand<Pick<R, RequiredProperties> & Omit<Partial<R>, RequiredProperties>>\n\t): R {\n\t\tconst result = {\n\t\t\t...this.createDefaultProperties(),\n\t\t\tid: (properties as Partial<R>).id ?? this.createId(),\n\t\t} as any\n\n\t\tfor (const [k, v] of Object.entries(properties)) {\n\t\t\tif (v !== undefined) {\n\t\t\t\tresult[k] = v\n\t\t\t}\n\t\t}\n\n\t\tresult.typeName = this.typeName\n\n\t\treturn result as R\n\t}\n\n\t/**\n\t * Creates a deep copy of an existing record with a new unique id.\n\t *\n\t * This method performs a deep clone of all properties while generating a fresh id,\n\t * making it useful for duplicating records without id conflicts.\n\t *\n\t * @example\n\t * ```ts\n\t * const originalBook = Book.create({ title: '1984', author: 'George Orwell' })\n\t * const duplicatedBook = Book.clone(originalBook)\n\t * // duplicatedBook has same properties but different id\n\t * ```\n\t *\n\t * @param record - The record to clone\n\t * @returns A new record with the same properties but a different id\n\t * @public\n\t */\n\tclone(record: R): R {\n\t\treturn { ...structuredClone(record), id: this.createId() }\n\t}\n\n\t/**\n\t * Create a new ID for this record type.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const id = recordType.createId()\n\t * ```\n\t *\n\t * @returns The new ID.\n\t * @public\n\t */\n\tcreateId(customUniquePart?: string): IdOf<R> {\n\t\treturn (this.typeName + ':' + (customUniquePart ?? uniqueId())) as IdOf<R>\n\t}\n\n\t/**\n\t * Extracts the unique identifier part from a full record id.\n\t *\n\t * Record ids have the format `typeName:uniquePart`. This method returns just the unique part.\n\t *\n\t * @example\n\t * ```ts\n\t * const bookId = Book.createId() // 'book:abc123'\n\t * const uniquePart = Book.parseId(bookId) // 'abc123'\n\t * ```\n\t *\n\t * @param id - The full record id to parse\n\t * @returns The unique identifier portion after the colon\n\t * @throws Error if the id is not valid for this record type\n\t * @public\n\t */\n\tparseId(id: IdOf<R>): string {\n\t\tif (!this.isId(id)) {\n\t\t\tthrow new Error(`ID \"${id}\" is not a valid ID for type \"${this.typeName}\"`)\n\t\t}\n\n\t\treturn id.slice(this.typeName.length + 1)\n\t}\n\n\t/**\n\t * Type guard that checks whether a record belongs to this RecordType.\n\t *\n\t * This method performs a runtime check by comparing the record's typeName\n\t * against this RecordType's typeName.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isInstance(someRecord)) {\n\t * // someRecord is now typed as a book record\n\t * console.log(someRecord.title)\n\t * }\n\t * ```\n\t *\n\t * @param record - The record to check, may be undefined\n\t * @returns True if the record is an instance of this record type\n\t * @public\n\t */\n\tisInstance(record?: UnknownRecord): record is R {\n\t\treturn record?.typeName === this.typeName\n\t}\n\n\t/**\n\t * Type guard that checks whether an id string belongs to this RecordType.\n\t *\n\t * Validates that the id starts with this RecordType's typeName followed by a colon.\n\t * This is more efficient than parsing the full id when you only need to verify the type.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isId(someId)) {\n\t * // someId is now typed as IdOf<BookRecord>\n\t * const book = store.get(someId)\n\t * }\n\t * ```\n\t *\n\t * @param id - The id string to check, may be undefined\n\t * @returns True if the id belongs to this record type\n\t * @public\n\t */\n\tisId(id?: string): id is IdOf<R> {\n\t\tif (!id) return false\n\t\tfor (let i = 0; i < this.typeName.length; i++) {\n\t\t\tif (id[i] !== this.typeName[i]) return false\n\t\t}\n\n\t\treturn id[this.typeName.length] === ':'\n\t}\n\n\t/**\n\t * Create a new RecordType that has the same type name as this RecordType and includes the given\n\t * default properties.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const authorType = createRecordType('author', () => ({ living: true }))\n\t * const deadAuthorType = authorType.withDefaultProperties({ living: false })\n\t * ```\n\t *\n\t * @param createDefaultProperties - A function that returns the default properties of the new RecordType.\n\t * @returns The new RecordType.\n\t */\n\twithDefaultProperties<DefaultProps extends Omit<Partial<R>, 'typeName' | 'id'>>(\n\t\tcreateDefaultProperties: () => DefaultProps\n\t): RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>> {\n\t\treturn new RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>>(this.typeName, {\n\t\t\tcreateDefaultProperties: createDefaultProperties as any,\n\t\t\tvalidator: this.validator,\n\t\t\tscope: this.scope,\n\t\t\tephemeralKeys: this.ephemeralKeys,\n\t\t})\n\t}\n\n\t/**\n\t * Validates a record against this RecordType's validator and returns it with proper typing.\n\t *\n\t * This method runs the configured validator function and throws an error if validation fails.\n\t * If a previous version of the record is provided, it may use optimized validation.\n\t *\n\t * @example\n\t * ```ts\n\t * try {\n\t * const validBook = Book.validate(untrustedData)\n\t * // validBook is now properly typed and validated\n\t * } catch (error) {\n\t * console.log('Validation failed:', error.message)\n\t * }\n\t * ```\n\t *\n\t * @param record - The unknown record data to validate\n\t * @param recordBefore - Optional previous version for optimized validation\n\t * @returns The validated and properly typed record\n\t * @throws Error if validation fails\n\t * @public\n\t */\n\tvalidate(record: unknown, recordBefore?: R): R {\n\t\tif (recordBefore && this.validator.validateUsingKnownGoodVersion) {\n\t\t\treturn this.validator.validateUsingKnownGoodVersion(recordBefore, record)\n\t\t}\n\t\treturn this.validator.validate(record)\n\t}\n}\n\n/**\n * Creates a new RecordType with the specified configuration.\n *\n * This factory function creates a RecordType that can be used to create, validate, and manage\n * records of a specific type within a store. The resulting RecordType can be extended with\n * default properties using the withDefaultProperties method.\n *\n * @example\n * ```ts\n * interface BookRecord extends BaseRecord<'book', RecordId<BookRecord>> {\n * title: string\n * author: string\n * inStock: boolean\n * }\n *\n * const Book = createRecordType<BookRecord>('book', {\n * scope: 'document',\n * validator: bookValidator\n * })\n * ```\n *\n * @param typeName - The unique type name for this record type\n * @param config - Configuration object containing validator, scope, and ephemeral keys\n * @returns A new RecordType instance for creating and managing records\n * @public\n */\nexport function createRecordType<R extends UnknownRecord>(\n\ttypeName: R['typeName'],\n\tconfig: {\n\t\tvalidator?: StoreValidator<R>\n\t\tscope: RecordScope\n\t\tephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t}\n): RecordType<R, keyof Omit<R, 'id' | 'typeName'>> {\n\treturn new RecordType<R, keyof Omit<R, 'id' | 'typeName'>>(typeName, {\n\t\tcreateDefaultProperties: () => ({}) as any,\n\t\tvalidator: config.validator,\n\t\tscope: config.scope,\n\t\tephemeralKeys: config.ephemeralKeys,\n\t})\n}\n\n/**\n * Assert whether an id correspond to a record type.\n *\n * @example\n *\n * ```ts\n * assertIdType(myId, \"shape\")\n * ```\n *\n * @param id - The id to check.\n * @param type - The type of the record.\n * @public\n */\nexport function assertIdType<R extends UnknownRecord>(\n\tid: string | undefined,\n\ttype: RecordType<R, any>\n): asserts id is IdOf<R> {\n\tif (!id || !type.isId(id)) {\n\t\tthrow new Error(`string ${JSON.stringify(id)} is not a valid ${type.typeName} id`)\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAoE;AAkC7D,MAAM,WAGX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CD,YAOiB,UAChB,QAUC;AAXe;AAYhB,SAAK,0BAA0B,OAAO;AACtC,SAAK,YAAY,OAAO,aAAa,EAAE,UAAU,CAAC,MAAe,EAAO;AACxE,SAAK,QAAQ,OAAO,SAAS;AAC7B,SAAK,gBAAgB,OAAO;AAE5B,UAAM,kBAAkB,oBAAI,IAAY;AACxC,QAAI,OAAO,eAAe;AACzB,iBAAW,CAAC,KAAK,WAAW,SAAK,+BAAiB,OAAO,aAAa,GAAG;AACxE,YAAI,YAAa,iBAAgB,IAAI,GAAa;AAAA,MACnD;AAAA,IACD;AACA,SAAK,kBAAkB;AAAA,EACxB;AAAA,EAxBiB;AAAA;AAAA;AAAA;AAAA;AAAA,EA7CR;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiET,OACC,YACI;AACJ,UAAM,SAAS;AAAA,MACd,GAAG,KAAK,wBAAwB;AAAA,MACh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AAI,QAAO;AAChB,aAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,KAAK;AAC9C,UAAI,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,EAAG,QAAO;AAAA,IACxC;AAEA,WAAO,GAAG,KAAK,SAAS,MAAM,MAAM;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,sBACC,yBACiE;AACjE,WAAO,IAAI,WAA+D,KAAK,UAAU;AAAA,MACxF;AAAA,MACA,WAAW,KAAK;AAAA,MAChB,OAAO,KAAK;AAAA,MACZ,eAAe,KAAK;AAAA,IACrB,CAAC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBA,SAAS,QAAiB,cAAqB;AAC9C,QAAI,gBAAgB,KAAK,UAAU,+BAA+B;AACjE,aAAO,KAAK,UAAU,8BAA8B,cAAc,MAAM;AAAA,IACzE;AACA,WAAO,KAAK,UAAU,SAAS,MAAM;AAAA,EACtC;AACD;AA4BO,SAAS,iBACf,UACA,QAKkD;AAClD,SAAO,IAAI,WAAgD,UAAU;AAAA,IACpE,yBAAyB,OAAO,CAAC;AAAA,IACjC,WAAW,OAAO;AAAA,IAClB,OAAO,OAAO;AAAA,IACd,eAAe,OAAO;AAAA,EACvB,CAAC;AACF;AAeO,SAAS,aACf,IACA,MACwB;AACxB,MAAI,CAAC,MAAM,CAAC,KAAK,KAAK,EAAE,GAAG;AAC1B,UAAM,IAAI,MAAM,UAAU,KAAK,UAAU,EAAE,CAAC,mBAAmB,KAAK,QAAQ,KAAK;AAAA,EAClF;AACD;",
4
+ "sourcesContent": ["import { Expand, objectMapEntries, structuredClone, uniqueId } from '@tldraw/utils'\nimport { IdOf, UnknownRecord } from './BaseRecord'\nimport { StoreValidator } from './Store'\n\n/**\n * Utility type that extracts the record type from a RecordType instance.\n *\n * @example\n * ```ts\n * const Book = createRecordType<BookRecord>('book', { scope: 'document' })\n * type BookFromType = RecordTypeRecord<typeof Book> // BookRecord\n * ```\n *\n * @public\n */\nexport type RecordTypeRecord<R extends RecordType<any, any>> = ReturnType<R['create']>\n\n/**\n * Defines the scope of the record\n *\n * session: The record belongs to a single instance of the store. It should not be synced, and any persistence logic should 'de-instance-ize' the record before persisting it, and apply the reverse when rehydrating.\n * document: The record is persisted and synced. It is available to all store instances.\n * presence: The record belongs to a single instance of the store. It may be synced to other instances, but other instances should not make changes to it. It should not be persisted.\n *\n * @public\n * */\nexport type RecordScope = 'session' | 'document' | 'presence'\n\n/**\n * A record type is a type that can be stored in a record store. It is created with\n * `createRecordType`.\n *\n * @public\n */\nexport class RecordType<\n\tR extends UnknownRecord,\n\tRequiredProperties extends keyof Omit<R, 'id' | 'typeName'>,\n> {\n\t/**\n\t * Factory function that creates default properties for new records.\n\t * @public\n\t */\n\treadonly createDefaultProperties: () => Exclude<Omit<R, 'id' | 'typeName'>, RequiredProperties>\n\n\t/**\n\t * Validator function used to validate records of this type.\n\t * @public\n\t */\n\treadonly validator: StoreValidator<R>\n\n\t/**\n\t * Optional configuration specifying which record properties are ephemeral.\n\t * Ephemeral properties are not included in snapshots or synchronization.\n\t * @public\n\t */\n\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\n\t/**\n\t * Set of property names that are marked as ephemeral for efficient lookup.\n\t * @public\n\t */\n\treadonly ephemeralKeySet: ReadonlySet<string>\n\n\t/**\n\t * The scope that determines how records of this type are persisted and synchronized.\n\t * @public\n\t */\n\treadonly scope: RecordScope\n\n\t/**\n\t * Creates a new RecordType instance.\n\t *\n\t * typeName - The unique type name for records created by this RecordType\n\t * config - Configuration object for the RecordType\n\t * - createDefaultProperties - Function that returns default properties for new records\n\t * - validator - Optional validator function for record validation\n\t * - scope - Optional scope determining persistence behavior (defaults to 'document')\n\t * - ephemeralKeys - Optional mapping of property names to ephemeral status\n\t * @public\n\t */\n\tconstructor(\n\t\t/**\n\t\t * The unique type associated with this record.\n\t\t *\n\t\t * @public\n\t\t * @readonly\n\t\t */\n\t\tpublic readonly typeName: R['typeName'],\n\t\tconfig: {\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly createDefaultProperties: () => Exclude<\n\t\t\t\tOmit<R, 'id' | 'typeName'>,\n\t\t\t\tRequiredProperties\n\t\t\t>\n\t\t\treadonly validator?: StoreValidator<R>\n\t\t\treadonly scope?: RecordScope\n\t\t\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t\t}\n\t) {\n\t\tthis.createDefaultProperties = config.createDefaultProperties\n\t\tthis.validator = config.validator ?? { validate: (r: unknown) => r as R }\n\t\tthis.scope = config.scope ?? 'document'\n\t\tthis.ephemeralKeys = config.ephemeralKeys\n\n\t\tconst ephemeralKeySet = new Set<string>()\n\t\tif (config.ephemeralKeys) {\n\t\t\tfor (const [key, isEphemeral] of objectMapEntries(config.ephemeralKeys)) {\n\t\t\t\tif (isEphemeral) ephemeralKeySet.add(key as string)\n\t\t\t}\n\t\t}\n\t\tthis.ephemeralKeySet = ephemeralKeySet\n\t}\n\n\t/**\n\t * Creates a new record of this type with the given properties.\n\t *\n\t * Properties are merged with default properties from the RecordType configuration.\n\t * If no id is provided, a unique id will be generated automatically.\n\t *\n\t * @example\n\t * ```ts\n\t * const book = Book.create({\n\t * title: 'The Great Gatsby',\n\t * author: 'F. Scott Fitzgerald'\n\t * })\n\t * // Result: { id: 'book:abc123', typeName: 'book', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', inStock: true }\n\t * ```\n\t *\n\t * @param properties - The properties for the new record, including both required and optional fields\n\t * @returns The newly created record with generated id and typeName\n\t * @public\n\t */\n\tcreate(\n\t\tproperties: Expand<Pick<R, RequiredProperties> & Omit<Partial<R>, RequiredProperties>>\n\t): R {\n\t\tconst result = {\n\t\t\t...this.createDefaultProperties(),\n\t\t\tid: (properties as Partial<R>).id ?? this.createId(),\n\t\t} as any\n\n\t\tfor (const [k, v] of objectMapEntries(properties)) {\n\t\t\tif (v !== undefined) {\n\t\t\t\tresult[k] = v\n\t\t\t}\n\t\t}\n\n\t\tresult.typeName = this.typeName\n\n\t\treturn result as R\n\t}\n\n\t/**\n\t * Creates a deep copy of an existing record with a new unique id.\n\t *\n\t * This method performs a deep clone of all properties while generating a fresh id,\n\t * making it useful for duplicating records without id conflicts.\n\t *\n\t * @example\n\t * ```ts\n\t * const originalBook = Book.create({ title: '1984', author: 'George Orwell' })\n\t * const duplicatedBook = Book.clone(originalBook)\n\t * // duplicatedBook has same properties but different id\n\t * ```\n\t *\n\t * @param record - The record to clone\n\t * @returns A new record with the same properties but a different id\n\t * @public\n\t */\n\tclone(record: R): R {\n\t\treturn { ...structuredClone(record), id: this.createId() }\n\t}\n\n\t/**\n\t * Create a new ID for this record type.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const id = recordType.createId()\n\t * ```\n\t *\n\t * @returns The new ID.\n\t * @public\n\t */\n\tcreateId(customUniquePart?: string): IdOf<R> {\n\t\treturn (this.typeName + ':' + (customUniquePart ?? uniqueId())) as IdOf<R>\n\t}\n\n\t/**\n\t * Extracts the unique identifier part from a full record id.\n\t *\n\t * Record ids have the format `typeName:uniquePart`. This method returns just the unique part.\n\t *\n\t * @example\n\t * ```ts\n\t * const bookId = Book.createId() // 'book:abc123'\n\t * const uniquePart = Book.parseId(bookId) // 'abc123'\n\t * ```\n\t *\n\t * @param id - The full record id to parse\n\t * @returns The unique identifier portion after the colon\n\t * @throws Error if the id is not valid for this record type\n\t * @public\n\t */\n\tparseId(id: IdOf<R>): string {\n\t\tif (!this.isId(id)) {\n\t\t\tthrow new Error(`ID \"${id}\" is not a valid ID for type \"${this.typeName}\"`)\n\t\t}\n\n\t\treturn id.slice(this.typeName.length + 1)\n\t}\n\n\t/**\n\t * Type guard that checks whether a record belongs to this RecordType.\n\t *\n\t * This method performs a runtime check by comparing the record's typeName\n\t * against this RecordType's typeName.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isInstance(someRecord)) {\n\t * // someRecord is now typed as a book record\n\t * console.log(someRecord.title)\n\t * }\n\t * ```\n\t *\n\t * @param record - The record to check, may be undefined\n\t * @returns True if the record is an instance of this record type\n\t * @public\n\t */\n\tisInstance(record?: UnknownRecord): record is R {\n\t\treturn record?.typeName === this.typeName\n\t}\n\n\t/**\n\t * Type guard that checks whether an id string belongs to this RecordType.\n\t *\n\t * Validates that the id starts with this RecordType's typeName followed by a colon.\n\t * This is more efficient than parsing the full id when you only need to verify the type.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isId(someId)) {\n\t * // someId is now typed as IdOf<BookRecord>\n\t * const book = store.get(someId)\n\t * }\n\t * ```\n\t *\n\t * @param id - The id string to check, may be undefined\n\t * @returns True if the id belongs to this record type\n\t * @public\n\t */\n\tisId(id?: string): id is IdOf<R> {\n\t\tif (!id) return false\n\t\tfor (let i = 0; i < this.typeName.length; i++) {\n\t\t\tif (id[i] !== this.typeName[i]) return false\n\t\t}\n\n\t\treturn id[this.typeName.length] === ':'\n\t}\n\n\t/**\n\t * Create a new RecordType that has the same type name as this RecordType and includes the given\n\t * default properties.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const authorType = createRecordType('author', () => ({ living: true }))\n\t * const deadAuthorType = authorType.withDefaultProperties({ living: false })\n\t * ```\n\t *\n\t * @param createDefaultProperties - A function that returns the default properties of the new RecordType.\n\t * @returns The new RecordType.\n\t */\n\twithDefaultProperties<DefaultProps extends Omit<Partial<R>, 'typeName' | 'id'>>(\n\t\tcreateDefaultProperties: () => DefaultProps\n\t): RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>> {\n\t\treturn new RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>>(this.typeName, {\n\t\t\tcreateDefaultProperties: createDefaultProperties as any,\n\t\t\tvalidator: this.validator,\n\t\t\tscope: this.scope,\n\t\t\tephemeralKeys: this.ephemeralKeys,\n\t\t})\n\t}\n\n\t/**\n\t * Validates a record against this RecordType's validator and returns it with proper typing.\n\t *\n\t * This method runs the configured validator function and throws an error if validation fails.\n\t * If a previous version of the record is provided, it may use optimized validation.\n\t *\n\t * @example\n\t * ```ts\n\t * try {\n\t * const validBook = Book.validate(untrustedData)\n\t * // validBook is now properly typed and validated\n\t * } catch (error) {\n\t * console.log('Validation failed:', error.message)\n\t * }\n\t * ```\n\t *\n\t * @param record - The unknown record data to validate\n\t * @param recordBefore - Optional previous version for optimized validation\n\t * @returns The validated and properly typed record\n\t * @throws Error if validation fails\n\t * @public\n\t */\n\tvalidate(record: unknown, recordBefore?: R): R {\n\t\tif (recordBefore && this.validator.validateUsingKnownGoodVersion) {\n\t\t\treturn this.validator.validateUsingKnownGoodVersion(recordBefore, record)\n\t\t}\n\t\treturn this.validator.validate(record)\n\t}\n}\n\n/**\n * Creates a new RecordType with the specified configuration.\n *\n * This factory function creates a RecordType that can be used to create, validate, and manage\n * records of a specific type within a store. The resulting RecordType can be extended with\n * default properties using the withDefaultProperties method.\n *\n * @example\n * ```ts\n * interface BookRecord extends BaseRecord<'book', RecordId<BookRecord>> {\n * title: string\n * author: string\n * inStock: boolean\n * }\n *\n * const Book = createRecordType<BookRecord>('book', {\n * scope: 'document',\n * validator: bookValidator\n * })\n * ```\n *\n * @param typeName - The unique type name for this record type\n * @param config - Configuration object containing validator, scope, and ephemeral keys\n * @returns A new RecordType instance for creating and managing records\n * @public\n */\nexport function createRecordType<R extends UnknownRecord>(\n\ttypeName: R['typeName'],\n\tconfig: {\n\t\tvalidator?: StoreValidator<R>\n\t\tscope: RecordScope\n\t\tephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t}\n): RecordType<R, keyof Omit<R, 'id' | 'typeName'>> {\n\treturn new RecordType<R, keyof Omit<R, 'id' | 'typeName'>>(typeName, {\n\t\tcreateDefaultProperties: () => ({}) as any,\n\t\tvalidator: config.validator,\n\t\tscope: config.scope,\n\t\tephemeralKeys: config.ephemeralKeys,\n\t})\n}\n\n/**\n * Assert whether an id correspond to a record type.\n *\n * @example\n *\n * ```ts\n * assertIdType(myId, \"shape\")\n * ```\n *\n * @param id - The id to check.\n * @param type - The type of the record.\n * @public\n */\nexport function assertIdType<R extends UnknownRecord>(\n\tid: string | undefined,\n\ttype: RecordType<R, any>\n): asserts id is IdOf<R> {\n\tif (!id || !type.isId(id)) {\n\t\tthrow new Error(`string ${JSON.stringify(id)} is not a valid ${type.typeName} id`)\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAoE;AAkC7D,MAAM,WAGX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2CD,YAOiB,UAChB,QAUC;AAXe;AAYhB,SAAK,0BAA0B,OAAO;AACtC,SAAK,YAAY,OAAO,aAAa,EAAE,UAAU,CAAC,MAAe,EAAO;AACxE,SAAK,QAAQ,OAAO,SAAS;AAC7B,SAAK,gBAAgB,OAAO;AAE5B,UAAM,kBAAkB,oBAAI,IAAY;AACxC,QAAI,OAAO,eAAe;AACzB,iBAAW,CAAC,KAAK,WAAW,SAAK,+BAAiB,OAAO,aAAa,GAAG;AACxE,YAAI,YAAa,iBAAgB,IAAI,GAAa;AAAA,MACnD;AAAA,IACD;AACA,SAAK,kBAAkB;AAAA,EACxB;AAAA,EAxBiB;AAAA;AAAA;AAAA;AAAA;AAAA,EA7CR;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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K,UAAU,EAAE,CAAC,mBAAmB,KAAK,QAAQ,KAAK;AAAA,EAClF;AACD;",
6
6
  "names": []
7
7
  }
@@ -23,15 +23,17 @@ __export(RecordsDiff_exports, {
23
23
  isRecordsDiffEmpty: () => isRecordsDiffEmpty,
24
24
  reverseRecordsDiff: () => reverseRecordsDiff,
25
25
  squashRecordDiffs: () => squashRecordDiffs,
26
- squashRecordDiffsMutable: () => squashRecordDiffsMutable
26
+ squashRecordDiffsMutable: () => squashRecordDiffsMutable,
27
+ squashRecordDiffsMutableByType: () => squashRecordDiffsMutableByType
27
28
  });
28
29
  module.exports = __toCommonJS(RecordsDiff_exports);
30
+ var import_utils = require("@tldraw/utils");
29
31
  function createEmptyRecordsDiff() {
30
32
  return { added: {}, updated: {}, removed: {} };
31
33
  }
32
34
  function reverseRecordsDiff(diff) {
33
35
  const result = { added: diff.removed, removed: diff.added, updated: {} };
34
- for (const [from, to] of Object.values(diff.updated)) {
36
+ for (const [from, to] of (0, import_utils.objectMapValues)(diff.updated)) {
35
37
  result.updated[from.id] = [to, from];
36
38
  }
37
39
  return result;
@@ -44,23 +46,41 @@ function hasAnyKey(obj) {
44
46
  return false;
45
47
  }
46
48
  function squashRecordDiffs(diffs, options) {
47
- const result = options?.mutateFirstDiff ? diffs[0] : { added: {}, removed: {}, updated: {} };
48
- squashRecordDiffsMutable(result, options?.mutateFirstDiff ? diffs.slice(1) : diffs);
49
+ if (options?.mutateFirstDiff) {
50
+ const result2 = diffs[0];
51
+ squashRecordDiffsMutable(result2, diffs, 1);
52
+ return result2;
53
+ }
54
+ const result = { added: {}, removed: {}, updated: {} };
55
+ squashRecordDiffsMutable(result, diffs);
49
56
  return result;
50
57
  }
51
- function squashRecordDiffsMutable(target, diffs) {
52
- for (const diff of diffs) {
58
+ function squashRecordDiffsMutable(target, diffs, fromIndex = 0) {
59
+ squashRecordDiffsMutableImpl(target, diffs, fromIndex);
60
+ }
61
+ function squashRecordDiffsMutableByType(target, diffs, typeName) {
62
+ return squashRecordDiffsMutableImpl(target, diffs, 0, typeName);
63
+ }
64
+ function squashRecordDiffsMutableImpl(target, diffs, fromIndex, typeName) {
65
+ let sizeChange = 0;
66
+ const trackSize = typeName !== void 0;
67
+ for (let i = fromIndex; i < diffs.length; i++) {
68
+ const diff = diffs[i];
53
69
  const targetHasRemoved = hasAnyKey(target.removed);
54
70
  for (const _id in diff.added) {
55
71
  const id = _id;
56
72
  const value = diff.added[id];
73
+ if (typeName !== void 0 && value.typeName !== typeName) continue;
57
74
  if (targetHasRemoved && target.removed[id]) {
58
75
  const original = target.removed[id];
59
76
  delete target.removed[id];
77
+ if (trackSize) sizeChange--;
60
78
  if (original !== value) {
61
79
  target.updated[id] = [original, value];
80
+ if (trackSize) sizeChange++;
62
81
  }
63
82
  } else {
83
+ if (trackSize && !target.added[id]) sizeChange++;
64
84
  target.added[id] = value;
65
85
  }
66
86
  }
@@ -68,32 +88,48 @@ function squashRecordDiffsMutable(target, diffs) {
68
88
  for (const _id in diff.updated) {
69
89
  const id = _id;
70
90
  const to = diff.updated[id][1];
91
+ if (typeName !== void 0 && to.typeName !== typeName) continue;
71
92
  if (targetHasAdded && target.added[id]) {
72
93
  target.added[id] = to;
94
+ if (trackSize && target.updated[id]) sizeChange--;
73
95
  delete target.updated[id];
74
- if (targetHasRemoved) delete target.removed[id];
96
+ if (targetHasRemoved) {
97
+ if (trackSize && target.removed[id]) sizeChange--;
98
+ delete target.removed[id];
99
+ }
75
100
  continue;
76
101
  }
77
102
  const existing = target.updated[id];
78
103
  if (existing) {
79
104
  existing[1] = to;
80
- if (targetHasRemoved) delete target.removed[id];
105
+ if (targetHasRemoved) {
106
+ if (trackSize && target.removed[id]) sizeChange--;
107
+ delete target.removed[id];
108
+ }
81
109
  continue;
82
110
  }
83
111
  target.updated[id] = [diff.updated[id][0], to];
84
- if (targetHasRemoved) delete target.removed[id];
112
+ if (trackSize) sizeChange++;
113
+ if (targetHasRemoved) {
114
+ if (trackSize && target.removed[id]) sizeChange--;
115
+ delete target.removed[id];
116
+ }
85
117
  }
86
118
  for (const _id in diff.removed) {
87
119
  const id = _id;
120
+ if (typeName !== void 0 && diff.removed[id].typeName !== typeName) continue;
88
121
  if (target.added[id]) {
89
122
  delete target.added[id];
123
+ if (trackSize) sizeChange--;
90
124
  } else if (target.updated[id]) {
91
125
  target.removed[id] = target.updated[id][0];
92
126
  delete target.updated[id];
93
127
  } else {
128
+ if (trackSize && !target.removed[id]) sizeChange++;
94
129
  target.removed[id] = diff.removed[id];
95
130
  }
96
131
  }
97
132
  }
133
+ return sizeChange;
98
134
  }
99
135
  //# sourceMappingURL=RecordsDiff.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/RecordsDiff.ts"],
4
- "sourcesContent": ["import { IdOf, UnknownRecord } from './BaseRecord'\n\n/**\n * A diff describing the changes to records, containing collections of records that were added,\n * updated, or removed. This is the fundamental data structure used throughout the store system\n * to track and communicate changes.\n *\n * @example\n * ```ts\n * const diff: RecordsDiff<Book> = {\n * added: {\n * 'book:1': { id: 'book:1', typeName: 'book', title: 'New Book' }\n * },\n * updated: {\n * 'book:2': [\n * { id: 'book:2', typeName: 'book', title: 'Old Title' }, // from\n * { id: 'book:2', typeName: 'book', title: 'New Title' } // to\n * ]\n * },\n * removed: {\n * 'book:3': { id: 'book:3', typeName: 'book', title: 'Deleted Book' }\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface RecordsDiff<R extends UnknownRecord> {\n\t/** Records that were created, keyed by their ID */\n\tadded: Record<IdOf<R>, R>\n\t/** Records that were modified, keyed by their ID. Each entry contains [from, to] tuple */\n\tupdated: Record<IdOf<R>, [from: R, to: R]>\n\t/** Records that were deleted, keyed by their ID */\n\tremoved: Record<IdOf<R>, R>\n}\n\n/**\n * Creates an empty RecordsDiff with no added, updated, or removed records.\n * This is useful as a starting point when building diffs programmatically.\n *\n * @returns An empty RecordsDiff with all collections initialized to empty objects\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * // Result: { added: {}, updated: {}, removed: {} }\n * ```\n *\n * @internal\n */\nexport function createEmptyRecordsDiff<R extends UnknownRecord>(): RecordsDiff<R> {\n\treturn { added: {}, updated: {}, removed: {} } as RecordsDiff<R>\n}\n\n/**\n * Creates the inverse of a RecordsDiff, effectively reversing all changes.\n * Added records become removed, removed records become added, and updated records\n * have their from/to values swapped. This is useful for implementing undo operations.\n *\n * @param diff - The diff to reverse\n * @returns A new RecordsDiff that represents the inverse of the input diff\n * @example\n * ```ts\n * const originalDiff: RecordsDiff<Book> = {\n * added: { 'book:1': newBook },\n * updated: { 'book:2': [oldBook, updatedBook] },\n * removed: { 'book:3': deletedBook }\n * }\n *\n * const reversedDiff = reverseRecordsDiff(originalDiff)\n * // Result: {\n * // added: { 'book:3': deletedBook },\n * // updated: { 'book:2': [updatedBook, oldBook] },\n * // removed: { 'book:1': newBook }\n * // }\n * ```\n *\n * @public\n */\nexport function reverseRecordsDiff(diff: RecordsDiff<any>) {\n\tconst result: RecordsDiff<any> = { added: diff.removed, removed: diff.added, updated: {} }\n\tfor (const [from, to] of Object.values(diff.updated)) {\n\t\tresult.updated[from.id] = [to, from]\n\t}\n\treturn result\n}\n\n/**\n * Checks whether a RecordsDiff contains any changes. A diff is considered empty\n * if it has no added, updated, or removed records.\n *\n * @param diff - The diff to check\n * @returns True if the diff contains no changes, false otherwise\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * console.log(isRecordsDiffEmpty(emptyDiff)) // true\n *\n * const nonEmptyDiff: RecordsDiff<Book> = {\n * added: { 'book:1': someBook },\n * updated: {},\n * removed: {}\n * }\n * console.log(isRecordsDiffEmpty(nonEmptyDiff)) // false\n * ```\n *\n * @public\n */\nexport function isRecordsDiffEmpty<T extends UnknownRecord>(diff: RecordsDiff<T>) {\n\treturn !hasAnyKey(diff.added) && !hasAnyKey(diff.updated) && !hasAnyKey(diff.removed)\n}\n\n// Cheaper than Object.keys().length, but note that for-in still pays an O(N)\n// key-collection prologue on dictionary-mode objects (which diffs become once keys\n// are deleted from them) \u2014 avoid calling this on large diffs in per-frame hot paths.\n/** @internal */\nexport function hasAnyKey(obj: object) {\n\tfor (const _ in obj) return true\n\treturn false\n}\n\n/**\n * Combines multiple RecordsDiff objects into a single consolidated diff.\n * This function intelligently merges changes, handling cases where the same record\n * is modified multiple times across different diffs. For example, if a record is\n * added in one diff and then updated in another, the result will show it as added\n * with the final state.\n *\n * @param diffs - An array of diffs to combine into a single diff\n * @param options - Configuration options for the squashing operation\n * - mutateFirstDiff - If true, modifies the first diff in place instead of creating a new one\n * @returns A single diff that represents the cumulative effect of all input diffs\n * @example\n * ```ts\n * const diff1: RecordsDiff<Book> = {\n * added: { 'book:1': { id: 'book:1', title: 'New Book' } },\n * updated: {},\n * removed: {}\n * }\n *\n * const diff2: RecordsDiff<Book> = {\n * added: {},\n * updated: { 'book:1': [{ id: 'book:1', title: 'New Book' }, { id: 'book:1', title: 'Updated Title' }] },\n * removed: {}\n * }\n *\n * const squashed = squashRecordDiffs([diff1, diff2])\n * // Result: {\n * // added: { 'book:1': { id: 'book:1', title: 'Updated Title' } },\n * // updated: {},\n * // removed: {}\n * // }\n * ```\n *\n * @public\n */\nexport function squashRecordDiffs<T extends UnknownRecord>(\n\tdiffs: RecordsDiff<T>[],\n\toptions?: {\n\t\tmutateFirstDiff?: boolean\n\t}\n): RecordsDiff<T> {\n\tconst result = options?.mutateFirstDiff\n\t\t? diffs[0]\n\t\t: ({ added: {}, removed: {}, updated: {} } as RecordsDiff<T>)\n\n\tsquashRecordDiffsMutable(result, options?.mutateFirstDiff ? diffs.slice(1) : diffs)\n\treturn result\n}\n\n/**\n * Applies an array of diffs to a target diff by mutating the target in-place.\n * This is the core implementation used by squashRecordDiffs. It handles complex\n * scenarios where records move between added/updated/removed states across multiple diffs.\n *\n * The function processes each diff sequentially, applying the following logic:\n * - Added records: If the record was previously removed, convert to an update; otherwise add it\n * - Updated records: Chain updates together, preserving the original 'from' state\n * - Removed records: If the record was added in this sequence, cancel both operations\n *\n * @param target - The diff to modify in-place (will be mutated)\n * @param diffs - Array of diffs to apply to the target\n * @example\n * ```ts\n * const targetDiff: RecordsDiff<Book> = {\n * added: {},\n * updated: {},\n * removed: { 'book:1': oldBook }\n * }\n *\n * const newDiffs = [{\n * added: { 'book:1': newBook },\n * updated: {},\n * removed: {}\n * }]\n *\n * squashRecordDiffsMutable(targetDiff, newDiffs)\n * // targetDiff is now: {\n * // added: {},\n * // updated: { 'book:1': [oldBook, newBook] },\n * // removed: {}\n * // }\n * ```\n *\n * @internal\n */\nexport function squashRecordDiffsMutable<T extends UnknownRecord>(\n\ttarget: RecordsDiff<T>,\n\tdiffs: RecordsDiff<T>[]\n): void {\n\t// This runs on every history interceptor call \u2014 e.g. once per input tick while\n\t// resizing N shapes, with N entries in diff.updated \u2014 so the updated loop must not\n\t// allocate per entry. We use for-in instead of Object.entries, mutate the target's\n\t// existing [from, to] tuples in place, and skip delete calls against collections we\n\t// know are empty. In-place tuple mutation is safe because the target exclusively\n\t// owns its updated tuples: they are always created here (never shared with a source\n\t// diff), and sources are never mutated.\n\tfor (const diff of diffs) {\n\t\t// target.removed can only lose entries before the removed loop below, so a\n\t\t// stale `true` is harmless (extra no-op deletes).\n\t\tconst targetHasRemoved = hasAnyKey(target.removed)\n\n\t\tfor (const _id in diff.added) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\tconst value = diff.added[id]\n\t\t\tif (targetHasRemoved && target.removed[id]) {\n\t\t\t\tconst original = target.removed[id]\n\t\t\t\tdelete target.removed[id]\n\t\t\t\tif (original !== value) {\n\t\t\t\t\ttarget.updated[id] = [original, value]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttarget.added[id] = value\n\t\t\t}\n\t\t}\n\n\t\t// the added loop above may have inserted into target.added\n\t\tconst targetHasAdded = hasAnyKey(target.added)\n\n\t\tfor (const _id in diff.updated) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\tconst to = diff.updated[id][1]\n\t\t\tif (targetHasAdded && target.added[id]) {\n\t\t\t\ttarget.added[id] = to\n\t\t\t\tdelete target.updated[id]\n\t\t\t\tif (targetHasRemoved) delete target.removed[id]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst existing = target.updated[id]\n\t\t\tif (existing) {\n\t\t\t\texisting[1] = to\n\t\t\t\tif (targetHasRemoved) delete target.removed[id]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// copy the tuple so the target owns it and can mutate it in place later\n\t\t\ttarget.updated[id] = [diff.updated[id][0], to]\n\t\t\tif (targetHasRemoved) delete target.removed[id]\n\t\t}\n\n\t\tfor (const _id in diff.removed) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\t// the same record was added in this diff sequence, just drop it\n\t\t\tif (target.added[id]) {\n\t\t\t\tdelete target.added[id]\n\t\t\t} else if (target.updated[id]) {\n\t\t\t\ttarget.removed[id] = target.updated[id][0]\n\t\t\t\tdelete target.updated[id]\n\t\t\t} else {\n\t\t\t\ttarget.removed[id] = diff.removed[id]\n\t\t\t}\n\t\t}\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiDO,SAAS,yBAAkE;AACjF,SAAO,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC,EAAE;AAC9C;AA2BO,SAAS,mBAAmB,MAAwB;AAC1D,QAAM,SAA2B,EAAE,OAAO,KAAK,SAAS,SAAS,KAAK,OAAO,SAAS,CAAC,EAAE;AACzF,aAAW,CAAC,MAAM,EAAE,KAAK,OAAO,OAAO,KAAK,OAAO,GAAG;AACrD,WAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,IAAI,IAAI;AAAA,EACpC;AACA,SAAO;AACR;AAuBO,SAAS,mBAA4C,MAAsB;AACjF,SAAO,CAAC,UAAU,KAAK,KAAK,KAAK,CAAC,UA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AC9C;AAAA,MACD;AAGA,aAAO,QAAQ,EAAE,IAAI,CAAC,KAAK,QAAQ,EAAE,EAAE,CAAC,GAAG,EAAE;AAC7C,UAAI,iBAAkB,QAAO,OAAO,QAAQ,EAAE;AAAA,IAC/C;AAEA,eAAW,OAAO,KAAK,SAAS;AAC/B,YAAM,KAAK;AAEX,UAAI,OAAO,MAAM,EAAE,GAAG;AACrB,eAAO,OAAO,MAAM,EAAE;AAAA,MACvB,WAAW,OAAO,QAAQ,EAAE,GAAG;AAC9B,eAAO,QAAQ,EAAE,IAAI,OAAO,QAAQ,EAAE,EAAE,CAAC;AACzC,eAAO,OAAO,QAAQ,EAAE;AAAA,MACzB,OAAO;AACN,eAAO,QAAQ,EAAE,IAAI,KAAK,QAAQ,EAAE;AAAA,MACrC;AAAA,IACD;AAAA,EACD;AACD;",
6
- "names": []
4
+ "sourcesContent": ["import { objectMapValues } from '@tldraw/utils'\nimport { IdOf, UnknownRecord } from './BaseRecord'\n\n/**\n * A diff describing the changes to records, containing collections of records that were added,\n * updated, or removed. This is the fundamental data structure used throughout the store system\n * to track and communicate changes.\n *\n * @example\n * ```ts\n * const diff: RecordsDiff<Book> = {\n * added: {\n * 'book:1': { id: 'book:1', typeName: 'book', title: 'New Book' }\n * },\n * updated: {\n * 'book:2': [\n * { id: 'book:2', typeName: 'book', title: 'Old Title' }, // from\n * { id: 'book:2', typeName: 'book', title: 'New Title' } // to\n * ]\n * },\n * removed: {\n * 'book:3': { id: 'book:3', typeName: 'book', title: 'Deleted Book' }\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface RecordsDiff<R extends UnknownRecord> {\n\t/** Records that were created, keyed by their ID */\n\tadded: Record<IdOf<R>, R>\n\t/** Records that were modified, keyed by their ID. Each entry contains [from, to] tuple */\n\tupdated: Record<IdOf<R>, [from: R, to: R]>\n\t/** Records that were deleted, keyed by their ID */\n\tremoved: Record<IdOf<R>, R>\n}\n\n/**\n * Creates an empty RecordsDiff with no added, updated, or removed records.\n * This is useful as a starting point when building diffs programmatically.\n *\n * @returns An empty RecordsDiff with all collections initialized to empty objects\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * // Result: { added: {}, updated: {}, removed: {} }\n * ```\n *\n * @internal\n */\nexport function createEmptyRecordsDiff<R extends UnknownRecord>(): RecordsDiff<R> {\n\treturn { added: {}, updated: {}, removed: {} } as RecordsDiff<R>\n}\n\n/**\n * Creates the inverse of a RecordsDiff, effectively reversing all changes.\n * Added records become removed, removed records become added, and updated records\n * have their from/to values swapped. This is useful for implementing undo operations.\n *\n * @param diff - The diff to reverse\n * @returns A new RecordsDiff that represents the inverse of the input diff\n * @example\n * ```ts\n * const originalDiff: RecordsDiff<Book> = {\n * added: { 'book:1': newBook },\n * updated: { 'book:2': [oldBook, updatedBook] },\n * removed: { 'book:3': deletedBook }\n * }\n *\n * const reversedDiff = reverseRecordsDiff(originalDiff)\n * // Result: {\n * // added: { 'book:3': deletedBook },\n * // updated: { 'book:2': [updatedBook, oldBook] },\n * // removed: { 'book:1': newBook }\n * // }\n * ```\n *\n * @public\n */\nexport function reverseRecordsDiff(diff: RecordsDiff<any>) {\n\tconst result: RecordsDiff<any> = { added: diff.removed, removed: diff.added, updated: {} }\n\tfor (const [from, to] of objectMapValues(diff.updated)) {\n\t\tresult.updated[from.id] = [to, from]\n\t}\n\treturn result\n}\n\n/**\n * Checks whether a RecordsDiff contains any changes. A diff is considered empty\n * if it has no added, updated, or removed records.\n *\n * @param diff - The diff to check\n * @returns True if the diff contains no changes, false otherwise\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * console.log(isRecordsDiffEmpty(emptyDiff)) // true\n *\n * const nonEmptyDiff: RecordsDiff<Book> = {\n * added: { 'book:1': someBook },\n * updated: {},\n * removed: {}\n * }\n * console.log(isRecordsDiffEmpty(nonEmptyDiff)) // false\n * ```\n *\n * @public\n */\nexport function isRecordsDiffEmpty<T extends UnknownRecord>(diff: RecordsDiff<T>) {\n\treturn !hasAnyKey(diff.added) && !hasAnyKey(diff.updated) && !hasAnyKey(diff.removed)\n}\n\n// Cheaper than Object.keys().length, but note that for-in still pays an O(N)\n// key-collection prologue on dictionary-mode objects (which diffs become once keys\n// are deleted from them) \u2014 avoid calling this on large diffs in per-frame hot paths.\n/** @internal */\nexport function hasAnyKey(obj: object) {\n\tfor (const _ in obj) return true\n\treturn false\n}\n\n/**\n * Combines multiple RecordsDiff objects into a single consolidated diff.\n * This function intelligently merges changes, handling cases where the same record\n * is modified multiple times across different diffs. For example, if a record is\n * added in one diff and then updated in another, the result will show it as added\n * with the final state.\n *\n * @param diffs - An array of diffs to combine into a single diff\n * @param options - Configuration options for the squashing operation\n * - mutateFirstDiff - If true, modifies the first diff in place instead of creating a new one\n * @returns A single diff that represents the cumulative effect of all input diffs\n * @example\n * ```ts\n * const diff1: RecordsDiff<Book> = {\n * added: { 'book:1': { id: 'book:1', title: 'New Book' } },\n * updated: {},\n * removed: {}\n * }\n *\n * const diff2: RecordsDiff<Book> = {\n * added: {},\n * updated: { 'book:1': [{ id: 'book:1', title: 'New Book' }, { id: 'book:1', title: 'Updated Title' }] },\n * removed: {}\n * }\n *\n * const squashed = squashRecordDiffs([diff1, diff2])\n * // Result: {\n * // added: { 'book:1': { id: 'book:1', title: 'Updated Title' } },\n * // updated: {},\n * // removed: {}\n * // }\n * ```\n *\n * @public\n */\nexport function squashRecordDiffs<T extends UnknownRecord>(\n\tdiffs: RecordsDiff<T>[],\n\toptions?: {\n\t\tmutateFirstDiff?: boolean\n\t}\n): RecordsDiff<T> {\n\tif (options?.mutateFirstDiff) {\n\t\tconst result = diffs[0]\n\t\tsquashRecordDiffsMutable(result, diffs, 1)\n\t\treturn result\n\t}\n\n\tconst result = { added: {}, removed: {}, updated: {} } as RecordsDiff<T>\n\tsquashRecordDiffsMutable(result, diffs)\n\treturn result\n}\n\n/**\n * Applies an array of diffs to a target diff by mutating the target in-place.\n * This is the core implementation used by squashRecordDiffs. It handles complex\n * scenarios where records move between added/updated/removed states across multiple diffs.\n *\n * The function processes each diff sequentially, applying the following logic:\n * - Added records: If the record was previously removed, convert to an update; otherwise add it\n * - Updated records: Chain updates together, preserving the original 'from' state\n * - Removed records: If the record was added in this sequence, cancel both operations\n *\n * @param target - The diff to modify in-place (will be mutated)\n * @param diffs - Array of diffs to apply to the target\n * @example\n * ```ts\n * const targetDiff: RecordsDiff<Book> = {\n * added: {},\n * updated: {},\n * removed: { 'book:1': oldBook }\n * }\n *\n * const newDiffs = [{\n * added: { 'book:1': newBook },\n * updated: {},\n * removed: {}\n * }]\n *\n * squashRecordDiffsMutable(targetDiff, newDiffs)\n * // targetDiff is now: {\n * // added: {},\n * // updated: { 'book:1': [oldBook, newBook] },\n * // removed: {}\n * // }\n * ```\n *\n * @internal\n */\nexport function squashRecordDiffsMutable<T extends UnknownRecord>(\n\ttarget: RecordsDiff<T>,\n\tdiffs: RecordsDiff<T>[],\n\tfromIndex = 0\n): void {\n\tsquashRecordDiffsMutableImpl(target, diffs, fromIndex)\n}\n\n/**\n * Applies only records of a given type from an array of diffs to a target diff. Returns the net\n * change in the number of entries in the target.\n *\n * @internal\n */\nexport function squashRecordDiffsMutableByType<\n\tT extends UnknownRecord,\n\tTypeName extends T['typeName'],\n>(\n\ttarget: RecordsDiff<Extract<T, { typeName: TypeName }>>,\n\tdiffs: RecordsDiff<T>[],\n\ttypeName: TypeName\n): number {\n\treturn squashRecordDiffsMutableImpl(target, diffs, 0, typeName)\n}\n\nfunction squashRecordDiffsMutableImpl<T extends UnknownRecord>(\n\ttarget: RecordsDiff<T>,\n\tdiffs: RecordsDiff<T>[],\n\tfromIndex: number,\n\ttypeName?: T['typeName']\n): number {\n\tlet sizeChange = 0\n\tconst trackSize = typeName !== undefined\n\n\t// This runs on every history interceptor call \u2014 e.g. once per input tick while\n\t// resizing N shapes, with N entries in diff.updated \u2014 so the updated loop must not\n\t// allocate per entry. We use for-in instead of Object.entries, mutate the target's\n\t// existing [from, to] tuples in place, and skip delete calls against collections we\n\t// know are empty. In-place tuple mutation is safe because the target exclusively\n\t// owns its updated tuples: they are always created here (never shared with a source\n\t// diff), and sources are never mutated.\n\tfor (let i = fromIndex; i < diffs.length; i++) {\n\t\tconst diff = diffs[i]\n\t\t// target.removed can only lose entries before the removed loop below, so a\n\t\t// stale `true` is harmless (extra no-op deletes).\n\t\tconst targetHasRemoved = hasAnyKey(target.removed)\n\n\t\tfor (const _id in diff.added) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\tconst value = diff.added[id]\n\t\t\tif (typeName !== undefined && value.typeName !== typeName) continue\n\t\t\tif (targetHasRemoved && target.removed[id]) {\n\t\t\t\tconst original = target.removed[id]\n\t\t\t\tdelete target.removed[id]\n\t\t\t\tif (trackSize) sizeChange--\n\t\t\t\tif (original !== value) {\n\t\t\t\t\ttarget.updated[id] = [original, value]\n\t\t\t\t\tif (trackSize) sizeChange++\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (trackSize && !target.added[id]) sizeChange++\n\t\t\t\ttarget.added[id] = value\n\t\t\t}\n\t\t}\n\n\t\t// the added loop above may have inserted into target.added\n\t\tconst targetHasAdded = hasAnyKey(target.added)\n\n\t\tfor (const _id in diff.updated) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\tconst to = diff.updated[id][1]\n\t\t\tif (typeName !== undefined && to.typeName !== typeName) continue\n\t\t\tif (targetHasAdded && target.added[id]) {\n\t\t\t\ttarget.added[id] = to\n\t\t\t\tif (trackSize && target.updated[id]) sizeChange--\n\t\t\t\tdelete target.updated[id]\n\t\t\t\tif (targetHasRemoved) {\n\t\t\t\t\tif (trackSize && target.removed[id]) sizeChange--\n\t\t\t\t\tdelete target.removed[id]\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst existing = target.updated[id]\n\t\t\tif (existing) {\n\t\t\t\texisting[1] = to\n\t\t\t\tif (targetHasRemoved) {\n\t\t\t\t\tif (trackSize && target.removed[id]) sizeChange--\n\t\t\t\t\tdelete target.removed[id]\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// copy the tuple so the target owns it and can mutate it in place later\n\t\t\ttarget.updated[id] = [diff.updated[id][0], to]\n\t\t\tif (trackSize) sizeChange++\n\t\t\tif (targetHasRemoved) {\n\t\t\t\tif (trackSize && target.removed[id]) sizeChange--\n\t\t\t\tdelete target.removed[id]\n\t\t\t}\n\t\t}\n\n\t\tfor (const _id in diff.removed) {\n\t\t\tconst id = _id as IdOf<T>\n\t\t\tif (typeName !== undefined && diff.removed[id].typeName !== typeName) continue\n\t\t\t// the same record was added in this diff sequence, just drop it\n\t\t\tif (target.added[id]) {\n\t\t\t\tdelete target.added[id]\n\t\t\t\tif (trackSize) sizeChange--\n\t\t\t} else if (target.updated[id]) {\n\t\t\t\ttarget.removed[id] = target.updated[id][0]\n\t\t\t\tdelete target.updated[id]\n\t\t\t} else {\n\t\t\t\tif (trackSize && !target.removed[id]) sizeChange++\n\t\t\t\ttarget.removed[id] = diff.removed[id]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn sizeChange\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAgC;AAkDzB,SAAS,yBAAkE;AACjF,SAAO,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC,EAAE;AAC9C;AA2BO,SAAS,mBAAmB,MAAwB;AAC1D,QAAM,SAA2B,EAAE,OAAO,KAAK,SAAS,SAAS,KAAK,OAAO,SAAS,CAAC,EAAE;AACzF,aAAW,CAAC,MAAM,EAAE,SAAK,8BAAgB,KAAK,OAAO,GAAG;AACvD,WAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,IAAI,IAAI;AAAA,EACpC;AACA,SAAO;AACR;AAuBO,SAAS,mBAA4C,MAAsB;AACjF,SAAO,CAAC,UAAU,KAAK,KAAK,KAAK,CAAC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,OAAO;AACN,YAAI,aAAa,CAAC,OAAO,QAAQ,EAAE,EAAG;AACtC,eAAO,QAAQ,EAAE,IAAI,KAAK,QAAQ,EAAE;AAAA,MACrC;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AACR;",
6
+ "names": ["result"]
7
7
  }
@@ -169,46 +169,35 @@ class Store {
169
169
  },
170
170
  { scheduleEffect: (cb) => this.cancelHistoryReactor = (0, import_utils.throttleToNextFrame)(cb) }
171
171
  );
172
- this.scopedTypes = {
173
- document: new Set(
174
- (0, import_utils.objectMapValues)(this.schema.types).filter((t) => t.scope === "document").map((t) => t.typeName)
175
- ),
176
- session: new Set(
177
- (0, import_utils.objectMapValues)(this.schema.types).filter((t) => t.scope === "session").map((t) => t.typeName)
178
- ),
179
- presence: new Set(
180
- (0, import_utils.objectMapValues)(this.schema.types).filter((t) => t.scope === "presence").map((t) => t.typeName)
181
- )
172
+ const scopedTypes = {
173
+ document: /* @__PURE__ */ new Set(),
174
+ session: /* @__PURE__ */ new Set(),
175
+ presence: /* @__PURE__ */ new Set()
182
176
  };
177
+ for (const type of (0, import_utils.objectMapValues)(this.schema.types)) {
178
+ scopedTypes[type.scope].add(type.typeName);
179
+ }
180
+ this.scopedTypes = scopedTypes;
183
181
  }
184
182
  _flushHistory() {
185
183
  if (this.historyAccumulator.hasChanges()) {
186
184
  const entries = this.historyAccumulator.flush();
187
185
  for (const { changes, source } of entries) {
188
- let instanceChanges = null;
189
- let documentChanges = null;
190
- let presenceChanges = null;
186
+ const scopedChanges = /* @__PURE__ */ new Map();
191
187
  for (const { onHistory, filters } of this.listeners) {
192
188
  if (filters.source !== "all" && filters.source !== source) {
193
189
  continue;
194
190
  }
195
- if (filters.scope !== "all") {
196
- if (filters.scope === "document") {
197
- documentChanges ??= this.filterChangesByScope(changes, "document");
198
- if (!documentChanges) continue;
199
- onHistory({ changes: documentChanges, source });
200
- } else if (filters.scope === "session") {
201
- instanceChanges ??= this.filterChangesByScope(changes, "session");
202
- if (!instanceChanges) continue;
203
- onHistory({ changes: instanceChanges, source });
204
- } else {
205
- presenceChanges ??= this.filterChangesByScope(changes, "presence");
206
- if (!presenceChanges) continue;
207
- onHistory({ changes: presenceChanges, source });
208
- }
209
- } else {
191
+ if (filters.scope === "all") {
210
192
  onHistory({ changes, source });
193
+ continue;
194
+ }
195
+ if (!scopedChanges.has(filters.scope)) {
196
+ scopedChanges.set(filters.scope, this.filterChangesByScope(changes, filters.scope));
211
197
  }
198
+ const filtered = scopedChanges.get(filters.scope);
199
+ if (!filtered) continue;
200
+ onHistory({ changes: filtered, source });
212
201
  }
213
202
  }
214
203
  }
@@ -228,7 +217,7 @@ class Store {
228
217
  updated: (0, import_utils.filterEntries)(change.updated, (_, r) => this.scopedTypes[scope].has(r[1].typeName)),
229
218
  removed: (0, import_utils.filterEntries)(change.removed, (_, r) => this.scopedTypes[scope].has(r.typeName))
230
219
  };
231
- if (!(0, import_RecordsDiff.hasAnyKey)(result.added) && !(0, import_RecordsDiff.hasAnyKey)(result.updated) && !(0, import_RecordsDiff.hasAnyKey)(result.removed)) {
220
+ if ((0, import_RecordsDiff.isRecordsDiffEmpty)(result)) {
232
221
  return null;
233
222
  }
234
223
  return result;