@dxos/echo 0.16.0 → 0.17.0

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 (176) hide show
  1. package/dist/lib/Annotation.mjs +2 -2
  2. package/dist/lib/Database.mjs +1 -1
  3. package/dist/lib/Error.mjs +1 -1
  4. package/dist/lib/Feed.mjs +1 -1
  5. package/dist/lib/Format.mjs +2 -2
  6. package/dist/lib/Migration.mjs +1 -1
  7. package/dist/lib/chunk-Annotation.mjs +14 -11
  8. package/dist/lib/chunk-Annotation.mjs.map +1 -1
  9. package/dist/lib/chunk-Blob.mjs +1 -1
  10. package/dist/lib/chunk-Collection.mjs +1 -1
  11. package/dist/lib/chunk-Database.mjs +93 -7
  12. package/dist/lib/chunk-Database.mjs.map +1 -1
  13. package/dist/lib/chunk-Dataset.mjs +1 -1
  14. package/dist/lib/chunk-Entity.mjs +2 -2
  15. package/dist/lib/chunk-Entity.mjs.map +1 -1
  16. package/dist/lib/chunk-Error.mjs +13 -1
  17. package/dist/lib/chunk-Error.mjs.map +1 -1
  18. package/dist/lib/chunk-Feed.mjs +311 -17
  19. package/dist/lib/chunk-Feed.mjs.map +1 -1
  20. package/dist/lib/chunk-Filter.mjs +4 -3
  21. package/dist/lib/chunk-Filter.mjs.map +1 -1
  22. package/dist/lib/chunk-Format.mjs +2 -1
  23. package/dist/lib/chunk-Hypergraph.mjs +1 -1
  24. package/dist/lib/chunk-Hypergraph.mjs.map +1 -1
  25. package/dist/lib/chunk-Migration.mjs +155 -5
  26. package/dist/lib/chunk-Migration.mjs.map +1 -1
  27. package/dist/lib/chunk-Obj.mjs +12 -5
  28. package/dist/lib/chunk-Obj.mjs.map +1 -1
  29. package/dist/lib/chunk-Query.mjs +2 -2
  30. package/dist/lib/chunk-QueryResult.mjs.map +1 -1
  31. package/dist/lib/chunk-Ref2.mjs +2 -2
  32. package/dist/lib/chunk-Registry.mjs +1 -1
  33. package/dist/lib/chunk-Registry.mjs.map +1 -1
  34. package/dist/lib/chunk-Relation.mjs +5 -5
  35. package/dist/lib/chunk-Relation.mjs.map +1 -1
  36. package/dist/lib/chunk-Scope.mjs +16 -2
  37. package/dist/lib/chunk-Scope.mjs.map +1 -1
  38. package/dist/lib/chunk-Tag.mjs +4 -4
  39. package/dist/lib/chunk-Tag.mjs.map +1 -1
  40. package/dist/lib/chunk-Text.mjs +2 -2
  41. package/dist/lib/chunk-Type.mjs +26 -7
  42. package/dist/lib/chunk-Type.mjs.map +1 -1
  43. package/dist/lib/chunk-View.mjs +1 -1
  44. package/dist/lib/chunk-atom-snapshot.mjs +29 -1
  45. package/dist/lib/chunk-atom-snapshot.mjs.map +1 -1
  46. package/dist/lib/chunk-entity-dictionary.mjs +28 -19
  47. package/dist/lib/chunk-entity-dictionary.mjs.map +1 -1
  48. package/dist/lib/chunk-internal.mjs +231 -79
  49. package/dist/lib/chunk-internal.mjs.map +1 -1
  50. package/dist/lib/chunk-json-schema.mjs +1 -1
  51. package/dist/lib/chunk-ref.mjs +38 -34
  52. package/dist/lib/chunk-ref.mjs.map +1 -1
  53. package/dist/lib/chunk-select.mjs +7 -3
  54. package/dist/lib/chunk-select.mjs.map +1 -1
  55. package/dist/lib/index.mjs +2 -2
  56. package/dist/lib/internal.mjs +6 -6
  57. package/dist/lib/testing.mjs +2 -2
  58. package/dist/lib/testing.mjs.map +1 -1
  59. package/dist/types/src/Annotation.d.ts +1 -1
  60. package/dist/types/src/Annotation.d.ts.map +1 -1
  61. package/dist/types/src/Database.d.ts +30 -13
  62. package/dist/types/src/Database.d.ts.map +1 -1
  63. package/dist/types/src/Entity.d.ts +3 -4
  64. package/dist/types/src/Entity.d.ts.map +1 -1
  65. package/dist/types/src/Error.d.ts +36 -0
  66. package/dist/types/src/Error.d.ts.map +1 -1
  67. package/dist/types/src/Feed.d.ts +261 -18
  68. package/dist/types/src/Feed.d.ts.map +1 -1
  69. package/dist/types/src/Filter.d.ts +7 -1
  70. package/dist/types/src/Filter.d.ts.map +1 -1
  71. package/dist/types/src/Hypergraph.d.ts +1 -1
  72. package/dist/types/src/Migration.d.ts +213 -2
  73. package/dist/types/src/Migration.d.ts.map +1 -1
  74. package/dist/types/src/Migration.test.d.ts +2 -0
  75. package/dist/types/src/Migration.test.d.ts.map +1 -0
  76. package/dist/types/src/Obj.d.ts +4 -4
  77. package/dist/types/src/Obj.d.ts.map +1 -1
  78. package/dist/types/src/QueryResult.d.ts +16 -0
  79. package/dist/types/src/QueryResult.d.ts.map +1 -1
  80. package/dist/types/src/Relation.d.ts +3 -4
  81. package/dist/types/src/Relation.d.ts.map +1 -1
  82. package/dist/types/src/Scope.d.ts +32 -1
  83. package/dist/types/src/Scope.d.ts.map +1 -1
  84. package/dist/types/src/Tag.d.ts.map +1 -1
  85. package/dist/types/src/Type.d.ts +27 -2
  86. package/dist/types/src/Type.d.ts.map +1 -1
  87. package/dist/types/src/internal/Annotation/annotations.d.ts +35 -1
  88. package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
  89. package/dist/types/src/internal/Annotation/atoms.d.ts +2 -2
  90. package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -1
  91. package/dist/types/src/internal/Entity/api.d.ts +11 -0
  92. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  93. package/dist/types/src/internal/Entity/model.d.ts +3 -2
  94. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  95. package/dist/types/src/internal/Format/string.d.ts +5 -1
  96. package/dist/types/src/internal/Format/string.d.ts.map +1 -1
  97. package/dist/types/src/internal/Obj/atoms.d.ts +1 -1
  98. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  99. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  100. package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
  101. package/dist/types/src/internal/Ref/ref.d.ts +5 -1
  102. package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
  103. package/dist/types/src/internal/Ref/strong-deps.d.ts +3 -1
  104. package/dist/types/src/internal/Ref/strong-deps.d.ts.map +1 -1
  105. package/dist/types/src/internal/common/api/meta.d.ts +4 -5
  106. package/dist/types/src/internal/common/api/meta.d.ts.map +1 -1
  107. package/dist/types/src/internal/common/atom-snapshot.d.ts +10 -0
  108. package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -1
  109. package/dist/types/src/internal/common/proxy/change-context.d.ts +4 -0
  110. package/dist/types/src/internal/common/proxy/change-context.d.ts.map +1 -1
  111. package/dist/types/src/internal/common/proxy/ownership.d.ts +5 -0
  112. package/dist/types/src/internal/common/proxy/ownership.d.ts.map +1 -1
  113. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
  114. package/dist/types/src/internal/common/proxy/schema-validator.d.ts +17 -2
  115. package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
  116. package/dist/types/src/internal/common/proxy/symbols.d.ts +10 -0
  117. package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
  118. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +0 -1
  119. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  120. package/dist/types/src/internal/common/types/meta.d.ts +8 -4
  121. package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
  122. package/dist/types/src/internal/common/types/model-symbols.d.ts +6 -0
  123. package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
  124. package/dist/types/src/internal/index.d.ts.map +1 -1
  125. package/dist/types/tsconfig.tsbuildinfo +1 -1
  126. package/package.json +19 -15
  127. package/src/Annotation.test.ts +34 -0
  128. package/src/Annotation.ts +3 -0
  129. package/src/Database.ts +46 -15
  130. package/src/Entity.ts +3 -4
  131. package/src/Error.ts +9 -0
  132. package/src/Feed.test.ts +160 -0
  133. package/src/Feed.ts +412 -29
  134. package/src/Filter.ts +8 -1
  135. package/src/Hypergraph.ts +1 -1
  136. package/src/Migration.test.ts +137 -0
  137. package/src/Migration.ts +376 -4
  138. package/src/Obj.test.ts +44 -4
  139. package/src/Obj.ts +19 -5
  140. package/src/QueryResult.ts +14 -0
  141. package/src/Relation.ts +3 -4
  142. package/src/Scope.ts +43 -1
  143. package/src/Tag.md +5 -6
  144. package/src/Tag.ts +3 -2
  145. package/src/Type.test.ts +52 -0
  146. package/src/Type.ts +75 -22
  147. package/src/Type.tst.ts +155 -0
  148. package/src/internal/Annotation/annotations.test.ts +19 -0
  149. package/src/internal/Annotation/annotations.ts +67 -1
  150. package/src/internal/Annotation/atoms.ts +10 -9
  151. package/src/internal/Entity/api.ts +20 -1
  152. package/src/internal/Entity/model.ts +3 -0
  153. package/src/internal/Filter/match.ts +2 -2
  154. package/src/internal/Format/string.ts +7 -2
  155. package/src/internal/JsonSchema/json-schema.test.ts +2 -2
  156. package/src/internal/Obj/atoms.ts +9 -5
  157. package/src/internal/Obj/json-serializer.test.ts +34 -7
  158. package/src/internal/Obj/json-serializer.ts +18 -3
  159. package/src/internal/Query/pretty.ts +3 -2
  160. package/src/internal/Ref/ref.test.ts +27 -2
  161. package/src/internal/Ref/ref.ts +18 -2
  162. package/src/internal/Ref/strong-deps.ts +21 -2
  163. package/src/internal/common/api/meta.ts +7 -8
  164. package/src/internal/common/atom-snapshot.ts +61 -0
  165. package/src/internal/common/proxy/change-context.ts +5 -0
  166. package/src/internal/common/proxy/change.test.ts +62 -31
  167. package/src/internal/common/proxy/json-serializer.ts +3 -2
  168. package/src/internal/common/proxy/ownership.ts +14 -1
  169. package/src/internal/common/proxy/proxy-utils.ts +7 -1
  170. package/src/internal/common/proxy/schema-validator.ts +116 -27
  171. package/src/internal/common/proxy/symbols.ts +12 -0
  172. package/src/internal/common/proxy/typed-handler.test.ts +43 -0
  173. package/src/internal/common/proxy/typed-handler.ts +105 -33
  174. package/src/internal/common/types/meta.ts +25 -20
  175. package/src/internal/common/types/model-symbols.ts +7 -0
  176. package/src/internal/index.ts +1 -2
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Migration.mjs","names":["Type.getSchema"],"sources":["../../src/Migration.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Schema from 'effect/Schema';\n\nimport { DXN, type URI } from '@dxos/keys';\n\nimport type * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport { type EntityMeta, MetaId, getSchemaURI } from './internal/index.ts';\nimport * as Type from './Type.ts';\n\nexport const TypeId = '~@dxos/echo/Migration' as const;\nexport type TypeId = typeof TypeId;\n\n/**\n * Base of every migration definition.\n */\nexport interface Migration {\n readonly [TypeId]: TypeId;\n readonly kind: 'object' | 'rename';\n}\n\n/**\n * Type guard for values produced by {@link define} / {@link defineRename}.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isMigration = (value: unknown): value is Migration => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const candidate = value as { [TypeId]?: unknown; kind?: unknown };\n // `kind` is checked too: a branded value carrying an unknown kind is not a migration any\n // consumer can dispatch on.\n return candidate[TypeId] === TypeId && (candidate.kind === 'object' || candidate.kind === 'rename');\n};\n\n/**\n * Result returned by a migration's `transform` callback.\n * The data shape matches the target schema; the optional `[Obj.Meta]` symbol key lets the\n * transform update the object's meta (e.g. `key` / `version`) atomically with the data swap.\n */\ntype MigrationSchemaInput = Type.AnyEntity;\n\ntype MigrationInstanceType<S extends MigrationSchemaInput> = Type.InstanceType<S>;\n\nexport type TransformResult<To extends MigrationSchemaInput> = Omit<MigrationInstanceType<To>, 'id' | Entity.KindId> & {\n [MetaId]?: Partial<EntityMeta>;\n};\n\ntype DefineObjectMigrationOptions<From extends MigrationSchemaInput, To extends MigrationSchemaInput> = {\n from: From;\n to: To;\n /**\n * Pure function that converts the old object data to the new object data.\n *\n * The returned object may include an optional `[Obj.Meta]` entry to update the object's meta\n * (e.g. registry `key` / `version`) atomically with the data swap.\n */\n // TODO(dmaretskyi): `id` should not be a part of the schema.\n transform: (from: MigrationInstanceType<From>, context: ObjectMigrationContext) => Promise<TransformResult<To>>;\n\n /**\n * Callback that is called after the object is migrated. Called for every object that is migrated.\n *\n * NOTE: Database mutations performed in this callback are not guaranteed to be idempotent.\n * If multiple peers run the migration separately, the effects may be applied multiple times.\n */\n onMigration?: (params: OnMigrateProps<From, To>) => Promise<void>;\n};\n\n/**\n * Context passed to object migration callbacks.\n */\nexport type ObjectMigrationContext = {\n db: Database.Database;\n};\n\ntype OnMigrateProps<From extends MigrationSchemaInput, To extends MigrationSchemaInput> = {\n before: MigrationInstanceType<From>;\n object: MigrationInstanceType<To>;\n db: Database.Database;\n};\n\n/**\n * Definition of a migration from one object schema version to another.\n */\nexport interface ObjectMigration extends Migration {\n readonly kind: 'object';\n fromType: URI.URI;\n toType: URI.URI;\n fromSchema: Schema.Codec<any, any>;\n toSchema: Schema.Codec<any, any>;\n transform: (from: unknown, context: ObjectMigrationContext) => Promise<unknown>;\n onMigration?: (params: OnMigrateProps<any, any>) => Promise<void>;\n}\n\n/**\n * Narrows a migration to an {@link ObjectMigration}.\n *\n * @performance O(1).\n */\nexport const isObjectMigration = (migration: Migration): migration is ObjectMigration => migration.kind === 'object';\n\n/**\n * Define a migration between two object schemas.\n *\n * @example\n * ```ts\n * const migration = Migration.define({\n * from: ContactV1,\n * to: ContactV2,\n * transform: async (from) => ({ name: `${from.firstName} ${from.lastName}` }),\n * onMigration: async () => {},\n * });\n * ```\n *\n * @performance O(1) at definition time; reads both schema URIs.\n */\nexport const define = <From extends MigrationSchemaInput, To extends MigrationSchemaInput>(\n options: DefineObjectMigrationOptions<From, To>,\n): ObjectMigration => {\n const fromSchema = Type.getSchema(options.from);\n const toSchema = Type.getSchema(options.to);\n const fromType = getSchemaURI(fromSchema);\n if (!fromType) {\n throw new Error('Invalid from schema');\n }\n const toType = getSchemaURI(toSchema);\n if (!toType) {\n throw new Error('Invalid to schema');\n }\n\n return {\n [TypeId]: TypeId,\n kind: 'object',\n fromType,\n toType,\n fromSchema,\n toSchema,\n transform: options.transform as any,\n onMigration: options.onMigration as any,\n };\n};\n\n/**\n * Compile-time validation of an NSID passed to {@link defineRename}, mirroring `DXN.make`.\n */\ntype ValidName<T extends string> = [DXN.Name<T>] extends [never]\n ? `Invalid NSID \"${T}\": final segment must be camelCase (no hyphens)`\n : T;\n\n/**\n * Definition of a rename of a named entity, repointing every `dxn:` reference to the old name.\n */\nexport interface RenameMigration extends Migration {\n readonly kind: 'rename';\n\n /** DXN of the old name (unversioned). */\n from: DXN.DXN;\n\n /** DXN of the new name (unversioned). */\n to: DXN.DXN;\n}\n\n/**\n * Narrows a migration to a {@link RenameMigration}.\n *\n * @performance O(1).\n */\nexport const isRenameMigration = (migration: Migration): migration is RenameMigration => migration.kind === 'rename';\n\n/**\n * Define a migration that renames a named entity.\n *\n * Applying it rewrites every reference pointing at `from` to point at `to`, preserving the\n * reference's version suffix. Idempotent: a reference that already reads correctly is not written.\n *\n * @example\n * ```ts\n * const migration = Migration.defineRename({\n * from: 'org.example.operation.foo',\n * to: 'org.example.operation.bar',\n * });\n * ```\n *\n * @performance O(1) at definition time.\n */\nexport const defineRename = <const From extends string, const To extends string>(options: {\n from: ValidName<From>;\n to: ValidName<To>;\n}): RenameMigration => ({\n [TypeId]: TypeId,\n kind: 'rename',\n from: DXN.make<string>(options.from),\n to: DXN.make<string>(options.to),\n});\n"],"mappings":";;;;;;;;;;;;;AAeA,IAAa,SAAS;;;;;;AAgBtB,IAAa,eAAe,UAAuC;CACjE,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,YAAY;CAGlB,OAAO,UAAA,6BAAA,4BAAiC,UAAU,SAAS,YAAY,UAAU,SAAS;AAC5F;;;;;;AAmEA,IAAa,qBAAqB,cAAuD,UAAU,SAAS;;;;;;;;;;;;;;;;AAiB5G,IAAa,UACX,YACoB;CACpB,MAAM,aAAaA,UAAe,QAAQ,IAAI;CAC9C,MAAM,WAAWA,UAAe,QAAQ,EAAE;CAC1C,MAAM,WAAW,aAAa,UAAU;CACxC,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,qBAAqB;CAEvC,MAAM,SAAS,aAAa,QAAQ;CACpC,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,mBAAmB;CAGrC,OAAO;GACJ,SAAS;EACV,MAAM;EACN;EACA;EACA;EACA;EACA,WAAW,QAAQ;EACnB,aAAa,QAAQ;CACvB;AACF;;;;;;AA2BA,IAAa,qBAAqB,cAAuD,UAAU,SAAS;;;;;;;;;;;;;;;;;AAkB5G,IAAa,gBAAoE,aAGzD;EACrB,SAAS;CACV,MAAM;CACN,MAAM,IAAI,KAAa,QAAQ,IAAI;CACnC,IAAI,IAAI,KAAa,QAAQ,EAAE;AACjC"}
1
+ {"version":3,"file":"chunk-Migration.mjs","names":["Type.getSchema"],"sources":["../../src/Migration.ts"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\n// @import-as-namespace\n\nimport type * as Effect from 'effect/Effect';\nimport * as Option from 'effect/Option';\nimport type * as Schema from 'effect/Schema';\n\nimport * as SchemaAST from '@dxos/effect/SchemaAST';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { DXN, type URI } from '@dxos/keys';\n\nimport type * as Database from './Database.ts';\nimport type * as Entity from './Entity.ts';\nimport type * as EchoError from './Error.ts';\nimport { ContentVersionAnnotation, type EntityMeta, MetaId, getSchemaURI } from './internal/index.ts';\nimport type * as Obj from './Obj.ts';\nimport * as Type from './Type.ts';\n\nexport const TypeId = '~@dxos/echo/Migration' as const;\nexport type TypeId = typeof TypeId;\n\n/**\n * Base of every migration definition.\n */\nexport interface Migration {\n readonly [TypeId]: TypeId;\n readonly kind: 'object' | 'rename' | 'content' | 'transaction';\n}\n\n/**\n * Type guard for values produced by {@link define} / {@link defineRename} / {@link defineContent}.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isMigration = (value: unknown): value is Migration => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const candidate = value as { [TypeId]?: unknown; kind?: unknown };\n // `kind` is checked too: a branded value carrying an unknown kind is not a migration any\n // consumer can dispatch on.\n return (\n candidate[TypeId] === TypeId &&\n (candidate.kind === 'object' ||\n candidate.kind === 'rename' ||\n candidate.kind === 'content' ||\n candidate.kind === 'transaction')\n );\n};\n\n/**\n * Result returned by a migration's `transform` callback.\n * The data shape matches the target schema; the optional `[Obj.Meta]` symbol key lets the\n * transform update the object's meta (e.g. `key` / `version`) atomically with the data swap.\n */\ntype MigrationSchemaInput = Type.AnyEntity;\n\ntype MigrationInstanceType<S extends MigrationSchemaInput> = Type.InstanceType<S>;\n\nexport type TransformResult<To extends MigrationSchemaInput> = Omit<MigrationInstanceType<To>, 'id' | Entity.KindId> & {\n [MetaId]?: Partial<EntityMeta>;\n};\n\ntype DefineObjectMigrationOptions<From extends MigrationSchemaInput, To extends MigrationSchemaInput> = {\n from: From;\n to: To;\n /**\n * Pure function that converts the old object data to the new object data.\n *\n * The returned object may include an optional `[Obj.Meta]` entry to update the object's meta\n * (e.g. registry `key` / `version`) atomically with the data swap.\n */\n // TODO(dmaretskyi): `id` should not be a part of the schema.\n transform: (from: MigrationInstanceType<From>, context: ObjectMigrationContext) => Promise<TransformResult<To>>;\n\n /**\n * Callback that is called after the object is migrated. Called for every object that is migrated.\n *\n * NOTE: Database mutations performed in this callback are not guaranteed to be idempotent.\n * If multiple peers run the migration separately, the effects may be applied multiple times.\n */\n onMigration?: (params: OnMigrateProps<From, To>) => Promise<void>;\n};\n\n/**\n * Context passed to object migration callbacks.\n */\nexport type ObjectMigrationContext = {\n db: Database.Database;\n};\n\ntype OnMigrateProps<From extends MigrationSchemaInput, To extends MigrationSchemaInput> = {\n before: MigrationInstanceType<From>;\n object: MigrationInstanceType<To>;\n db: Database.Database;\n};\n\n/**\n * Definition of a migration from one object schema version to another.\n */\nexport interface ObjectMigration extends Migration {\n readonly kind: 'object';\n fromType: URI.URI;\n toType: URI.URI;\n fromSchema: Schema.Codec<any, any>;\n toSchema: Schema.Codec<any, any>;\n transform: (from: unknown, context: ObjectMigrationContext) => Promise<unknown>;\n onMigration?: (params: OnMigrateProps<any, any>) => Promise<void>;\n}\n\n/**\n * Narrows a migration to an {@link ObjectMigration}.\n *\n * @performance O(1).\n */\nexport const isObjectMigration = (migration: Migration): migration is ObjectMigration => migration.kind === 'object';\n\n/**\n * Define a migration between two object schemas.\n *\n * @example\n * ```ts\n * const migration = Migration.define({\n * from: ContactV1,\n * to: ContactV2,\n * transform: async (from) => ({ name: `${from.firstName} ${from.lastName}` }),\n * onMigration: async () => {},\n * });\n * ```\n *\n * @performance O(1) at definition time; reads both schema URIs.\n */\nexport const define = <From extends MigrationSchemaInput, To extends MigrationSchemaInput>(\n options: DefineObjectMigrationOptions<From, To>,\n): ObjectMigration => {\n const fromSchema = Type.getSchema(options.from);\n const toSchema = Type.getSchema(options.to);\n const fromType = getSchemaURI(fromSchema);\n if (!fromType) {\n throw new Error('Invalid from schema');\n }\n const toType = getSchemaURI(toSchema);\n if (!toType) {\n throw new Error('Invalid to schema');\n }\n\n return {\n [TypeId]: TypeId,\n kind: 'object',\n fromType,\n toType,\n fromSchema,\n toSchema,\n transform: options.transform as any,\n onMigration: options.onMigration as any,\n };\n};\n\n/**\n * Compile-time validation of an NSID passed to {@link defineRename}, mirroring `DXN.make`.\n */\ntype ValidName<T extends string> = [DXN.Name<T>] extends [never]\n ? `Invalid NSID \"${T}\": final segment must be camelCase (no hyphens)`\n : T;\n\n/**\n * Definition of a rename of a named entity, repointing every `dxn:` reference to the old name.\n */\nexport interface RenameMigration extends Migration {\n readonly kind: 'rename';\n\n /** DXN of the old name (unversioned). */\n from: DXN.DXN;\n\n /** DXN of the new name (unversioned). */\n to: DXN.DXN;\n}\n\n/**\n * Narrows a migration to a {@link RenameMigration}.\n *\n * @performance O(1).\n */\nexport const isRenameMigration = (migration: Migration): migration is RenameMigration => migration.kind === 'rename';\n\n/**\n * Define a migration that renames a named entity.\n *\n * Applying it rewrites every reference pointing at `from` to point at `to`, preserving the\n * reference's version suffix. Idempotent: a reference that already reads correctly is not written.\n *\n * @example\n * ```ts\n * const migration = Migration.defineRename({\n * from: 'org.example.operation.foo',\n * to: 'org.example.operation.bar',\n * });\n * ```\n *\n * @performance O(1) at definition time.\n */\nexport const defineRename = <const From extends string, const To extends string>(options: {\n from: ValidName<From>;\n to: ValidName<To>;\n}): RenameMigration => ({\n [TypeId]: TypeId,\n kind: 'rename',\n from: DXN.make<string>(options.from),\n to: DXN.make<string>(options.to),\n});\n\n/**\n * Values of the content fields a {@link ContentVersionAnnotation} names, keyed by field name.\n * A field absent from the object is absent here.\n */\nexport type Content = Readonly<Record<string, unknown>>;\n\n/**\n * Definition of one step of a content format: upgrades the fields a type's\n * {@link ContentVersionAnnotation} names from content version `from` to `to`.\n */\nexport interface ContentMigration extends Migration {\n readonly kind: 'content';\n\n /** URI of the object type whose content this step upgrades. */\n readonly type: URI.URI;\n\n /** The string field holding the content version. */\n readonly versionField: string;\n\n /** The content fields the version describes. */\n readonly fields: readonly string[];\n\n /** Content fields declared as records, which the runner writes key by key. */\n readonly recordFields: readonly string[];\n\n /** Content version this step reads. */\n readonly from: string;\n\n /** Content version this step writes. */\n readonly to: string;\n\n /** Release that first ships this step, which decides when it can be deleted. */\n readonly since: string;\n\n /** Pure, deterministic upgrade of the content fields. */\n readonly transform: (content: Content) => Content;\n}\n\ntype DefineContentMigrationOptions<S extends MigrationSchemaInput> = {\n /** Object type whose schema carries a {@link ContentVersionAnnotation}. */\n type: S;\n from: string;\n to: string;\n since: string;\n /**\n * Returns the new values of the content fields. Must be pure and deterministic: peers migrating\n * the same object concurrently must write identical values for their changes to merge.\n */\n transform: (content: Content) => Content;\n};\n\n/**\n * Narrows a migration to a {@link ContentMigration}.\n *\n * @performance O(1).\n */\nexport const isContentMigration = (migration: Migration): migration is ContentMigration => migration.kind === 'content';\n\ntype ContentVersionField = { readonly field: string; readonly fields: readonly string[] };\n\n/** The field a schema's {@link ContentVersionAnnotation} marks, with the fields it versions. */\nconst getContentVersionField = (ast: SchemaAST.AST): ContentVersionField | undefined => {\n for (const property of SchemaAST.getPropertySignatures(ast)) {\n if (typeof property.name !== 'string') {\n continue;\n }\n // Optionality wraps the annotated schema in a union.\n const value = Option.getOrUndefined(\n Option.orElse(ContentVersionAnnotation.getFromAst(property.type), () =>\n ContentVersionAnnotation.getFromAst(SchemaEx.unwrapOptional(property.type)),\n ),\n );\n if (value) {\n return { field: property.name, fields: value.fields };\n }\n }\n return undefined;\n};\n\nconst isRecordAst = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isObjects(ast) && ast.propertySignatures.length === 0 && ast.indexSignatures.length > 0;\n\n/**\n * Define one step of a content format carried by an object type.\n *\n * The type's schema must mark its version field with {@link ContentVersionAnnotation}. Steps chain\n * by version: an object at `from` is upgraded through every step reachable from it.\n *\n * @example\n * ```ts\n * const sceneParams = Migration.defineContent({\n * type: Drawing.Canvas,\n * from: 'dxos.org/scene/1',\n * to: 'dxos.org/scene/2',\n * since: '0.11.0',\n * transform: ({ content }) => ({ content: upgradeRecords(content) }),\n * });\n * ```\n *\n * @performance O(fields) at definition time; walks the schema's top-level properties.\n */\nexport const defineContent = <S extends MigrationSchemaInput>(\n options: DefineContentMigrationOptions<S>,\n): ContentMigration => {\n const schema = Type.getSchema(options.type);\n const type = getSchemaURI(schema);\n if (!type) {\n throw new Error('Invalid type schema');\n }\n const version = getContentVersionField(schema.ast);\n if (!version) {\n throw new Error(`Type has no ContentVersionAnnotation: ${type}`);\n }\n if (options.from.length === 0 || options.to.length === 0 || options.from === options.to) {\n throw new Error(`Invalid content versions: ${options.from} -> ${options.to}`);\n }\n\n const properties = new Map(\n SchemaAST.getPropertySignatures(schema.ast).map((property) => [String(property.name), property]),\n );\n const recordFields = version.fields.filter((field) => {\n const property = properties.get(field);\n if (!property) {\n throw new Error(`ContentVersionAnnotation names an unknown field: ${field}`);\n }\n return isRecordAst(SchemaEx.unwrapOptional(property.type));\n });\n\n return {\n [TypeId]: TypeId,\n kind: 'content',\n type,\n versionField: version.field,\n fields: version.fields,\n recordFields,\n from: options.from,\n to: options.to,\n since: options.since,\n transform: options.transform,\n };\n};\n\n/**\n * The content steps of `type` keyed by `from`.\n *\n * @throws When two steps start at the same version, since the chain would be ambiguous.\n */\nexport const getContentSteps = (\n migrations: readonly Migration[],\n type: URI.URI,\n): ReadonlyMap<string, ContentMigration> => {\n const steps = new Map<string, ContentMigration>();\n for (const migration of migrations) {\n if (!isContentMigration(migration) || migration.type !== type) {\n continue;\n }\n const existing = steps.get(migration.from);\n if (existing && existing !== migration) {\n throw new Error(`Ambiguous content migrations from ${migration.from}: ${existing.to}, ${migration.to}`);\n }\n steps.set(migration.from, migration);\n }\n return steps;\n};\n\n/** Result of {@link upgradeContent}. */\nexport type UpgradedContent = {\n readonly version: string | undefined;\n readonly content: Content;\n};\n\n/**\n * Upgrades content in memory through the chain of content steps declared for `type`, from `version`\n * to the newest version reachable. Readers use it for data that synced in before the migration pass\n * ran; the pass itself applies the same chain. Content at a version no step starts from is\n * returned as it is (same reference).\n *\n * @performance O(steps) transforms; each costs what its `transform` does.\n */\nexport const upgradeContent = (\n migrations: readonly Migration[],\n type: MigrationSchemaInput | URI.URI,\n version: string | undefined,\n content: Content,\n): UpgradedContent => {\n const uri = typeof type === 'string' ? type : getSchemaURI(Type.getSchema(type));\n if (!uri || version === undefined) {\n return { version, content };\n }\n return applyContentSteps(getContentSteps(migrations, uri), version, content);\n};\n\n/**\n * Applies the chain of `steps` starting at `version`.\n *\n * @throws When the chain loops back to a version it already passed.\n */\nexport const applyContentSteps = (\n steps: ReadonlyMap<string, ContentMigration>,\n version: string,\n content: Content,\n): UpgradedContent => {\n const visited = new Set<string>([version]);\n let current = version;\n let result = content;\n for (let step = steps.get(current); step; step = steps.get(current)) {\n result = step.transform(result);\n current = step.to;\n if (visited.has(current)) {\n throw new Error(`Content migrations loop at ${current}`);\n }\n visited.add(current);\n }\n return { version: current, content: result };\n};\n\n//\n// Transaction\n//\n\n/**\n * Result of {@link Transaction.compact}.\n */\nexport type CompactResult = {\n /** Objects whose documents will be rewritten without history. */\n readonly compacted: readonly Obj.ID[];\n /** Requested objects not stored in a document of their own. */\n readonly skipped: readonly Obj.ID[];\n};\n\n/**\n * Options for {@link Transaction}.\n */\nexport type TransactionOptions = {\n /**\n * How {@link Transaction.commit} publishes the staged changes.\n * - `replace` (default): builds a new space root and starts a new epoch with it. Peers adopt the new\n * root, so writes made to the old root after the transaction began are lost.\n * - `update`: writes the changed links and inline objects into the current root in one atomic change.\n * No epoch is started, and concurrent writes to the root merge.\n */\n root?: 'replace' | 'update';\n};\n\n/**\n * Structural changes to a database, staged and then committed atomically.\n *\n * Staged changes are not visible to queries until {@link Transaction.commit}. Use it for changes that\n * an ordinary write cannot express: changing an object's type in place, removing objects without a\n * tombstone, or dropping document history. For schema changes that a write can express, prefer\n * {@link define}. Run it with `db.runMigrations` through {@link defineTransaction}, or directly:\n *\n * @example\n * ```ts\n * const migration = await space.db.beginMigration();\n * yield* migration.migrate(contact.id, (json) => Obj.make(ContactV2, { id: json.id, name: String(json.name) }));\n * migration.add(Obj.make(Note, { title: 'Imported' }));\n * migration.delete(legacy.id);\n * yield* migration.commit();\n * ```\n */\nexport interface Transaction {\n /**\n * The staged state of an object: what earlier calls in this transaction left, else what is stored.\n * None for an object that is not stored or that this transaction deletes.\n */\n get(id: Obj.ID): Effect.Effect<Option.Option<Obj.JSON>, EchoError.MigrationError>;\n\n /**\n * Stages a new object, with every object it references that is not stored yet.\n * The object is not bound to the database: query it after {@link commit}.\n */\n add(object: Obj.Unknown): void;\n\n /**\n * Stages `object` in place of the stored object with the same id, replacing its type, data and meta.\n * The object's document keeps its history, so concurrent edits from peers still merge.\n *\n * @throws When no object with that id is stored.\n */\n replace(object: Obj.Unknown): void;\n\n /**\n * Reads the staged state of an object and stages the object `transform` returns in its place.\n * The returned object must keep the id. Does nothing for an object that is not stored.\n *\n * @returns Whether the object was found.\n */\n migrate<E = never, R = never>(\n id: Obj.ID,\n transform: (current: Obj.JSON) => Obj.Unknown | Effect.Effect<Obj.Unknown, E, R>,\n ): Effect.Effect<boolean, E | EchoError.MigrationError, R>;\n\n /**\n * Stages removing an object from the space. The object leaves no tombstone.\n */\n delete(id: Obj.ID): void;\n\n /**\n * Stages rewriting the documents of the given objects (default: every object stored in a document\n * of its own) without their history.\n */\n compact(ids?: readonly Obj.ID[]): CompactResult;\n\n /**\n * Writes the staged changes as {@link TransactionOptions.root} selects.\n * The transaction cannot be used afterwards.\n */\n commit(): Effect.Effect<void, EchoError.MigrationError>;\n}\n\n/**\n * Context passed to a {@link TransactionMigration}.\n */\nexport type TransactionMigrationContext = {\n /** The database being migrated, for queries; writes go through the transaction. */\n db: Database.Database;\n};\n\n/**\n * A migration that stages its changes in a {@link Transaction}, which the runner commits once `run` succeeds.\n */\nexport interface TransactionMigration extends Migration {\n readonly kind: 'transaction';\n readonly options: TransactionOptions;\n readonly run: (transaction: Transaction, context: TransactionMigrationContext) => Effect.Effect<void, unknown>;\n}\n\n/**\n * Narrows a migration to a {@link TransactionMigration}.\n *\n * @performance O(1).\n */\nexport const isTransactionMigration = (migration: Migration): migration is TransactionMigration =>\n migration.kind === 'transaction';\n\n/**\n * Define a migration that stages structural changes in a {@link Transaction}.\n * A failure of `run` rejects `db.runMigrations` and commits nothing.\n *\n * @example\n * ```ts\n * const migration = Migration.defineTransaction((transaction) =>\n * Effect.sync(() => transaction.delete(legacyId)),\n * );\n * await db.runMigrations([migration]);\n * ```\n *\n * @performance O(1) at definition time.\n */\nexport const defineTransaction = <E>(\n run: (transaction: Transaction, context: TransactionMigrationContext) => Effect.Effect<void, E>,\n options: TransactionOptions = {},\n): TransactionMigration => ({\n [TypeId]: TypeId,\n kind: 'transaction',\n options,\n run,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAa,SAAS;;;;;;AAgBtB,IAAa,eAAe,UAAuC;CACjE,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,YAAY;CAGlB,OACE,UAAA,6BAAA,4BACC,UAAU,SAAS,YAClB,UAAU,SAA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YACoB;CACpB,MAAM,MAAM,OAAO,SAAS,WAAW,OAAO,aAAaA,UAAe,IAAI,CAAC;CAC/E,IAAI,CAAC,OAAO,YAAY,KAAA,GACtB,OAAO;EAAE;EAAS;CAAQ;CAE5B,OAAO,kBAAkB,gBAAgB,YAAY,GAAG,GAAG,SAAS,OAAO;AAC7E;;;;;;AAOA,IAAa,qBACX,OACA,SACA,YACoB;CACpB,MAAM,0BAAU,IAAI,IAAY,CAAC,OAAO,CAAC;CACzC,IAAI,UAAU;CACd,IAAI,SAAS;CACb,KAAK,IAAI,OAAO,MAAM,IAAI,OAAO,GAAG,MAAM,OAAO,MAAM,IAAI,OAAO,GAAG;EACnE,SAAS,KAAK,UAAU,MAAM;EAC9B,UAAU,KAAK;EACf,IAAI,QAAQ,IAAI,OAAO,GACrB,MAAM,IAAI,MAAM,8BAA8B,SAAS;EAEzD,QAAQ,IAAI,OAAO;CACrB;CACA,OAAO;EAAE,SAAS;EAAS,SAAS;CAAO;AAC7C;;;;;;AAuHA,IAAa,0BAA0B,cACrC,UAAU,SAAS;;;;;;;;;;;;;;;AAgBrB,IAAa,qBACX,KACA,UAA8B,CAAC,OACL;EACzB,SAAS;CACV,MAAM;CACN;CACA;AACF"}
@@ -1,10 +1,10 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { a as addTag$1, c as getMetaChecked, l as removeTag$1, o as deleteKeys$1, s as getKeys$1 } from "./chunk-entity-dictionary.mjs";
3
- import { A as objectToJSON, At as VersionTypeId$1, D as objectFromJSON, Dt as sort$1, F as encodeVersion$1, I as isVersion$1, L as version$1, N as compareVersions$1, Ot as sortByLabel$1, P as decodeVersion$1, R as versionValid$1, Y as makeObject, _ as propagateParentAnnotations, d as makeProperty, g as setValue$1, h as getSnapshot$1, kt as sortByTypename$1, l as makeLabelAtom, m as makeWithReactive, o as clone$1, p as makeTagsAtom, s as makeAtom, u as makeParentAtom, v as isDeleted$1 } from "./chunk-internal.mjs";
3
+ import { A as objectToJSON, At as sort$1, D as objectFromJSON, F as encodeVersion$1, I as isVersion$1, L as version$1, Mt as sortByTypename$1, N as compareVersions$1, Nt as VersionTypeId$1, P as decodeVersion$1, R as versionValid$1, Y as makeObject, _ as propagateParentAnnotations, d as makeProperty, g as setValue$1, gt as queueOwnerNotification, h as getSnapshot$1, jt as sortByLabel$1, l as makeLabelAtom, m as makeWithReactive, mt as isInChangeContext, o as clone$1, p as makeTagsAtom, pt as isAnyChangeContextActive, s as makeAtom, u as makeParentAtom, v as isDeleted$1 } from "./chunk-internal.mjs";
4
4
  import { a as ANY_OBJECT_VERSION, i as ANY_OBJECT_TYPENAME } from "./chunk-util.mjs";
5
- import { A as isInstanceOf, At as getTypeAnnotation, Ct as getLabel$1, Ft as setDescription$1, Ht as ParentId, Jt as getType$1, Lt as setLabel$1, M as getDatabase$1, Mt as getTypeURI$1, N as getUri, Nt as getTypename$1, St as getIcon$1, ft as TypeAnnotationId, j as getBranch$1, nn as MetaId, vt as getDescription$1, wt as getLabelProperty } from "./chunk-Database.mjs";
5
+ import { At as getIcon$1, Bt as getTypeURI$1, Et as getDescription$1, F as getUri, Kt as setLabel$1, M as getBranch$1, Mt as getLabelProperty, N as getDatabase$1, Rt as getTypeAnnotation, Vt as getTypename$1, Wt as setDescription$1, Zt as ParentId, fn as MetaId, j as isInstanceOf, jt as getLabel$1, rn as getType$1, yt as TypeAnnotationId } from "./chunk-Database.mjs";
6
+ import { L as ChangeKeyId, T as isProxy, v as change, w as getProxyTarget, y as subscribe$1 } from "./chunk-ref.mjs";
6
7
  import { o as GetReactiveError } from "./chunk-Error.mjs";
7
- import { D as getProxyTarget, O as isProxy, v as change, y as subscribe$1 } from "./chunk-ref.mjs";
8
8
  import { d as getSchema } from "./chunk-Type.mjs";
9
9
  import { n as Kind, o as SnapshotKindId, r as KindId } from "./chunk-Entity.mjs";
10
10
  import { c as isRef } from "./chunk-Ref2.mjs";
@@ -535,7 +535,7 @@ var deleteKeys = (entity, source) => deleteKeys$1(entity, source);
535
535
  * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`
536
536
  * parameters, so there is no compile-time error. Enforcement is runtime-only.
537
537
  *
538
- * @performance O(t) in the tag count; dedupes by ref URI before appending.
538
+ * @performance O(t) in the tag count; dedupes by tag id before appending.
539
539
  */
540
540
  var addTag = (entity, tag) => addTag$1(entity, tag);
541
541
  /**
@@ -671,7 +671,14 @@ var setParent = (entity, parent) => {
671
671
  });
672
672
  assumeType(entity);
673
673
  assumeType(parent);
674
- entity[ParentId] = parent;
674
+ if (isAnyChangeContextActive()) {
675
+ entity[ParentId] = parent;
676
+ const changeKey = Reflect.get(entity, ChangeKeyId);
677
+ if (changeKey === void 0 || !isInChangeContext(changeKey)) queueOwnerNotification(entity);
678
+ } else change(entity, (mutable) => {
679
+ assumeType(mutable);
680
+ mutable[ParentId] = parent;
681
+ });
675
682
  return entity;
676
683
  };
677
684
  var valuesEqual = (left, right) => {
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Obj.mjs","names":["internal.TypeAnnotationId","internal.ANY_OBJECT_TYPENAME","internal.ANY_OBJECT_VERSION","Type.getSchema","internal.getTypeAnnotation","internal.MetaId","internal.makeObject","Entity.KindId","Entity.SnapshotKindId","internal.subscribe","objInternal.getSnapshot","internal.getDatabase","Error.GetReactiveError","objInternal.clone","objInternal.setValue","internal.isInstanceOf","internal.getUri","internal.getTypeURI","internal.getType","internal.getTypename","internal.getBranch","internal.getMetaChecked","internal.getKeys","internal.deleteKeys","internal.addTag","internal.removeTag","objInternal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.getIcon","internal.setDescription","internal.ParentId","Ref.isRef","objInternal.objectToJSON","objInternal.objectFromJSON","internal.sortByLabel","internal.sortByTypename","internal.sort","internal.VersionTypeId","internal.isVersion","internal.versionValid","internal.compareVersions","internal.encodeVersion","internal.decodeVersion","internal.version","objInternal.makeAtom","objInternal.makeWithReactive","objInternal.makeProperty","objInternal.makeLabelAtom","objInternal.makeTagsAtom","internal.getLabelProperty","objInternal.makeParentAtom"],"sources":["../../src/Obj.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Exit from 'effect/Exit';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { assumeType, deepMapValues } from '@dxos/util';\n\nimport type * as Change from './Change.ts';\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport * as Error from './Error.ts';\nimport { getProxyTarget, isProxy } from './internal/common/proxy/proxy-utils.ts';\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport * as Ref from './Ref.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\n/**\n * Base type for all ECHO objects.\n */\ninterface BaseObj extends internal.AnyEntity, Entity.OfKind<typeof Entity.Kind.Object> {}\n\n/**\n * Object type with specific properties.\n */\nexport type OfShape<Props> = BaseObj & Props;\n\n/**\n * Object with no known properties beyond id and kind.\n * Use this when the object's schema/properties are not known.\n * For objects with arbitrary properties, use `Obj.AnyProps`.\n *\n * NOTE: This is a TypeScript type only, not a schema.\n * To validate that a value is an ECHO object, use `Schema.is(Type.Obj)`.\n */\nexport interface Unknown extends BaseObj {}\n\n/**\n * Runtime Effect schema for any ECHO object.\n * Use for validation, parsing, or as a reference target for collections.\n *\n * NOTE: `Schema.is(Type.Obj)` does STRUCTURAL validation only (checks for `id` field).\n * Use `Obj.isObject()` for proper ECHO instance type guards that check the KindId brand.\n *\n * @example\n * ```ts\n * // Structural type guard (accepts any object with id field)\n * if (Schema.is(Type.Obj)(unknownValue)) { ... }\n *\n * // ECHO instance type guard (checks KindId brand)\n * if (Obj.isObject(unknownValue)) { ... }\n *\n * // Reference to any object type\n * class Collection extends Type.makeObject<Collection>(DXN.make('com.example.type.collection', '0.1.0'))(\n * Schema.Struct({ objects: Schema.Array(Ref.Ref(Obj.Unknown)) }),\n * ) {}\n * ```\n */\n// TODO(wittjosiah): Investigate if Schema.filter can validate KindId on ECHO instances.\n// Effect Schema normalizes proxy objects to plain objects before calling filter predicates.\n// Possible approaches: custom Schema.declare, AST manipulation, or upstream contribution.\nexport const Unknown: internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object> = Schema.StructWithRest(\n Schema.Struct({ id: Schema.String }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n).pipe(\n Schema.annotate({\n [internal.TypeAnnotationId]: {\n kind: Entity.Kind.Object,\n typename: internal.ANY_OBJECT_TYPENAME,\n version: internal.ANY_OBJECT_VERSION,\n },\n }),\n) as unknown as internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object>;\n\n/**\n * Object with arbitrary properties.\n *\n * NOTE: Due to how TypeScript works, this type is not assignable to a specific schema type.\n * In that case, use `Obj.instanceOf` to check if an object is of a specific type.\n *\n * Prefer using `Obj.Unknown` when you don't need to access arbitrary properties.\n */\nexport interface Any extends BaseObj, internal.AnyProperties {}\n\n/**\n * Base type for snapshot objects (has SnapshotKindId instead of KindId).\n */\ninterface BaseSnapshot extends internal.AnyEntity {\n readonly [Entity.SnapshotKindId]: typeof Entity.Kind.Object;\n readonly id: EntityId;\n}\n\n/**\n * Immutable snapshot of an ECHO object.\n * Branded with SnapshotKindId (not KindId).\n * Property values are frozen at the time the snapshot was created.\n * Returned by getSnapshot() and hooks like useObject().\n *\n * Snapshots are structurally identical to reactive objects but have a different brand,\n * making them distinguishable at the TypeScript level. Neither is assignable to the other.\n */\nexport type Snapshot<T extends Unknown = Unknown> = Omit<T, Entity.KindId> & BaseSnapshot;\n\n/**\n * JSON-encoded properties for objects.\n */\nexport interface BaseObjJson {\n id: string;\n}\n\n// Factory (not a shared const): each object must get its own `keys`/`tags`/`annotations` containers,\n// otherwise mutating one object's meta would leak into every other object via the shared references.\nconst defaultMeta = (): internal.EntityMeta => ({\n keys: [],\n tags: [],\n annotations: {},\n});\n\n// TODO(burdon): Should we allow the caller to set the id?\n/**\n * Props type for object creation with a given type. Accepts a `Type.AnyObj`\n * entity and derives the instance shape via `Type.InstanceType`. Relation-kind\n * entities are rejected at the type level — use `Relation.MakeProps` for those.\n *\n * When the schema is the unconstrained `Type.AnyObj` (`Obj<unknown>` — e.g. a\n * dynamic type from `schemaRegistry.register`), the instance shape is not\n * statically known, so data props widen to `Record<string, unknown>` and the\n * caller can pass arbitrary fields without a cast.\n */\nexport type MakeProps<S extends Type.AnyObj> = {\n id?: EntityId;\n [Meta]?: Partial<internal.EntityMeta>;\n [Parent]?: Unknown;\n // When the resolved instance has no known data keys, widen to a permissive\n // record (the `Obj<unknown>` case); otherwise use the precise property shape.\n // `[keyof …] extends [never]` is wrapped in tuples so the check is\n // non-distributive — a `never` instance type (e.g. when narrowing collapses\n // the schema) stays a single branch instead of distributing to `never`.\n} & ([keyof Entity.Properties<Type.InstanceType<S>>] extends [never]\n ? Record<string, unknown>\n : Entity.Properties<Type.InstanceType<S>>);\n\n/**\n * Options for {@link make}.\n */\nexport type MakeOptions = {\n /**\n * Skip validating `props` against the schema. Only for props the caller built from values that are\n * already typed (e.g. serializing in-memory definitions), where validation re-checks what the\n * compiler did and dominates the cost of creating large objects. Invalid props are not rejected.\n */\n skipValidation?: boolean;\n};\n\n/**\n * Creates a new echo object of the given schema or `Type.Type`.\n *\n * @param typeOrSchema - A static object schema (`Type.makeObject(...)`) or a\n * `Type.Type` entity (e.g. one returned by `db.addType(schemaEntity)`).\n * @param props - Object properties.\n * @param options - See {@link MakeOptions}.\n *\n * Meta can be passed as a symbol in `props`.\n *\n * Example:\n * ```ts\n * const obj = Obj.make(Person, { [Obj.Meta]: { keys: [...] }, name: 'John' });\n * ```\n *\n * Note: Only accepts object schemas / object-kind types, not relation schemas.\n * Use `Relation.make` for relations.\n *\n * @performance O(n) in props size; validates props against the schema and allocates a reactive proxy, with no database\n * I/O.\n */\nexport function make<T extends Type.AnyObj>(\n type: T,\n props: NoInfer<MakeProps<T>>,\n options?: MakeOptions,\n): OfShape<Type.InstanceType<T>>;\nexport function make(input: Type.AnyObj, props: any, options?: MakeOptions): OfShape<any> {\n // `Type.Type` entities aren't `Schema.Schema` themselves; derive the Effect\n // Schema via `Type.getSchema(...)`. Pass the entity through to `makeObject`\n // so subsequent schema mutations (`Type.addFields`, etc.) propagate.\n const schema = Type.getSchema(input);\n assertArgument(\n internal.getTypeAnnotation(schema)?.kind === Entity.Kind.Object,\n 'schema',\n 'Expected an object schema',\n );\n\n let meta: internal.EntityMeta | undefined = undefined;\n\n // Set default fields on meta on creation.\n if (props[internal.MetaId] != null) {\n meta = { ...defaultMeta(), ...props[internal.MetaId] };\n delete props[internal.MetaId];\n }\n\n // Filter undefined values (Object.entries only returns string-keyed properties).\n const filterUndefined: any = Object.fromEntries(Object.entries(props).filter(([_, v]) => v !== undefined));\n\n // Copy symbol properties (like ParentId) that Object.entries doesn't include.\n for (const sym of Object.getOwnPropertySymbols(props)) {\n const value = (props as any)[sym];\n if (value !== undefined) {\n filterUndefined[sym] = value;\n }\n }\n\n const obj = internal.makeObject(\n schema,\n filterUndefined,\n {\n ...defaultMeta(),\n ...meta,\n },\n input,\n { validate: !options?.skipValidation },\n );\n\n internal.propagateParentAnnotations(obj);\n return obj;\n}\n\n/**\n * Determine if object is an ECHO object.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isObject = (obj: unknown): obj is Unknown => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && obj[Entity.KindId] === Entity.Kind.Object;\n};\n\n/**\n * Determine if a value is an ECHO object snapshot.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (obj: unknown): obj is Snapshot => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && (obj as any)[Entity.SnapshotKindId] === Entity.Kind.Object;\n};\n\n/**\n * Subscribe to object updates.\n * The callback is called synchronously when the object is modified.\n * Only accepts reactive objects (not snapshots).\n * @returns Unsubscribe function.\n *\n * @performance O(1) listener registration; the callback runs synchronously after every committed change.\n */\nexport const subscribe = (obj: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(obj, callback);\n};\n\n//\n// Snapshot\n//\n\n/**\n * Returns an immutable snapshot of an object.\n * The snapshot is branded with SnapshotKindId instead of KindId,\n * making it distinguishable from the reactive object at the type level.\n *\n * @performance O(n) in entity size; deep-copies plain data (refs are shared, not resolved) into a frozen object per\n * call.\n */\nexport const getSnapshot: <T extends Unknown>(obj: T) => Snapshot<T> = objInternal.getSnapshot as any;\n\n/**\n * Returns the reactive version of an object from the database, given its snapshot.\n * Inverse of `Obj.getSnapshot`.\n *\n * Uses `Obj.getDatabase` internally to get the database from the snapshot,\n * then resolves the reactive object by ID.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with the reactive object, or fails with `GetReactiveError`.\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(obj);\n * const reactive = Obj.getReactive(snapshot).pipe(\n * Effect.runSync\n * );\n * ```\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactive = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<T, Error.GetReactiveError> =>\n Effect.gen(function* () {\n const db = internal.getDatabase(snapshot);\n if (!db) {\n return yield* Effect.fail(new Error.GetReactiveError({ reason: 'no-database', snapshotId: snapshot.id }));\n }\n const obj = db.getObjectById(snapshot.id);\n if (!obj) {\n return yield* Effect.fail(new Error.GetReactiveError({ reason: 'object-not-found', snapshotId: snapshot.id }));\n }\n return obj as T;\n });\n\n/**\n * Like `Obj.getReactive` but returns `Option.none()` instead of failing when the object\n * cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with `Option.some(reactive)` or `Option.none()`.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOption = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<Option.Option<T>, never> =>\n getReactive(snapshot).pipe(\n Effect.map(Option.some),\n Effect.catch(() => Effect.succeed(Option.none())),\n );\n\n/**\n * Synchronous version of `Obj.getReactive`. Returns the reactive object or throws\n * `GetReactiveError` when the object cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns The reactive object.\n * @throws {Error.GetReactiveError} When the object cannot be resolved.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOrThrow = <T extends Unknown>(snapshot: Snapshot<T>): T =>\n Effect.runSync(getReactive(snapshot));\n\n/**\n * Synchronous version of `Obj.getReactive` that returns `undefined` instead of throwing.\n * Accepts `undefined` input so callers can pass the result of `useObject` directly.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot` or `useObject`), or `undefined`.\n * @returns The reactive object, or `undefined` if the snapshot is `undefined` or unresolvable.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOrUndefined = <T extends Unknown>(snapshot: Snapshot<T> | undefined): T | undefined => {\n if (snapshot === undefined) {\n return undefined;\n }\n return Effect.runSyncExit(getReactive(snapshot)).pipe(\n Exit.match({ onSuccess: (value) => value, onFailure: () => undefined }),\n );\n};\n\nexport type CloneOptions = {\n /**\n * Retain the original object's ID.\n * @default false\n */\n retainId?: boolean;\n\n /**\n * Recursively clone referenced objects.\n * - `'parent'`: clone only refs whose target is transitively parented under the clone root (children\n * that cascade-delete with it); shared refs (registry operations, context objects, …) are copied as-is.\n * - `'all'`: clone every referenced object recursively.\n * Omit for a shallow clone (refs copied as-is).\n */\n deep?: 'parent' | 'all';\n};\n\n/**\n * Clones an object or relation.\n * This does not clone referenced objects, only the properties in the object.\n * @returns A new object with the same schema and properties.\n *\n * @performance O(n) in object size; with `deep`, also clones each qualifying ref target that resolves synchronously\n * (O(reachable subgraph)).\n */\nexport const clone: <T extends Unknown>(obj: T, opts?: CloneOptions) => T = objInternal.clone;\n\n//\n// Change\n//\n\n/**\n * Makes all properties mutable recursively.\n * Used to provide a mutable view of an object within `Obj.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an echo object within a controlled context.\n *\n * All mutations within the callback are batched and trigger a single notification\n * when the callback completes. Direct mutations outside of `Obj.update` will throw\n * an error for echo objects.\n *\n * This function also works with nested objects within echo objects (e.g., Template structs)\n * that are reactive at runtime.\n *\n * @param obj - The echo object to mutate. Use `Relation.update` for relations.\n * @param callback - The callback that performs mutations on the object.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John', age: 25 });\n *\n * // Mutate within Obj.update\n * Obj.update(person, (obj) => {\n * obj.name = 'Jane';\n * obj.age = 30;\n * });\n * // ONE notification fires here\n *\n * // Direct mutation throws\n * person.name = 'Bob'; // Error: Cannot modify outside Obj.update()\n * ```\n *\n * Note: Only accepts objects. Use `Relation.update` for relations.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification and an O(owning\n * fields) parent pass.\n */\nexport const update = <T extends Unknown>(obj: T, callback: internal.ChangeCallback<T>): T => {\n internal.change(obj, callback);\n internal.propagateParentAnnotations(obj);\n return obj;\n};\n\n/**\n * Get a deeply nested property from an object.\n *\n * Similar to lodash.get and getDeep from @dxos/util.\n * This is the complementary function to setValue.\n * Accepts both reactive objects and snapshots.\n *\n * @param obj - The ECHO object to get the property from.\n * @param path - Path to the property (array of keys).\n * @returns The value at the path, or undefined if not found.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, {\n * name: 'John',\n * addresses: [{ street: '123 Main St' }]\n * });\n *\n * Obj.getValue(person, ['addresses', 0, 'street']); // '123 Main St'\n * Obj.getValue(person, ['addresses', 1, 'street']); // undefined\n * ```\n *\n * @performance O(path length) property walk; no schema lookup.\n */\nexport const getValue = (obj: Unknown | Snapshot, path: readonly (string | number)[]): any => {\n return SchemaEx.getValue(obj, SchemaEx.createJsonPath(path));\n};\n\n/**\n * Set a deeply nested property on an object, using the object's schema to determine\n * whether to initialize nested data as an empty object or array.\n *\n * Similar to lodash.set and setDeep from @dxos/util, but schema-aware.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @param obj - The mutable ECHO object to set the property on.\n * @param path - Path to the property (array of keys).\n * @param value - Value to set.\n * @returns The value that was set.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John' });\n * // Person schema has: addresses: Schema.Array(Address)\n * Obj.update(person, (obj) => {\n * Obj.setValue(obj, ['addresses', 0, 'street'], '123 Main St');\n * });\n * // Creates: person.addresses = [{ street: '123 Main St' }]\n * ```\n *\n * @performance O(path length) schema-guided walk; each missing level scans its schema properties once.\n */\n// TODO(wittjosiah): Compute possible path values + type value based on generic object type.\nexport const setValue: (obj: Mutable<Unknown>, path: readonly (string | number)[], value: any) => void =\n objInternal.setValue as any;\n\n//\n// Type\n//\n\nexport const ID = EntityId;\nexport type ID = EntityId;\n\n/**\n * Test if an object is an instance of a given object type.\n *\n * @example\n * ```ts\n * const john = Obj.make(Person, { name: 'John' });\n * const isPerson = Obj.instanceOf(Person);\n * if (isPerson(john)) {\n * // john is Person\n * }\n * ```\n *\n * Only accepts `Type.AnyObj` — use `Relation.instanceOf` for relations and\n * `Type.isType(value)` to test for `Type.Type` meta-schema entities.\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n // Reject `Type.Type` at the type level — those are meta-schema entities, not\n // object instances. Use `Type.isType(value)` instead.\n <T extends Type.Type>(\n type: T,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept Type.Type; use Type.isType(value) instead']\n ): never;\n // Reject relation types — use `Relation.instanceOf` instead.\n <R extends Type.AnyRelation>(\n type: R,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept relation types; use Relation.instanceOf instead']\n ): never;\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyEntity, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Test if a snapshot is an instance of a schema.\n * Mirrors `instanceOf` but only accepts values branded with SnapshotKindId.\n * Use when the value is known to be a snapshot (e.g. from `getSnapshot` or `useObject`).\n *\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(person);\n * if (Obj.snapshotOf(Person, snapshot)) {\n * // snapshot is Obj.Snapshot<Person>\n * }\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const snapshotOf: {\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Snapshot<Type.InstanceType<S>>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Snapshot<Type.InstanceType<S>>;\n} = ((...args: [schema: Type.AnyObj, value: unknown] | [schema: Type.AnyObj]) => {\n const check = (entity: unknown) =>\n entity != null &&\n typeof entity === 'object' &&\n Entity.SnapshotKindId in entity &&\n internal.isInstanceOf(args[0], entity);\n\n if (args.length === 1) {\n return (entity: unknown) => check(entity);\n }\n\n return check(args[1]);\n}) as any;\n\nexport type { GetURIOptions } from './internal/index.ts';\n\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the URI of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.prefer - Controls the URI form (see {@link GetURIOptions}).\n *\n * @performance O(1); returns the stored URI, constructing (and allocating) one only when `options.prefer` asks for\n * another form.\n */\nexport const getURI = (entity: Unknown | Snapshot, options?: internal.GetURIOptions): URI.URI => {\n assertArgument(!Schema.isSchema(entity), 'obj', 'Object should not be a schema.');\n return internal.getUri(entity, options);\n};\n\n/**\n * Get the object's mnemonic: the last 6 characters of its id, uppercased.\n * Short enough to read out or type, and stable for the life of the object, so it is how a\n * person names a particular object — in a log line, a UI chip, or `Filter.mnemonic(...)`.\n * Accepts both reactive objects and snapshots.\n *\n * @example\n * ```ts\n * Obj.getMnemonic(task); // '7QK2ZB'\n * ```\n *\n * @performance O(1) slice of the id; no allocation beyond the result string.\n */\nexport const getMnemonic = (entity: Unknown | Snapshot): string => EntityId.getMnemonic(entity.id);\n\n/**\n * @returns The DXN of the object's type.\n * @example dxn:com.example.type.person:1.0.0\n * @throws If the object is missing its type (corrupted object).\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI = (obj: Unknown | Snapshot): URI.URI => {\n const type = internal.getTypeURI(obj);\n invariant(type != null, 'Corrupted object: missing type.');\n return type;\n};\n\n/**\n * Get the type entity (`Type.AnyObj`) the object was created from.\n *\n * Returns `undefined` when the object's type isn't registered in this runtime\n * (e.g. a freshly deserialized snapshot whose type entity hasn't been wired\n * up yet, or an object loaded from storage before its schema is known). To\n * get the Effect Schema from the returned entity, use `Type.getSchema(...)`.\n *\n * @performance O(1) read of the type back-reference.\n */\nexport const getType = (obj: Unknown | Snapshot): Type.AnyObj | undefined =>\n internal.getType(obj) as Type.AnyObj | undefined;\n\n/**\n * @returns The typename of the object's type.\n * Accepts both reactive objects and snapshots.\n * @example `com.example.type.person`\n *\n * @performance O(1); reads the schema type annotation (database objects resolve the schema by registry URI lookup).\n */\nexport const getTypename = (entity: Unknown | Snapshot): string | undefined => internal.getTypename(entity);\n\n//\n// Database\n//\n\n/**\n * Get the database the object belongs to.\n * Accepts both reactive objects and snapshots.\n *\n * @idiom org.dxos.echo.objGetDatabase\n * applies: Reaching an object's database — to query, add, or remove — when the surrounding Space is not otherwise needed\n * instead-of: `getSpace(obj)?.db` (resolving the whole Space just to read its `.db`)\n * uses: {@link getDatabase}\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Entity.Unknown | Entity.Snapshot): Database.Database | undefined =>\n internal.getDatabase(entity);\n\n/**\n * Get the branch this object instance is bound to: `'main'` for the canonical object, or the branch of\n * a `db.branch()` independent instance. The branch is a property of the instance — two instances of the\n * same object id on different branches each report their own branch.\n *\n * @performance O(1) slot read.\n */\nexport const getBranch = (obj: Unknown): string => internal.getBranch(obj);\n\n/**\n * Get an immutable snapshot of the object at the given historical heads — a detached instance, not a\n * pin on the live object. Only the surface that asks for it sees the historical value; the live\n * object and every other surface are unaffected. The functional alternative to a read-time-travel pin.\n *\n * @performance O(object size) plus the Automerge cost of viewing the document at `heads`; nothing is cached.\n */\nexport const getVersion = <T extends Unknown>(obj: T, heads: readonly string[]): Snapshot<T> => {\n const db = getDatabase(obj);\n invariant(db, 'object is not bound to a database');\n return db.getVersion(obj, heads);\n};\n\n/**\n * Options for {@link getChanges}.\n */\nexport type GetChangesOptions<K extends string = string> = {\n /** Narrow the history to the changes that touched this property; `before`/`after` then hold its value. */\n property?: K;\n};\n\n/**\n * The object's edit history, oldest first: one {@link Change.Change} per document change that\n * touched the object, carrying its snapshot before and after. Given `property`, only the changes that\n * touched that property, carrying its value. Pass an entry's `heads` to {@link getVersion} to read the\n * whole object as that change left it.\n *\n * Changes belong to the object's Automerge document, so `time`, `actor` and `ops` describe the whole\n * change, which may also have written other objects in the same document. Edits to the content of a\n * referenced object (e.g. a `Ref<Text>`) are that object's history, not this one's.\n *\n * @example\n * ```ts\n * for (const { time, before, after } of Obj.getChanges(task, { property: 'status' })) {\n * console.log(new Date(time), before, '→', after);\n * }\n * ```\n *\n * @performance O(document history): diffs every change of the Automerge document and snapshots each match; not cached.\n */\nexport function getChanges<T extends Unknown>(obj: T): Change.Change<Snapshot<T>>[];\nexport function getChanges<T extends Unknown, K extends Exclude<keyof Snapshot<T> & string, 'id'>>(\n obj: T,\n opts: GetChangesOptions<K> & { property: K },\n): Change.Change<Snapshot<T>[K]>[];\nexport function getChanges<T extends Unknown>(obj: T, opts?: GetChangesOptions): Change.ValueChange<unknown>[] {\n const db = getDatabase(obj);\n invariant(db, 'object is not bound to a database');\n return db.getChanges(obj, opts);\n}\n\n//\n// Meta\n//\n\n/**\n * Property that accesses metadata for an entity.\n *\n * Alias for `Entity.Meta`.\n */\nexport const Meta = internal.MetaId;\n\n/**\n * Deeply read-only version of EntityMeta.\n * Prevents mutation at all nesting levels (e.g., `meta.keys.push()` is a TypeScript error).\n */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Mutable meta type returned by `Obj.getMeta` inside an `Obj.update` callback.\n */\nexport type Meta = internal.Meta;\n\n// TODO(burdon): Narrow type.\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the metadata for an object.\n * Returns mutable meta when passed a mutable object (inside `Obj.update` callback).\n * Returns read-only meta when passed a regular object or snapshot.\n *\n * @example\n * ```ts\n * // Read-only access outside change callback\n * const meta = Obj.getMeta(person); // ReadonlyMeta\n *\n * // Mutable access inside change callback\n * Obj.update(person, (obj) => {\n * const meta = Obj.getMeta(obj); // EntityMeta (mutable)\n * meta.tags.push(Ref.make(tag)); // tags are refs to Tag objects\n * });\n * ```\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\n// TODO(wittjosiah): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\nexport function getMeta(entity: Mutable<Unknown>): Meta;\nexport function getMeta(entity: Unknown | Snapshot): ReadonlyMeta;\nexport function getMeta(entity: Unknown | Snapshot | Mutable<Unknown>): Meta | ReadonlyMeta {\n return internal.getMetaChecked(entity);\n}\n\n/**\n * @returns Foreign keys for the object from the specified source.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys: {\n (entity: Unknown | Snapshot, source: string): ForeignKey[];\n (source: string): (entity: Unknown | Snapshot) => ForeignKey[];\n} = Function.dual(2, (entity: Unknown | Snapshot, source?: string): ForeignKey[] => internal.getKeys(entity, source!));\n\n/**\n * Delete all keys from the object for the specified source.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(k) in the foreign-key count.\n */\nexport const deleteKeys = (entity: Mutable<Unknown>, source: string): void => internal.deleteKeys(entity, source);\n\n/**\n * Add a tag to the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(t) in the tag count; dedupes by ref URI before appending.\n */\nexport const addTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.addTag(entity, tag);\n\n/**\n * Remove a tag from the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(t) in the tag count.\n */\nexport const removeTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.removeTag(entity, tag);\n\n/**\n * Check if the object is deleted.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(1) slot read.\n */\n// TODO(dmaretskyi): Default to `false`.\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => objInternal.isDeleted(entity);\n\n//\n// Annotations\n//\n\n/**\n * Get the label of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.fallback `'typename'` returns the object's typename when no\n * label is set (e.g. `org.dxos.type.table`).\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: Unknown | Snapshot, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * Set the label of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(1); writes the first `LabelAnnotation` accessor, a no-op without a schema.\n */\nexport const setLabel = (entity: Mutable<Unknown>, label: string): void => internal.setLabel(entity, label);\n\n/**\n * Get the description of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(1); reads the field named by the schema `DescriptionAnnotation`.\n */\nexport const getDescription = (entity: Unknown | Snapshot): string | undefined => internal.getDescription(entity);\n\n/**\n * Get the icon annotation for the object (or any entity), resolved via its type-level\n * `IconAnnotation`. Accepts both reactive entities and snapshots, and either Objects or\n * Relations — the underlying schema-based lookup works for both.\n *\n * Returns the full `{ icon, hue }` annotation; callers wanting just the icon name typically\n * write `Obj.getIcon(obj)?.icon ?? 'ph--cube--regular'`.\n *\n * @performance O(1) schema annotation lookup, but decodes the annotation value on every call (not cached).\n */\nexport const getIcon = (entity: Entity.Unknown | Entity.Snapshot): internal.IconAnnotation | undefined =>\n internal.getIcon(entity);\n\n/**\n * Set the description of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(1); writes the field named by the schema `DescriptionAnnotation`.\n */\nexport const setDescription = (entity: Mutable<Unknown>, description: string): void =>\n internal.setDescription(entity, description);\n\n/**\n * Symbol to set parent when creating objects with `Obj.make`.\n * @example\n * ```ts\n * Obj.make(TestSchema.Person, {\n * [Obj.Parent]: parentObject,\n * name: 'John',\n * })\n * ```\n */\nexport const Parent: unique symbol = internal.ParentId as any;\n\n/**\n * Get the parent of an object.\n * The parent is always loaded together with the object.\n * Only objects are allowed to have a parent\n * @returns The parent object, or undefined if the object has no parent.\n *\n * @performance O(1); reads the parent slot (a working-set lookup for database objects, never a load).\n */\nexport const getParent = (entity: Unknown | Snapshot): Unknown | undefined => {\n assertArgument(isObject(entity) || isSnapshot(entity), 'Expected an object');\n assumeType<internal.InternalObjectProps>(entity);\n return entity[internal.ParentId] as Unknown | undefined;\n};\n\n/**\n * Whether the parent's own data or meta annotations hold a ref to the child. A parent edge without\n * one leaves the child reachable only by index query (no graph path reaches it), and the child\n * would not read as owned content of the parent.\n */\nconst parentRefsChild = (parent: Any, childId: EntityId): boolean => {\n let found = false;\n const visit = (value: unknown, recurse: (value: unknown) => unknown): unknown => {\n if (found) {\n return value;\n }\n if (Ref.isRef(value)) {\n const eid = EID.tryParse(value.uri);\n if (eid && EID.getEntityId(eid) === childId) {\n found = true;\n }\n return value;\n }\n return recurse(value);\n };\n deepMapValues(parent, visit);\n if (!found) {\n deepMapValues(getMeta(parent).annotations, visit);\n }\n return found;\n};\n\n/**\n * Sets the parent of an object.\n * If a parent (or any transitive parent) is deleted, the object will be deleted.\n * Only objects are allowed to have a parent.\n *\n * The parent must hold a ref to the child (in its data, or in an object annotation — e.g.\n * `Chat.CompanionChatAnnotation`); a ref-less edge currently only warns while call sites are swept.\n *\n * @performance O(n) in parent size: scans the parent data and annotations for a ref to the child before the O(1) write.\n */\n// TODO(burdon): Promote the ref-less-edge warning to an invariant once call sites are swept.\nexport const setParent = (entity: Unknown, parent: Any | undefined) => {\n assertArgument(isObject(entity), 'Expected an object');\n assertArgument(parent === undefined || isObject(parent), 'Expected an object');\n if (parent !== undefined && !parentRefsChild(parent, entity.id)) {\n log.warn('parent edge without a ref from parent to child', {\n child: internal.getTypename(entity),\n parent: internal.getTypename(parent),\n });\n }\n assumeType<internal.InternalObjectProps>(entity);\n assumeType<internal.InternalObjectProps | undefined>(parent);\n entity[internal.ParentId] = parent;\n return entity;\n};\n\ninterface UpdateFromOptions<T> {\n exclude?: (keyof T)[];\n include?: (keyof T)[];\n}\n\nconst valuesEqual = (left: unknown, right: unknown): boolean => {\n if (left === right) {\n return true;\n }\n if (left === null || right === null) {\n return left === right;\n }\n if (typeof left !== 'object' || typeof right !== 'object') {\n return Equal.equals(left, right);\n }\n if (Ref.isRef(left) && Ref.isRef(right)) {\n return left.uri === right.uri;\n }\n if (Ref.isRef(left) || Ref.isRef(right)) {\n return false;\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n if (left.length !== right.length) {\n return false;\n }\n for (let index = 0; index < left.length; index++) {\n if (!valuesEqual(left[index], right[index])) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return false;\n }\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const keys = new Set([\n ...Object.keys(leftRecord).filter((key) => key !== 'id'),\n ...Object.keys(rightRecord).filter((key) => key !== 'id'),\n ]);\n for (const key of keys) {\n const leftHas = Object.hasOwn(leftRecord, key);\n const rightHas = Object.hasOwn(rightRecord, key);\n const leftValue = leftHas ? leftRecord[key] : undefined;\n const rightValue = rightHas ? rightRecord[key] : undefined;\n if (!valuesEqual(leftValue, rightValue)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Breaks reactive proxies on assigned values so echo-db assignment accepts nested structs (same idea as link assignment).\n */\nconst prepareAssignValue = (value: unknown): unknown =>\n deepMapValues(value, (nested, recurse) => {\n if (nested === null || typeof nested !== 'object') {\n return nested;\n }\n if (Ref.isRef(nested)) {\n return nested;\n }\n if (Array.isArray(nested)) {\n return recurse(nested);\n }\n if (isProxy(nested)) {\n return recurse({ ...getProxyTarget(nested) });\n }\n return recurse(nested);\n });\n\n/**\n * For each key present on `source` (except `id`), assigns `target[key]` when the current value differs.\n * References are compared by target DXN; other values use Effect `Equal.equals` inside a structural region,\n * with recursive comparison for arrays and plain object-shaped property bags (excluding `id`).\n *\n * Must be called within an `Obj.update` callback.\n *\n * @returns Whether any property was updated.\n *\n * @performance O(n) in source size; deep-compares every selected property and assigns only the changed ones.\n */\nexport const updateFrom = <T extends Unknown>(\n target: Mutable<T>,\n source: T,\n options?: UpdateFromOptions<T>,\n): boolean => {\n assertArgument(isObject(target), 'Expected an echo object target.');\n assertArgument(isObject(source), 'Expected an echo object source.');\n let keys = Object.keys(source as Record<string, unknown>).filter((key) => key !== 'id');\n if (options?.include !== undefined) {\n const include = new Set(options.include.map((key) => String(key)));\n keys = keys.filter((key) => include.has(key));\n }\n if (options?.exclude !== undefined) {\n const exclude = new Set(options.exclude.map((key) => String(key)));\n keys = keys.filter((key) => !exclude.has(key));\n }\n let updated = false;\n const sourceRecord = source as Record<string, unknown>;\n const targetRecord = target as Record<string, unknown>;\n for (const key of keys) {\n if (!Object.hasOwn(sourceRecord, key)) {\n continue;\n }\n const nextValue = sourceRecord[key];\n const prevValue = Object.hasOwn(targetRecord, key) ? targetRecord[key] : undefined;\n if (valuesEqual(prevValue, nextValue)) {\n continue;\n }\n targetRecord[key] = prepareAssignValue(nextValue) as never;\n updated = true;\n }\n return updated;\n};\n\n//\n// JSON\n//\n\n/**\n * JSON representation of an object.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Converts object to its JSON representation.\n * Accepts both reactive objects and snapshots.\n *\n * `JSON.stringify(obj)` gives the same result for an in-memory object, which shares this serializer.\n * A database-backed object carries its own `toJSON`, which reads the document rather than the target\n * and still differs in two ways: it omits `@uri`, and it leaves `Uint8Array` values unencoded.\n * Prefer this function where the two must agree.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\n// TODO(dmaretskyi): Unify with the echo-handler serializer (`echo-prototypes.ts`) so the divergence\n// above goes away; changes what `JSON.stringify` emits for every database object.\nexport const toJSON = (entity: Unknown | Snapshot): JSON => objInternal.objectToJSON(entity);\n\n/**\n * Creates an object from its json representation, performing schema validation.\n * References and schemas will be resolvable if the `refResolver` is provided.\n *\n * The function must be async to support resolving the schema as well as the relation endpoints.\n *\n * @param options.refResolver - Resolver for references. Produces hydrated references that can be resolved.\n * @param options.uri - Override object URI. Changes the result of `Obj.getURI`.\n * @param options.database - Database to associate with the object.\n * @param options.parent - Parent entity to associate with the object (used when the JSON has no `@parent`). Changes the result of `Obj.getParent`.\n *\n * @performance Async; O(n) schema decode plus resolver round trips for the type, relation endpoints and parent.\n */\nexport const fromJSON: (\n json: unknown,\n options?: { refResolver?: Ref.Resolver; uri?: URI.URI; database?: Database.Database; parent?: Unknown },\n) => Promise<Unknown> = objInternal.objectFromJSON as any;\n\n/**\n * Comparator function type for sorting objects.\n * Accepts both reactive objects and snapshots.\n */\nexport type Comparator = internal.Comparator<Unknown | Snapshot>;\n\n/**\n * Comparator that orders objects by label.\n *\n * @performance O(label accessors) per comparison; labels are recomputed, not cached, so a sort costs O(n log n) label\n * reads.\n */\nexport const sortByLabel: Comparator = internal.sortByLabel as Comparator;\n/**\n * Comparator that orders objects by typename.\n *\n * @performance O(1) per comparison.\n */\nexport const sortByTypename: Comparator = internal.sortByTypename as Comparator;\n/**\n * Compose comparators, applying each in order until one returns non-zero.\n *\n * @performance O(c) per comparison in the number of composed comparators.\n */\nexport const sort = (...comparators: Comparator[]): Comparator => internal.sort(...comparators) as Comparator;\n\n//\n// Version\n//\n\nexport const VersionTypeId = internal.VersionTypeId;\nexport type VersionCompareResult = internal.VersionCompareResult;\n\n/**\n * Represent object version.\n * May be backed by Automerge.\n * Objects with no history are not versioned.\n */\nexport type Version = internal.EntityVersion;\n\n/**\n * Checks that a value is a version object.\n *\n * @performance O(1) brand check.\n */\nexport const isVersion = internal.isVersion;\n/**\n * Checks that a version object is versioned.\n *\n * @performance O(1).\n */\nexport const versionValid = internal.versionValid;\n/**\n * Compares two versions.\n *\n * @performance O(h²) in the number of Automerge heads, which is typically small.\n */\nexport const compareVersions = internal.compareVersions;\n/**\n * Encodes a version as a string.\n *\n * @performance O(h) JSON serialization of the heads.\n */\nexport const encodeVersion = internal.encodeVersion;\n/**\n * Decodes a version from its string encoding.\n *\n * @performance O(h) JSON parse of the heads.\n */\nexport const decodeVersion = internal.decodeVersion;\n\n/**\n * Returns the version of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(h) in Automerge heads: database entities copy the current heads into a fresh array per call.\n */\nexport const version = (entity: Unknown | Snapshot): Version => internal.version(entity);\n\n//\n// Atoms\n//\n\n/**\n * Create a reactive snapshot atom for an ECHO object or ref.\n * Use inside atom computations (e.g. `Atom.make((get) => get(Obj.atom(ref)))`) to subscribe\n * to a ref's target — the atom re-fires when the target loads or changes.\n *\n * @idiom org.dxos.echo.objAtomReactive\n * applies: Subscribing to a ref's target inside an atom computation or a non-React reactive context\n * instead-of: `ref.target` — synchronous and not reactive; returns `undefined` when the target isn't loaded yet and never notifies when it becomes available\n * uses: {@link atom}\n * related: org.dxos.echo-react.useObjectReactive\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeAtom;\n/**\n * Create a reactive atom that yields the live object (or the loaded targets of a ref or ref array).\n *\n * @performance O(1) memoized atom-family lookup (O(r) key copy for a ref array); emits live objects without\n * snapshotting.\n */\nexport const atomReactive = objInternal.makeWithReactive;\n/**\n * Create a reactive atom for a single property of an object or of a ref target.\n *\n * @performance O(1) memoized atom-family lookup; re-reads and shallow-compares the property on every object change.\n */\nexport const atomProperty = objInternal.makeProperty;\n/**\n * Create a reactive atom for the label of an object.\n *\n * @performance O(1) memoized atom-family lookup; recomputes the label on every entity change, emitting only on\n * difference.\n */\nexport const labelAtom = objInternal.makeLabelAtom;\n/**\n * Create a reactive atom for the meta tags of an object.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the tags on every entity change, emitting only when the\n * tag list changes.\n */\nexport const tagsAtom = objInternal.makeTagsAtom;\n/**\n * Get the name of the property that holds the label of an object.\n *\n * @performance O(1); reads the first accessor of the schema `LabelAnnotation`.\n */\nexport const labelProperty = internal.getLabelProperty;\n/**\n * Create a reactive atom for the parent of an object.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the parent slot on every object change, emitting only on\n * difference.\n */\nexport const parentAtom = objInternal.makeParentAtom;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,IAAa,eAAeC;;;;;;;AAO5B,IAAa,YAAYC;;;;;;;AAOzB,IAAa,WAAWC;;;;;;AAMxB,IAAa,gBAAgBC;;;;;;;AAO7B,IAAa,aAAaC"}
1
+ {"version":3,"file":"chunk-Obj.mjs","names":["internal.TypeAnnotationId","internal.ANY_OBJECT_TYPENAME","internal.ANY_OBJECT_VERSION","Type.getSchema","internal.getTypeAnnotation","internal.MetaId","internal.makeObject","Entity.KindId","Entity.SnapshotKindId","internal.subscribe","objInternal.getSnapshot","internal.getDatabase","Error.GetReactiveError","objInternal.clone","objInternal.setValue","internal.isInstanceOf","internal.getUri","internal.getTypeURI","internal.getType","internal.getTypename","internal.getBranch","internal.getMetaChecked","internal.getKeys","internal.deleteKeys","internal.addTag","internal.removeTag","objInternal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.getIcon","internal.setDescription","internal.ParentId","Ref.isRef","internal.isAnyChangeContextActive","internal.ChangeKeyId","internal.isInChangeContext","objInternal.objectToJSON","objInternal.objectFromJSON","internal.sortByLabel","internal.sortByTypename","internal.sort","internal.VersionTypeId","internal.isVersion","internal.versionValid","internal.compareVersions","internal.encodeVersion","internal.decodeVersion","internal.version","objInternal.makeAtom","objInternal.makeWithReactive","objInternal.makeProperty","objInternal.makeLabelAtom","objInternal.makeTagsAtom","internal.getLabelProperty","objInternal.makeParentAtom"],"sources":["../../src/Obj.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Effect from 'effect/Effect';\nimport * as Equal from 'effect/Equal';\nimport * as Exit from 'effect/Exit';\nimport * as Function from 'effect/Function';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { EID, EntityId, type URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { assumeType, deepMapValues } from '@dxos/util';\n\nimport type * as Change from './Change.ts';\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport * as Error from './Error.ts';\nimport { getProxyTarget, isProxy } from './internal/common/proxy/proxy-utils.ts';\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport * as Ref from './Ref.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\n/**\n * Base type for all ECHO objects.\n */\ninterface BaseObj extends internal.AnyEntity, Entity.OfKind<typeof Entity.Kind.Object> {}\n\n/**\n * Object type with specific properties.\n */\nexport type OfShape<Props> = BaseObj & Props;\n\n/**\n * Object with no known properties beyond id and kind.\n * Use this when the object's schema/properties are not known.\n * For objects with arbitrary properties, use `Obj.AnyProps`.\n *\n * NOTE: This is a TypeScript type only, not a schema.\n * To validate that a value is an ECHO object, use `Schema.is(Type.Obj)`.\n */\nexport interface Unknown extends BaseObj {}\n\n/**\n * Runtime Effect schema for any ECHO object.\n * Use for validation, parsing, or as a reference target for collections.\n *\n * NOTE: `Schema.is(Type.Obj)` does STRUCTURAL validation only (checks for `id` field).\n * Use `Obj.isObject()` for proper ECHO instance type guards that check the KindId brand.\n *\n * @example\n * ```ts\n * // Structural type guard (accepts any object with id field)\n * if (Schema.is(Type.Obj)(unknownValue)) { ... }\n *\n * // ECHO instance type guard (checks KindId brand)\n * if (Obj.isObject(unknownValue)) { ... }\n *\n * // Reference to any object type\n * class Collection extends Type.makeObject<Collection>(DXN.make('com.example.type.collection', '0.1.0'))(\n * Schema.Struct({ objects: Schema.Array(Ref.Ref(Obj.Unknown)) }),\n * ) {}\n * ```\n */\n// TODO(wittjosiah): Investigate if Schema.filter can validate KindId on ECHO instances.\n// Effect Schema normalizes proxy objects to plain objects before calling filter predicates.\n// Possible approaches: custom Schema.declare, AST manipulation, or upstream contribution.\nexport const Unknown: internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object> = Schema.StructWithRest(\n Schema.Struct({ id: Schema.String }),\n [Schema.Record(Schema.String, Schema.Unknown)],\n).pipe(\n Schema.annotate({\n [internal.TypeAnnotationId]: {\n kind: Entity.Kind.Object,\n typename: internal.ANY_OBJECT_TYPENAME,\n version: internal.ANY_OBJECT_VERSION,\n },\n }),\n) as unknown as internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Object>;\n\n/**\n * Object with arbitrary properties.\n *\n * NOTE: Due to how TypeScript works, this type is not assignable to a specific schema type.\n * In that case, use `Obj.instanceOf` to check if an object is of a specific type.\n *\n * Prefer using `Obj.Unknown` when you don't need to access arbitrary properties.\n */\nexport interface Any extends BaseObj, internal.AnyProperties {}\n\n/**\n * Base type for snapshot objects (has SnapshotKindId instead of KindId).\n */\ninterface BaseSnapshot extends internal.AnyEntity {\n readonly [Entity.SnapshotKindId]: typeof Entity.Kind.Object;\n readonly id: EntityId;\n}\n\n/**\n * Immutable snapshot of an ECHO object.\n * Branded with SnapshotKindId (not KindId).\n * Property values are frozen at the time the snapshot was created.\n * Returned by getSnapshot() and hooks like useObject().\n *\n * Snapshots are structurally identical to reactive objects but have a different brand,\n * making them distinguishable at the TypeScript level. Neither is assignable to the other.\n */\nexport type Snapshot<T extends Unknown = Unknown> = Omit<T, Entity.KindId> & BaseSnapshot;\n\n/**\n * JSON-encoded properties for objects.\n */\nexport interface BaseObjJson {\n id: string;\n}\n\n// Factory (not a shared const): each object must get its own `keys`/`tags`/`annotations` containers,\n// otherwise mutating one object's meta would leak into every other object via the shared references.\nconst defaultMeta = (): internal.EntityMeta => ({\n keys: [],\n tags: [],\n annotations: {},\n});\n\n// TODO(burdon): Should we allow the caller to set the id?\n/**\n * Props type for object creation with a given type. Accepts a `Type.AnyObj`\n * entity and derives the instance shape via `Type.InstanceType`. Relation-kind\n * entities are rejected at the type level — use `Relation.MakeProps` for those.\n *\n * When the schema is the unconstrained `Type.AnyObj` (`Obj<unknown>` — e.g. a\n * dynamic type from `schemaRegistry.register`), the instance shape is not\n * statically known, so data props widen to `Record<string, unknown>` and the\n * caller can pass arbitrary fields without a cast.\n */\nexport type MakeProps<S extends Type.AnyObj> = {\n id?: EntityId;\n [Meta]?: Partial<internal.EntityMeta>;\n [Parent]?: Unknown;\n // When the resolved instance has no known data keys, widen to a permissive\n // record (the `Obj<unknown>` case); otherwise use the precise property shape.\n // `[keyof …] extends [never]` is wrapped in tuples so the check is\n // non-distributive — a `never` instance type (e.g. when narrowing collapses\n // the schema) stays a single branch instead of distributing to `never`.\n} & ([keyof Entity.Properties<Type.InstanceType<S>>] extends [never]\n ? Record<string, unknown>\n : Entity.Properties<Type.InstanceType<S>>);\n\n/**\n * Options for {@link make}.\n */\nexport type MakeOptions = {\n /**\n * Skip validating `props` against the schema. Only for props the caller built from values that are\n * already typed (e.g. serializing in-memory definitions), where validation re-checks what the\n * compiler did and dominates the cost of creating large objects. Invalid props are not rejected.\n */\n skipValidation?: boolean;\n};\n\n/**\n * Creates a new echo object of the given schema or `Type.Type`.\n *\n * @param typeOrSchema - A static object schema (`Type.makeObject(...)`) or a\n * `Type.Type` entity (e.g. one returned by `db.addType(schemaEntity)`).\n * @param props - Object properties.\n * @param options - See {@link MakeOptions}.\n *\n * Meta can be passed as a symbol in `props`.\n *\n * Example:\n * ```ts\n * const obj = Obj.make(Person, { [Obj.Meta]: { keys: [...] }, name: 'John' });\n * ```\n *\n * Note: Only accepts object schemas / object-kind types, not relation schemas.\n * Use `Relation.make` for relations.\n *\n * @performance O(n) in props size; validates props against the schema and allocates a reactive proxy, with no database\n * I/O.\n */\nexport function make<T extends Type.AnyObj>(\n type: T,\n props: NoInfer<MakeProps<T>>,\n options?: MakeOptions,\n): OfShape<Type.InstanceType<T>>;\nexport function make(input: Type.AnyObj, props: any, options?: MakeOptions): OfShape<any> {\n // `Type.Type` entities aren't `Schema.Schema` themselves; derive the Effect\n // Schema via `Type.getSchema(...)`. Pass the entity through to `makeObject`\n // so subsequent schema mutations (`Type.addFields`, etc.) propagate.\n const schema = Type.getSchema(input);\n assertArgument(\n internal.getTypeAnnotation(schema)?.kind === Entity.Kind.Object,\n 'schema',\n 'Expected an object schema',\n );\n\n let meta: internal.EntityMeta | undefined = undefined;\n\n // Set default fields on meta on creation.\n if (props[internal.MetaId] != null) {\n meta = { ...defaultMeta(), ...props[internal.MetaId] };\n delete props[internal.MetaId];\n }\n\n // Filter undefined values (Object.entries only returns string-keyed properties).\n const filterUndefined: any = Object.fromEntries(Object.entries(props).filter(([_, v]) => v !== undefined));\n\n // Copy symbol properties (like ParentId) that Object.entries doesn't include.\n for (const sym of Object.getOwnPropertySymbols(props)) {\n const value = (props as any)[sym];\n if (value !== undefined) {\n filterUndefined[sym] = value;\n }\n }\n\n const obj = internal.makeObject(\n schema,\n filterUndefined,\n {\n ...defaultMeta(),\n ...meta,\n },\n input,\n { validate: !options?.skipValidation },\n );\n\n internal.propagateParentAnnotations(obj);\n return obj;\n}\n\n/**\n * Determine if object is an ECHO object.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isObject = (obj: unknown): obj is Unknown => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && obj[Entity.KindId] === Entity.Kind.Object;\n};\n\n/**\n * Determine if a value is an ECHO object snapshot.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (obj: unknown): obj is Snapshot => {\n assumeType<internal.InternalObjectProps>(obj);\n return typeof obj === 'object' && obj !== null && (obj as any)[Entity.SnapshotKindId] === Entity.Kind.Object;\n};\n\n/**\n * Subscribe to object updates.\n * The callback is called synchronously when the object is modified.\n * Only accepts reactive objects (not snapshots).\n * @returns Unsubscribe function.\n *\n * @performance O(1) listener registration; the callback runs synchronously after every committed change.\n */\nexport const subscribe = (obj: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(obj, callback);\n};\n\n//\n// Snapshot\n//\n\n/**\n * Returns an immutable snapshot of an object.\n * The snapshot is branded with SnapshotKindId instead of KindId,\n * making it distinguishable from the reactive object at the type level.\n *\n * @performance O(n) in entity size; deep-copies plain data (refs are shared, not resolved) into a frozen object per\n * call.\n */\nexport const getSnapshot: <T extends Unknown>(obj: T) => Snapshot<T> = objInternal.getSnapshot as any;\n\n/**\n * Returns the reactive version of an object from the database, given its snapshot.\n * Inverse of `Obj.getSnapshot`.\n *\n * Uses `Obj.getDatabase` internally to get the database from the snapshot,\n * then resolves the reactive object by ID.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with the reactive object, or fails with `GetReactiveError`.\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(obj);\n * const reactive = Obj.getReactive(snapshot).pipe(\n * Effect.runSync\n * );\n * ```\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactive = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<T, Error.GetReactiveError> =>\n Effect.gen(function* () {\n const db = internal.getDatabase(snapshot);\n if (!db) {\n return yield* Effect.fail(new Error.GetReactiveError({ reason: 'no-database', snapshotId: snapshot.id }));\n }\n const obj = db.getObjectById(snapshot.id);\n if (!obj) {\n return yield* Effect.fail(new Error.GetReactiveError({ reason: 'object-not-found', snapshotId: snapshot.id }));\n }\n return obj as T;\n });\n\n/**\n * Like `Obj.getReactive` but returns `Option.none()` instead of failing when the object\n * cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns Effect that succeeds with `Option.some(reactive)` or `Option.none()`.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOption = <T extends Unknown>(snapshot: Snapshot<T>): Effect.Effect<Option.Option<T>, never> =>\n getReactive(snapshot).pipe(\n Effect.map(Option.some),\n Effect.catch(() => Effect.succeed(Option.none())),\n );\n\n/**\n * Synchronous version of `Obj.getReactive`. Returns the reactive object or throws\n * `GetReactiveError` when the object cannot be resolved (no database, object not found).\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot`).\n * @returns The reactive object.\n * @throws {Error.GetReactiveError} When the object cannot be resolved.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOrThrow = <T extends Unknown>(snapshot: Snapshot<T>): T =>\n Effect.runSync(getReactive(snapshot));\n\n/**\n * Synchronous version of `Obj.getReactive` that returns `undefined` instead of throwing.\n * Accepts `undefined` input so callers can pass the result of `useObject` directly.\n *\n * @param snapshot - A snapshot of the object (from `Obj.getSnapshot` or `useObject`), or `undefined`.\n * @returns The reactive object, or `undefined` if the snapshot is `undefined` or unresolvable.\n *\n * @performance O(1) working-set lookup by id; never loads from disk.\n */\nexport const getReactiveOrUndefined = <T extends Unknown>(snapshot: Snapshot<T> | undefined): T | undefined => {\n if (snapshot === undefined) {\n return undefined;\n }\n return Effect.runSyncExit(getReactive(snapshot)).pipe(\n Exit.match({ onSuccess: (value) => value, onFailure: () => undefined }),\n );\n};\n\nexport type CloneOptions = {\n /**\n * Retain the original object's ID.\n * @default false\n */\n retainId?: boolean;\n\n /**\n * Recursively clone referenced objects.\n * - `'parent'`: clone only refs whose target is transitively parented under the clone root (children\n * that cascade-delete with it); shared refs (registry operations, context objects, …) are copied as-is.\n * - `'all'`: clone every referenced object recursively.\n * Omit for a shallow clone (refs copied as-is).\n */\n deep?: 'parent' | 'all';\n};\n\n/**\n * Clones an object or relation.\n * This does not clone referenced objects, only the properties in the object.\n * @returns A new object with the same schema and properties.\n *\n * @performance O(n) in object size; with `deep`, also clones each qualifying ref target that resolves synchronously\n * (O(reachable subgraph)).\n */\nexport const clone: <T extends Unknown>(obj: T, opts?: CloneOptions) => T = objInternal.clone;\n\n//\n// Change\n//\n\n/**\n * Makes all properties mutable recursively.\n * Used to provide a mutable view of an object within `Obj.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an echo object within a controlled context.\n *\n * All mutations within the callback are batched and trigger a single notification\n * when the callback completes. Direct mutations outside of `Obj.update` will throw\n * an error for echo objects.\n *\n * This function also works with nested objects within echo objects (e.g., Template structs)\n * that are reactive at runtime.\n *\n * @param obj - The echo object to mutate. Use `Relation.update` for relations.\n * @param callback - The callback that performs mutations on the object.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John', age: 25 });\n *\n * // Mutate within Obj.update\n * Obj.update(person, (obj) => {\n * obj.name = 'Jane';\n * obj.age = 30;\n * });\n * // ONE notification fires here\n *\n * // Direct mutation throws\n * person.name = 'Bob'; // Error: Cannot modify outside Obj.update()\n * ```\n *\n * Note: Only accepts objects. Use `Relation.update` for relations.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification and an O(owning\n * fields) parent pass.\n */\nexport const update = <T extends Unknown>(obj: T, callback: internal.ChangeCallback<T>): T => {\n internal.change(obj, callback);\n internal.propagateParentAnnotations(obj);\n return obj;\n};\n\n/**\n * Get a deeply nested property from an object.\n *\n * Similar to lodash.get and getDeep from @dxos/util.\n * This is the complementary function to setValue.\n * Accepts both reactive objects and snapshots.\n *\n * @param obj - The ECHO object to get the property from.\n * @param path - Path to the property (array of keys).\n * @returns The value at the path, or undefined if not found.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, {\n * name: 'John',\n * addresses: [{ street: '123 Main St' }]\n * });\n *\n * Obj.getValue(person, ['addresses', 0, 'street']); // '123 Main St'\n * Obj.getValue(person, ['addresses', 1, 'street']); // undefined\n * ```\n *\n * @performance O(path length) property walk; no schema lookup.\n */\nexport const getValue = (obj: Unknown | Snapshot, path: readonly (string | number)[]): any => {\n return SchemaEx.getValue(obj, SchemaEx.createJsonPath(path));\n};\n\n/**\n * Set a deeply nested property on an object, using the object's schema to determine\n * whether to initialize nested data as an empty object or array.\n *\n * Similar to lodash.set and setDeep from @dxos/util, but schema-aware.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @param obj - The mutable ECHO object to set the property on.\n * @param path - Path to the property (array of keys).\n * @param value - Value to set.\n * @returns The value that was set.\n *\n * @example\n * ```ts\n * const person = Obj.make(Person, { name: 'John' });\n * // Person schema has: addresses: Schema.Array(Address)\n * Obj.update(person, (obj) => {\n * Obj.setValue(obj, ['addresses', 0, 'street'], '123 Main St');\n * });\n * // Creates: person.addresses = [{ street: '123 Main St' }]\n * ```\n *\n * @performance O(path length) schema-guided walk; each missing level scans its schema properties once.\n */\n// TODO(wittjosiah): Compute possible path values + type value based on generic object type.\nexport const setValue: (obj: Mutable<Unknown>, path: readonly (string | number)[], value: any) => void =\n objInternal.setValue as any;\n\n//\n// Type\n//\n\nexport const ID = EntityId;\nexport type ID = EntityId;\n\n/**\n * Test if an object is an instance of a given object type.\n *\n * @example\n * ```ts\n * const john = Obj.make(Person, { name: 'John' });\n * const isPerson = Obj.instanceOf(Person);\n * if (isPerson(john)) {\n * // john is Person\n * }\n * ```\n *\n * Only accepts `Type.AnyObj` — use `Relation.instanceOf` for relations and\n * `Type.isType(value)` to test for `Type.Type` meta-schema entities.\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n // Reject `Type.Type` at the type level — those are meta-schema entities, not\n // object instances. Use `Type.isType(value)` instead.\n <T extends Type.Type>(\n type: T,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept Type.Type; use Type.isType(value) instead']\n ): never;\n // Reject relation types — use `Relation.instanceOf` instead.\n <R extends Type.AnyRelation>(\n type: R,\n _hint?: never,\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n ..._error: ['ERROR: Obj.instanceOf does not accept relation types; use Relation.instanceOf instead']\n ): never;\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyEntity, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Test if a snapshot is an instance of a schema.\n * Mirrors `instanceOf` but only accepts values branded with SnapshotKindId.\n * Use when the value is known to be a snapshot (e.g. from `getSnapshot` or `useObject`).\n *\n * @example\n * ```ts\n * const snapshot = Obj.getSnapshot(person);\n * if (Obj.snapshotOf(Person, snapshot)) {\n * // snapshot is Obj.Snapshot<Person>\n * }\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const snapshotOf: {\n <S extends Type.AnyObj>(schema: S): (value: unknown) => value is Snapshot<Type.InstanceType<S>>;\n <S extends Type.AnyObj>(schema: S, value: unknown): value is Snapshot<Type.InstanceType<S>>;\n} = ((...args: [schema: Type.AnyObj, value: unknown] | [schema: Type.AnyObj]) => {\n const check = (entity: unknown) =>\n entity != null &&\n typeof entity === 'object' &&\n Entity.SnapshotKindId in entity &&\n internal.isInstanceOf(args[0], entity);\n\n if (args.length === 1) {\n return (entity: unknown) => check(entity);\n }\n\n return check(args[1]);\n}) as any;\n\nexport type { GetURIOptions } from './internal/index.ts';\n\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the URI of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.prefer - Controls the URI form (see {@link GetURIOptions}).\n *\n * @performance O(1); returns the stored URI, constructing (and allocating) one only when `options.prefer` asks for\n * another form.\n */\nexport const getURI = (entity: Unknown | Snapshot, options?: internal.GetURIOptions): URI.URI => {\n assertArgument(!Schema.isSchema(entity), 'obj', 'Object should not be a schema.');\n return internal.getUri(entity, options);\n};\n\n/**\n * Get the object's mnemonic: the last 6 characters of its id, uppercased.\n * Short enough to read out or type, and stable for the life of the object, so it is how a\n * person names a particular object — in a log line, a UI chip, or `Filter.mnemonic(...)`.\n * Accepts both reactive objects and snapshots.\n *\n * @example\n * ```ts\n * Obj.getMnemonic(task); // '7QK2ZB'\n * ```\n *\n * @performance O(1) slice of the id; no allocation beyond the result string.\n */\nexport const getMnemonic = (entity: Unknown | Snapshot): string => EntityId.getMnemonic(entity.id);\n\n/**\n * @returns The DXN of the object's type.\n * @example dxn:com.example.type.person:1.0.0\n * @throws If the object is missing its type (corrupted object).\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI = (obj: Unknown | Snapshot): URI.URI => {\n const type = internal.getTypeURI(obj);\n invariant(type != null, 'Corrupted object: missing type.');\n return type;\n};\n\n/**\n * Get the type entity (`Type.AnyObj`) the object was created from.\n *\n * Returns `undefined` when the object's type isn't registered in this runtime\n * (e.g. a freshly deserialized snapshot whose type entity hasn't been wired\n * up yet, or an object loaded from storage before its schema is known). To\n * get the Effect Schema from the returned entity, use `Type.getSchema(...)`.\n *\n * @performance O(1) read of the type back-reference.\n */\nexport const getType = (obj: Unknown | Snapshot): Type.AnyObj | undefined =>\n internal.getType(obj) as Type.AnyObj | undefined;\n\n/**\n * @returns The typename of the object's type.\n * Accepts both reactive objects and snapshots.\n * @example `com.example.type.person`\n *\n * @performance O(1); reads the schema type annotation (database objects resolve the schema by registry URI lookup).\n */\nexport const getTypename = (entity: Unknown | Snapshot): string | undefined => internal.getTypename(entity);\n\n//\n// Database\n//\n\n/**\n * Get the database the object belongs to.\n * Accepts both reactive objects and snapshots.\n *\n * @idiom org.dxos.echo.objGetDatabase\n * applies: Reaching an object's database — to query, add, or remove — when the surrounding Space is not otherwise needed\n * instead-of: `getSpace(obj)?.db` (resolving the whole Space just to read its `.db`)\n * uses: {@link getDatabase}\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Entity.Unknown | Entity.Snapshot): Database.Database | undefined =>\n internal.getDatabase(entity);\n\n/**\n * Get the branch this object instance is bound to: `'main'` for the canonical object, or the branch of\n * a `db.branch()` independent instance. The branch is a property of the instance — two instances of the\n * same object id on different branches each report their own branch.\n *\n * @performance O(1) slot read.\n */\nexport const getBranch = (obj: Unknown): string => internal.getBranch(obj);\n\n/**\n * Get an immutable snapshot of the object at the given historical heads — a detached instance, not a\n * pin on the live object. Only the surface that asks for it sees the historical value; the live\n * object and every other surface are unaffected. The functional alternative to a read-time-travel pin.\n *\n * @performance O(object size) plus the Automerge cost of viewing the document at `heads`; nothing is cached.\n */\nexport const getVersion = <T extends Unknown>(obj: T, heads: readonly string[]): Snapshot<T> => {\n const db = getDatabase(obj);\n invariant(db, 'object is not bound to a database');\n return db.getVersion(obj, heads);\n};\n\n/**\n * Options for {@link getChanges}.\n */\nexport type GetChangesOptions<K extends string = string> = {\n /** Narrow the history to the changes that touched this property; `before`/`after` then hold its value. */\n property?: K;\n};\n\n/**\n * The object's edit history, oldest first: one {@link Change.Change} per document change that\n * touched the object, carrying its snapshot before and after. Given `property`, only the changes that\n * touched that property, carrying its value. Pass an entry's `heads` to {@link getVersion} to read the\n * whole object as that change left it.\n *\n * Changes belong to the object's Automerge document, so `time`, `actor` and `ops` describe the whole\n * change, which may also have written other objects in the same document. Edits to the content of a\n * referenced object (e.g. a `Ref<Text>`) are that object's history, not this one's.\n *\n * @example\n * ```ts\n * for (const { time, before, after } of Obj.getChanges(task, { property: 'status' })) {\n * console.log(new Date(time), before, '→', after);\n * }\n * ```\n *\n * @performance O(document history): diffs every change of the Automerge document and snapshots each match; not cached.\n */\nexport function getChanges<T extends Unknown>(obj: T): Change.Change<Snapshot<T>>[];\nexport function getChanges<T extends Unknown, K extends Exclude<keyof Snapshot<T> & string, 'id'>>(\n obj: T,\n opts: GetChangesOptions<K> & { property: K },\n): Change.Change<Snapshot<T>[K]>[];\nexport function getChanges<T extends Unknown>(obj: T, opts?: GetChangesOptions): Change.ValueChange<unknown>[] {\n const db = getDatabase(obj);\n invariant(db, 'object is not bound to a database');\n return db.getChanges(obj, opts);\n}\n\n//\n// Meta\n//\n\n/**\n * Property that accesses metadata for an entity.\n *\n * Alias for `Entity.Meta`.\n */\nexport const Meta = internal.MetaId;\n\n/**\n * Deeply read-only version of EntityMeta.\n * Prevents mutation at all nesting levels (e.g., `meta.keys.push()` is a TypeScript error).\n */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Mutable meta type returned by `Obj.getMeta` inside an `Obj.update` callback.\n */\nexport type Meta = internal.Meta;\n\n// TODO(burdon): Narrow type.\n// TODO(dmaretskyi): Allow returning undefined.\n/**\n * Get the metadata for an object.\n * Returns mutable meta when passed a mutable object (inside `Obj.update` callback).\n * Returns read-only meta when passed a regular object or snapshot.\n *\n * @example\n * ```ts\n * // Read-only access outside change callback\n * const meta = Obj.getMeta(person); // ReadonlyMeta\n *\n * // Mutable access inside change callback\n * Obj.update(person, (obj) => {\n * const meta = Obj.getMeta(obj); // EntityMeta (mutable)\n * meta.tags.push(tag); // tags are Tag objects\n * });\n * ```\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\n// TODO(wittjosiah): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\nexport function getMeta(entity: Mutable<Unknown>): Meta;\nexport function getMeta(entity: Unknown | Snapshot): ReadonlyMeta;\nexport function getMeta(entity: Unknown | Snapshot | Mutable<Unknown>): Meta | ReadonlyMeta {\n return internal.getMetaChecked(entity);\n}\n\n/**\n * @returns Foreign keys for the object from the specified source.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys: {\n (entity: Unknown | Snapshot, source: string): ForeignKey[];\n (source: string): (entity: Unknown | Snapshot) => ForeignKey[];\n} = Function.dual(2, (entity: Unknown | Snapshot, source?: string): ForeignKey[] => internal.getKeys(entity, source!));\n\n/**\n * Delete all keys from the object for the specified source.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(k) in the foreign-key count.\n */\nexport const deleteKeys = (entity: Mutable<Unknown>, source: string): void => internal.deleteKeys(entity, source);\n\n/**\n * Add a tag to the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(t) in the tag count; dedupes by tag id before appending.\n */\nexport const addTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.addTag(entity, tag);\n\n/**\n * Remove a tag from the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(t) in the tag count.\n */\nexport const removeTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.removeTag(entity, tag);\n\n/**\n * Check if the object is deleted.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(1) slot read.\n */\n// TODO(dmaretskyi): Default to `false`.\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => objInternal.isDeleted(entity);\n\n//\n// Annotations\n//\n\n/**\n * Get the label of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @param options.fallback `'typename'` returns the object's typename when no\n * label is set (e.g. `org.dxos.type.table`).\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: Unknown | Snapshot, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * Set the label of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(1); writes the first `LabelAnnotation` accessor, a no-op without a schema.\n */\nexport const setLabel = (entity: Mutable<Unknown>, label: string): void => internal.setLabel(entity, label);\n\n/**\n * Get the description of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(1); reads the field named by the schema `DescriptionAnnotation`.\n */\nexport const getDescription = (entity: Unknown | Snapshot): string | undefined => internal.getDescription(entity);\n\n/**\n * Get the icon annotation for the object (or any entity), resolved via its type-level\n * `IconAnnotation`. Accepts both reactive entities and snapshots, and either Objects or\n * Relations — the underlying schema-based lookup works for both.\n *\n * Returns the full `{ icon, hue }` annotation; callers wanting just the icon name typically\n * write `Obj.getIcon(obj)?.icon ?? 'ph--cube--regular'`.\n *\n * @performance O(1) schema annotation lookup, but decodes the annotation value on every call (not cached).\n */\nexport const getIcon = (entity: Entity.Unknown | Entity.Snapshot): internal.IconAnnotation | undefined =>\n internal.getIcon(entity);\n\n/**\n * Set the description of the object.\n * Must be called within an `Obj.update` callback.\n *\n * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`\n * parameters, so there is no compile-time error. Enforcement is runtime-only.\n *\n * @performance O(1); writes the field named by the schema `DescriptionAnnotation`.\n */\nexport const setDescription = (entity: Mutable<Unknown>, description: string): void =>\n internal.setDescription(entity, description);\n\n/**\n * Symbol to set parent when creating objects with `Obj.make`.\n * @example\n * ```ts\n * Obj.make(TestSchema.Person, {\n * [Obj.Parent]: parentObject,\n * name: 'John',\n * })\n * ```\n */\nexport const Parent: unique symbol = internal.ParentId as any;\n\n/**\n * Get the parent of an object.\n * The parent is always loaded together with the object.\n * Only objects are allowed to have a parent\n * @returns The parent object, or undefined if the object has no parent.\n *\n * @performance O(1); reads the parent slot (a working-set lookup for database objects, never a load).\n */\nexport const getParent = (entity: Unknown | Snapshot): Unknown | undefined => {\n assertArgument(isObject(entity) || isSnapshot(entity), 'Expected an object');\n assumeType<internal.InternalObjectProps>(entity);\n return entity[internal.ParentId] as Unknown | undefined;\n};\n\n/**\n * Whether the parent's own data or meta annotations hold a ref to the child. A parent edge without\n * one leaves the child reachable only by index query (no graph path reaches it), and the child\n * would not read as owned content of the parent.\n */\nconst parentRefsChild = (parent: Any, childId: EntityId): boolean => {\n let found = false;\n const visit = (value: unknown, recurse: (value: unknown) => unknown): unknown => {\n if (found) {\n return value;\n }\n if (Ref.isRef(value)) {\n const eid = EID.tryParse(value.uri);\n if (eid && EID.getEntityId(eid) === childId) {\n found = true;\n }\n return value;\n }\n return recurse(value);\n };\n deepMapValues(parent, visit);\n if (!found) {\n deepMapValues(getMeta(parent).annotations, visit);\n }\n return found;\n};\n\n/**\n * Sets the parent of an object.\n * If a parent (or any transitive parent) is deleted, the object will be deleted.\n * Only objects are allowed to have a parent.\n *\n * The parent must hold a ref to the child (in its data, or in an object annotation — e.g.\n * `Chat.CompanionChatAnnotation`); a ref-less edge currently only warns while call sites are swept.\n *\n * @performance O(n) in parent size: scans the parent data and annotations for a ref to the child before the O(1) write.\n */\n// TODO(burdon): Promote the ref-less-edge warning to an invariant once call sites are swept.\nexport const setParent = (entity: Unknown, parent: Any | undefined) => {\n assertArgument(isObject(entity), 'Expected an object');\n assertArgument(parent === undefined || isObject(parent), 'Expected an object');\n if (parent !== undefined && !parentRefsChild(parent, entity.id)) {\n log.warn('parent edge without a ref from parent to child', {\n child: internal.getTypename(entity),\n parent: internal.getTypename(parent),\n });\n }\n assumeType<internal.InternalObjectProps>(entity);\n assumeType<internal.InternalObjectProps | undefined>(parent);\n // The parent is part of the object's state, so setting it notifies subscribers like any edit, in a change\n // of its own; inside any `Obj.update` it is set directly, since a nested change would end the caller's.\n if (internal.isAnyChangeContextActive()) {\n entity[internal.ParentId] = parent;\n // The context's exit notifies only its own object, so another object's update must queue this one.\n const changeKey: object | undefined = Reflect.get(entity, internal.ChangeKeyId);\n if (changeKey === undefined || !internal.isInChangeContext(changeKey)) {\n internal.queueOwnerNotification(entity);\n }\n } else {\n internal.change(entity, (mutable) => {\n assumeType<internal.InternalObjectProps>(mutable);\n mutable[internal.ParentId] = parent;\n });\n }\n return entity;\n};\n\ninterface UpdateFromOptions<T> {\n exclude?: (keyof T)[];\n include?: (keyof T)[];\n}\n\nconst valuesEqual = (left: unknown, right: unknown): boolean => {\n if (left === right) {\n return true;\n }\n if (left === null || right === null) {\n return left === right;\n }\n if (typeof left !== 'object' || typeof right !== 'object') {\n return Equal.equals(left, right);\n }\n if (Ref.isRef(left) && Ref.isRef(right)) {\n return left.uri === right.uri;\n }\n if (Ref.isRef(left) || Ref.isRef(right)) {\n return false;\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n if (left.length !== right.length) {\n return false;\n }\n for (let index = 0; index < left.length; index++) {\n if (!valuesEqual(left[index], right[index])) {\n return false;\n }\n }\n return true;\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return false;\n }\n const leftRecord = left as Record<string, unknown>;\n const rightRecord = right as Record<string, unknown>;\n const keys = new Set([\n ...Object.keys(leftRecord).filter((key) => key !== 'id'),\n ...Object.keys(rightRecord).filter((key) => key !== 'id'),\n ]);\n for (const key of keys) {\n const leftHas = Object.hasOwn(leftRecord, key);\n const rightHas = Object.hasOwn(rightRecord, key);\n const leftValue = leftHas ? leftRecord[key] : undefined;\n const rightValue = rightHas ? rightRecord[key] : undefined;\n if (!valuesEqual(leftValue, rightValue)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Breaks reactive proxies on assigned values so echo-db assignment accepts nested structs (same idea as link assignment).\n */\nconst prepareAssignValue = (value: unknown): unknown =>\n deepMapValues(value, (nested, recurse) => {\n if (nested === null || typeof nested !== 'object') {\n return nested;\n }\n if (Ref.isRef(nested)) {\n return nested;\n }\n if (Array.isArray(nested)) {\n return recurse(nested);\n }\n if (isProxy(nested)) {\n return recurse({ ...getProxyTarget(nested) });\n }\n return recurse(nested);\n });\n\n/**\n * For each key present on `source` (except `id`), assigns `target[key]` when the current value differs.\n * References are compared by target DXN; other values use Effect `Equal.equals` inside a structural region,\n * with recursive comparison for arrays and plain object-shaped property bags (excluding `id`).\n *\n * Must be called within an `Obj.update` callback.\n *\n * @returns Whether any property was updated.\n *\n * @performance O(n) in source size; deep-compares every selected property and assigns only the changed ones.\n */\nexport const updateFrom = <T extends Unknown>(\n target: Mutable<T>,\n source: T,\n options?: UpdateFromOptions<T>,\n): boolean => {\n assertArgument(isObject(target), 'Expected an echo object target.');\n assertArgument(isObject(source), 'Expected an echo object source.');\n let keys = Object.keys(source as Record<string, unknown>).filter((key) => key !== 'id');\n if (options?.include !== undefined) {\n const include = new Set(options.include.map((key) => String(key)));\n keys = keys.filter((key) => include.has(key));\n }\n if (options?.exclude !== undefined) {\n const exclude = new Set(options.exclude.map((key) => String(key)));\n keys = keys.filter((key) => !exclude.has(key));\n }\n let updated = false;\n const sourceRecord = source as Record<string, unknown>;\n const targetRecord = target as Record<string, unknown>;\n for (const key of keys) {\n if (!Object.hasOwn(sourceRecord, key)) {\n continue;\n }\n const nextValue = sourceRecord[key];\n const prevValue = Object.hasOwn(targetRecord, key) ? targetRecord[key] : undefined;\n if (valuesEqual(prevValue, nextValue)) {\n continue;\n }\n targetRecord[key] = prepareAssignValue(nextValue) as never;\n updated = true;\n }\n return updated;\n};\n\n//\n// JSON\n//\n\n/**\n * JSON representation of an object.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Converts object to its JSON representation.\n * Accepts both reactive objects and snapshots.\n *\n * `JSON.stringify(obj)` gives the same result for an in-memory object, which shares this serializer.\n * A database-backed object carries its own `toJSON`, which reads the document rather than the target\n * and still differs in two ways: it omits `@uri`, and it leaves `Uint8Array` values unencoded.\n * Prefer this function where the two must agree.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\n// TODO(dmaretskyi): Unify with the echo-handler serializer (`echo-prototypes.ts`) so the divergence\n// above goes away; changes what `JSON.stringify` emits for every database object.\nexport const toJSON = (entity: Unknown | Snapshot): JSON => objInternal.objectToJSON(entity);\n\n/**\n * Creates an object from its json representation, performing schema validation.\n * References and schemas will be resolvable if the `refResolver` is provided.\n *\n * The function must be async to support resolving the schema as well as the relation endpoints.\n *\n * @param options.refResolver - Resolver for references. Produces hydrated references that can be resolved.\n * @param options.uri - Override object URI. Changes the result of `Obj.getURI`.\n * @param options.database - Database to associate with the object.\n * @param options.parent - Parent entity to associate with the object (used when the JSON has no `@parent`). Changes the result of `Obj.getParent`.\n *\n * @performance Async; O(n) schema decode plus resolver round trips for the type, relation endpoints and parent.\n */\nexport const fromJSON: (\n json: unknown,\n options?: { refResolver?: Ref.Resolver; uri?: URI.URI; database?: Database.Database; parent?: Unknown },\n) => Promise<Unknown> = objInternal.objectFromJSON as any;\n\n/**\n * Comparator function type for sorting objects.\n * Accepts both reactive objects and snapshots.\n */\nexport type Comparator = internal.Comparator<Unknown | Snapshot>;\n\n/**\n * Comparator that orders objects by label.\n *\n * @performance O(label accessors) per comparison; labels are recomputed, not cached, so a sort costs O(n log n) label\n * reads.\n */\nexport const sortByLabel: Comparator = internal.sortByLabel as Comparator;\n/**\n * Comparator that orders objects by typename.\n *\n * @performance O(1) per comparison.\n */\nexport const sortByTypename: Comparator = internal.sortByTypename as Comparator;\n/**\n * Compose comparators, applying each in order until one returns non-zero.\n *\n * @performance O(c) per comparison in the number of composed comparators.\n */\nexport const sort = (...comparators: Comparator[]): Comparator => internal.sort(...comparators) as Comparator;\n\n//\n// Version\n//\n\nexport const VersionTypeId = internal.VersionTypeId;\nexport type VersionCompareResult = internal.VersionCompareResult;\n\n/**\n * Represent object version.\n * May be backed by Automerge.\n * Objects with no history are not versioned.\n */\nexport type Version = internal.EntityVersion;\n\n/**\n * Checks that a value is a version object.\n *\n * @performance O(1) brand check.\n */\nexport const isVersion = internal.isVersion;\n/**\n * Checks that a version object is versioned.\n *\n * @performance O(1).\n */\nexport const versionValid = internal.versionValid;\n/**\n * Compares two versions.\n *\n * @performance O(h²) in the number of Automerge heads, which is typically small.\n */\nexport const compareVersions = internal.compareVersions;\n/**\n * Encodes a version as a string.\n *\n * @performance O(h) JSON serialization of the heads.\n */\nexport const encodeVersion = internal.encodeVersion;\n/**\n * Decodes a version from its string encoding.\n *\n * @performance O(h) JSON parse of the heads.\n */\nexport const decodeVersion = internal.decodeVersion;\n\n/**\n * Returns the version of the object.\n * Accepts both reactive objects and snapshots.\n *\n * @performance O(h) in Automerge heads: database entities copy the current heads into a fresh array per call.\n */\nexport const version = (entity: Unknown | Snapshot): Version => internal.version(entity);\n\n//\n// Atoms\n//\n\n/**\n * Create a reactive snapshot atom for an ECHO object or ref.\n * Use inside atom computations (e.g. `Atom.make((get) => get(Obj.atom(ref)))`) to subscribe\n * to a ref's target — the atom re-fires when the target loads or changes.\n *\n * @idiom org.dxos.echo.objAtomReactive\n * applies: Subscribing to a ref's target inside an atom computation or a non-React reactive context\n * instead-of: `ref.target` — synchronous and not reactive; returns `undefined` when the target isn't loaded yet and never notifies when it becomes available\n * uses: {@link atom}\n * related: org.dxos.echo-react.useObjectReactive\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeAtom;\n/**\n * Create a reactive atom that yields the live object (or the loaded targets of a ref or ref array).\n *\n * @performance O(1) memoized atom-family lookup (O(r) key copy for a ref array); emits live objects without\n * snapshotting.\n */\nexport const atomReactive = objInternal.makeWithReactive;\n/**\n * Create a reactive atom for a single property of an object or of a ref target.\n *\n * @performance O(1) memoized atom-family lookup; re-reads and shallow-compares the property on every object change.\n */\nexport const atomProperty = objInternal.makeProperty;\n/**\n * Create a reactive atom for the label of an object.\n *\n * @performance O(1) memoized atom-family lookup; recomputes the label on every entity change, emitting only on\n * difference.\n */\nexport const labelAtom = objInternal.makeLabelAtom;\n/**\n * Create a reactive atom for the meta tags of an object.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the tags on every entity change, emitting only when the\n * tag list changes.\n */\nexport const tagsAtom = objInternal.makeTagsAtom;\n/**\n * Get the name of the property that holds the label of an object.\n *\n * @performance O(1); reads the first accessor of the schema `LabelAnnotation`.\n */\nexport const labelProperty = internal.getLabelProperty;\n/**\n * Create a reactive atom for the parent of an object.\n *\n * @performance O(1) memoized atom-family lookup; re-reads the parent slot on every object change, emitting only on\n * difference.\n */\nexport const parentAtom = objInternal.makeParentAtom;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,IAAa,UAA0E,OAAO,eAC5F,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC,GACnC,CAAC,OAAO,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,WAAwCC,UAAiB,MAAM;;;;;;;;;;;;;;AAmBvF,IAAa,OAAOC;;;;;;;AAOpB,IAAa,eAAeC;;;;;;AAM5B,IAAa,eAAeC;;;;;;;AAO5B,IAAa,YAAYC;;;;;;;AAOzB,IAAa,WAAWC;;;;;;AAMxB,IAAa,gBAAgBC;;;;;;;AAO7B,IAAa,aAAaC"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { Nt as makeProjection, wt as prettyQuery } from "./chunk-internal.mjs";
3
- import { k as getTypeURIFromSpecifier, p as isDatabase } from "./chunk-Database.mjs";
2
+ import { Dt as prettyQuery, It as makeProjection } from "./chunk-internal.mjs";
3
+ import { A as getTypeURIFromSpecifier, m as isDatabase } from "./chunk-Database.mjs";
4
4
  import { F as getURI, P as getTypename } from "./chunk-Obj.mjs";
5
5
  import { F as type$1, f as everything, j as props, x as is$1 } from "./chunk-Filter.mjs";
6
6
  import { QueryAST } from "@dxos/echo-protocol";
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-QueryResult.mjs","names":[],"sources":["../../src/QueryResult.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Effect from 'effect/Effect';\nimport type * as Option from 'effect/Option';\nimport type * as Atom from 'effect/reactivity/Atom';\n\nimport { type CleanupFn } from '@dxos/async';\n\nimport type * as Entity from './Entity.ts';\n\n/**\n * Individual query result entry.\n */\nexport type Entry<T> = {\n id: string;\n\n /**\n * May not be present for remote results.\n */\n result?: T;\n\n match?: {\n // TODO(dmaretskyi): text positional info.\n\n /**\n * Higher means better match.\n */\n rank: number;\n };\n\n /**\n * Query resolution metadata.\n */\n // TODO(dmaretskyi): Rename to meta?\n resolution?: {\n // TODO(dmaretskyi): Make this more generic.\n source: Source;\n\n /**\n * Query resolution time in milliseconds.\n */\n time: number;\n };\n};\n\n/**\n * Where query results come from.\n */\nexport type Source = 'remote' | 'local' | 'index' | 'registry';\n\n/**\n * How much of the answer a live query holds right now:\n * - `complete`: nothing outstanding.\n * - `local-only`: in-process results are shown; no remote source has answered yet.\n * - `merged`: some remote sources answered and some have not.\n * - `stale`: a remote answer predates a local write inside its scope; its re-run has not arrived.\n * - `failed`: a remote source errored or timed out; `sources` names it.\n * - `pending`: nothing in-process contributes and no remote has answered.\n */\nexport type Completeness = 'complete' | 'local-only' | 'merged' | 'stale' | 'failed' | 'pending';\n\n/** One source's progress on a live query, for diagnostics and for waiting on a specific answer. */\nexport type SourceState = {\n source: Source;\n state: 'pending' | 'answered' | 'failed';\n /** Answers integrated for the current query, including re-runs that left the result unchanged. */\n answers: number;\n};\n\n/**\n * Invidual query result entry for a database Entity.\n */\nexport type EntityEntry<T extends Entity.Unknown = Entity.Unknown> = Entry<T>;\n\nexport type RunOptions = {\n timeout?: number;\n};\n\nexport type SubscriptionOptions = {\n /**\n * Fire the callback immediately.\n */\n fire?: boolean;\n};\n\n// TODO(burdon): Should T be constrained to Entity.Any?\nexport interface QueryResult<T> {\n /**\n * Currently available results along with their match metadata.\n *\n * @performance Synchronous; O(n) recompute from the working set on first read after a change, cached otherwise.\n */\n readonly entries: Entry<T>[];\n\n /**\n * Currently available results.\n *\n * @performance Synchronous; O(n) recompute from the working set on first read after a change, cached otherwise.\n */\n readonly results: T[];\n\n /**\n * Returns all known results.\n *\n * @performance Async; executes the full query (index plus working set) on every call, not cached; O(n) in the data\n * the executor examines, not in the result count.\n */\n run(opts?: RunOptions): Promise<T[]>;\n\n /**\n * Returns all known results along with their match metadata.\n *\n * @performance Async; executes the full query (index plus working set) on every call, not cached; O(n) in the data\n * the executor examines, not in the result count.\n */\n runEntries(opts?: RunOptions): Promise<Entry<T>[]>;\n\n /**\n * Returns currently available results synchronously.\n *\n * @performance Synchronous; working-set results only, recomputed in O(n) after a change and cached otherwise.\n */\n runSync(): T[];\n\n /**\n * Returns currently available results synchronously along with their match metadata.\n *\n * @performance Synchronous; working-set results only, recomputed in O(n) after a change and cached otherwise.\n */\n runSyncEntries(): Entry<T>[];\n\n /**\n * Returns first result.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n first(opts?: RunOptions): Promise<T>;\n\n /**\n * Returns first result if there is one.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n firstOrUndefined(opts?: RunOptions): Promise<T | undefined>;\n\n /**\n * Subscribes to changes in query results.\n *\n * @performance O(1) registration; the first subscriber starts the live query, whose updates cost an O(n) recompute.\n */\n subscribe(callback?: (query: QueryResult<T>) => void, opts?: SubscriptionOptions): CleanupFn;\n\n /**\n * Self-updating atom. Updates automatically when query results change.\n *\n * Memoized per QueryResult instance — repeated accesses on the same instance return the same\n * Atom. Safe only when the QueryResult is itself held stable across re-renders (e.g. behind a\n * `useMemo`). It must NOT be used in graph-builder connectors/actions or other atom computes,\n * where `db.query(...)` is called fresh on each re-evaluation: every run constructs a new\n * QueryResult and so a new atom + subscription, leaking the previous ones. Use the memoized\n * {@link atom} family there instead.\n *\n * @performance O(1) memoized per instance; each emission is a `runSync`.\n */\n readonly atom: Atom.Atom<T[]>;\n\n /**\n * How much of the answer the current results hold. Reading it never notifies; subscribers are notified\n * only when results change.\n *\n * @performance O(sources).\n */\n readonly completeness: Completeness;\n\n /**\n * Per-source progress of the live query.\n *\n * @performance O(sources); allocates.\n */\n readonly sources: readonly SourceState[];\n}\n\n/**\n * Effect that returns a QueryResult when evaluated, but also has shorthand methods for running the query or getting the first result.\n */\nexport interface QueryResultEffect<T, E, R> extends Effect.Effect<QueryResult<T>, E, R> {\n /**\n * Runs the query once.\n *\n * @performance Executes the full query once, O(n) in the data the executor examines.\n */\n run: Effect.Effect<T[], E, R>;\n /**\n * Runs the query once and returns the first result.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n first: Effect.Effect<Option.Option<T>, E, R>;\n\n // TODO(dmaretskyi): Considering adding `atom`, but since `Database.query` is used in imperative code only, I dont think it will be useful.\n}\n"],"mappings":""}
1
+ {"version":3,"file":"chunk-QueryResult.mjs","names":[],"sources":["../../src/QueryResult.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport type * as Effect from 'effect/Effect';\nimport type * as Option from 'effect/Option';\nimport type * as Atom from 'effect/reactivity/Atom';\n\nimport { type CleanupFn } from '@dxos/async';\n\nimport type * as Entity from './Entity.ts';\n\n/**\n * Individual query result entry.\n */\nexport type Entry<T> = {\n id: string;\n\n /**\n * May not be present for remote results.\n */\n result?: T;\n\n match?: {\n // TODO(dmaretskyi): text positional info.\n\n /**\n * Higher means better match.\n */\n rank: number;\n };\n\n /**\n * Query resolution metadata.\n */\n // TODO(dmaretskyi): Rename to meta?\n resolution?: {\n // TODO(dmaretskyi): Make this more generic.\n source: Source;\n\n /**\n * Query resolution time in milliseconds.\n */\n time: number;\n\n /** The state a remote source evaluated the entry at; absent for an in-process entry. */\n version?: Version;\n\n /**\n * Whether local evidence confirmed a remote entry: its object is loaded here and still matches, or is held\n * at the exact version the remote evaluated. False when the entry is shown on the remote's word alone.\n */\n verified?: boolean;\n };\n};\n\n/** The state a remote source evaluated an entry at: a document's heads, or a feed block's position. */\nexport type Version =\n | { kind: 'automerge'; documentId: string; heads: readonly string[] }\n | { kind: 'feed'; insertionId: number };\n\n/**\n * Where query results come from.\n */\nexport type Source = 'remote' | 'local' | 'index' | 'registry';\n\n/**\n * How much of the answer a live query holds right now:\n * - `complete`: nothing outstanding.\n * - `local-only`: in-process results are shown; no remote source has answered yet.\n * - `merged`: some remote sources answered and some have not.\n * - `stale`: a remote answer predates a local write inside its scope; its re-run has not arrived.\n * - `failed`: a remote source errored or timed out; `sources` names it.\n * - `pending`: nothing in-process contributes and no remote has answered.\n */\nexport type Completeness = 'complete' | 'local-only' | 'merged' | 'stale' | 'failed' | 'pending';\n\n/** One source's progress on a live query, for diagnostics and for waiting on a specific answer. */\nexport type SourceState = {\n source: Source;\n state: 'pending' | 'answered' | 'failed';\n /** Answers integrated for the current query, including re-runs that left the result unchanged. */\n answers: number;\n};\n\n/**\n * Invidual query result entry for a database Entity.\n */\nexport type EntityEntry<T extends Entity.Unknown = Entity.Unknown> = Entry<T>;\n\nexport type RunOptions = {\n timeout?: number;\n};\n\nexport type SubscriptionOptions = {\n /**\n * Fire the callback immediately.\n */\n fire?: boolean;\n};\n\n// TODO(burdon): Should T be constrained to Entity.Any?\nexport interface QueryResult<T> {\n /**\n * Currently available results along with their match metadata.\n *\n * @performance Synchronous; O(n) recompute from the working set on first read after a change, cached otherwise.\n */\n readonly entries: Entry<T>[];\n\n /**\n * Currently available results.\n *\n * @performance Synchronous; O(n) recompute from the working set on first read after a change, cached otherwise.\n */\n readonly results: T[];\n\n /**\n * Returns all known results.\n *\n * @performance Async; executes the full query (index plus working set) on every call, not cached; O(n) in the data\n * the executor examines, not in the result count.\n */\n run(opts?: RunOptions): Promise<T[]>;\n\n /**\n * Returns all known results along with their match metadata.\n *\n * @performance Async; executes the full query (index plus working set) on every call, not cached; O(n) in the data\n * the executor examines, not in the result count.\n */\n runEntries(opts?: RunOptions): Promise<Entry<T>[]>;\n\n /**\n * Returns currently available results synchronously.\n *\n * @performance Synchronous; working-set results only, recomputed in O(n) after a change and cached otherwise.\n */\n runSync(): T[];\n\n /**\n * Returns currently available results synchronously along with their match metadata.\n *\n * @performance Synchronous; working-set results only, recomputed in O(n) after a change and cached otherwise.\n */\n runSyncEntries(): Entry<T>[];\n\n /**\n * Returns first result.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n first(opts?: RunOptions): Promise<T>;\n\n /**\n * Returns first result if there is one.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n firstOrUndefined(opts?: RunOptions): Promise<T | undefined>;\n\n /**\n * Subscribes to changes in query results.\n *\n * @performance O(1) registration; the first subscriber starts the live query, whose updates cost an O(n) recompute.\n */\n subscribe(callback?: (query: QueryResult<T>) => void, opts?: SubscriptionOptions): CleanupFn;\n\n /**\n * Self-updating atom. Updates automatically when query results change.\n *\n * Memoized per QueryResult instance — repeated accesses on the same instance return the same\n * Atom. Safe only when the QueryResult is itself held stable across re-renders (e.g. behind a\n * `useMemo`). It must NOT be used in graph-builder connectors/actions or other atom computes,\n * where `db.query(...)` is called fresh on each re-evaluation: every run constructs a new\n * QueryResult and so a new atom + subscription, leaking the previous ones. Use the memoized\n * {@link atom} family there instead.\n *\n * @performance O(1) memoized per instance; each emission is a `runSync`.\n */\n readonly atom: Atom.Atom<T[]>;\n\n /**\n * How much of the answer the current results hold. Reading it never notifies; subscribers are notified\n * only when results change.\n *\n * @performance O(sources).\n */\n readonly completeness: Completeness;\n\n /**\n * Per-source progress of the live query.\n *\n * @performance O(sources); allocates.\n */\n readonly sources: readonly SourceState[];\n}\n\n/**\n * Effect that returns a QueryResult when evaluated, but also has shorthand methods for running the query or getting the first result.\n */\nexport interface QueryResultEffect<T, E, R> extends Effect.Effect<QueryResult<T>, E, R> {\n /**\n * Runs the query once.\n *\n * @performance Executes the full query once, O(n) in the data the executor examines.\n */\n run: Effect.Effect<T[], E, R>;\n /**\n * Runs the query once and returns the first result.\n *\n * @performance O(n) in the data examined: runs the full query and takes the first result; `.limit(1)` bounds the\n * work only where the executor applies the limit before scanning.\n */\n first: Effect.Effect<Option.Option<T>, E, R>;\n\n // TODO(dmaretskyi): Considering adding `atom`, but since `Database.query` is used in imperative code only, I dont think it will be useful.\n}\n"],"mappings":""}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { ct as ReferenceAnnotationId } from "./chunk-Database.mjs";
2
+ import { ht as ReferenceAnnotationId } from "./chunk-Database.mjs";
3
3
  import { d as getSchemaReferenceDXN, f as isRefIdentifier$1, n as Ref$1 } from "./chunk-ref.mjs";
4
- import { t as snapshotEquals } from "./chunk-atom-snapshot.mjs";
4
+ import { r as snapshotEquals } from "./chunk-atom-snapshot.mjs";
5
5
  import { n as loadAll$1, t as RefArray } from "./chunk-ref-array.mjs";
6
6
  import { DXN } from "@dxos/keys";
7
7
  import * as SchemaAST from "@dxos/effect/SchemaAST";
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { _ as isType, f as getTypename } from "./chunk-Type.mjs";
3
+ import * as Atom from "effect/reactivity/Atom";
3
4
  import * as Effect from "effect/Effect";
4
5
  import * as Context from "effect/Context";
5
- import * as Atom from "effect/reactivity/Atom";
6
6
  //#region src/internal/Registry/atoms.ts
7
7
  /**
8
8
  * Atom family for the type entity registered under a typename.
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Registry.mjs","names":["Type.isType","Type.getTypename","registryAtoms.makeTypeAtom"],"sources":["../../src/internal/Registry/atoms.ts","../../src/Registry.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport type * as Registry from '../../Registry.ts';\nimport * as Type from '../../Type.ts';\n\n/**\n * Atom family for the type entity registered under a typename.\n * Keyed by a structurally-equal tuple key `[registry, typename]` so nested families are avoided.\n */\nconst typeEntityFamily = Atom.family(\n ([registry, typename]: readonly [Registry.Registry, string]): Atom.Atom<Type.AnyEntity | undefined> => {\n const read = (): Type.AnyEntity | undefined =>\n registry\n .list()\n .filter(Type.isType)\n .find((type) => Type.getTypename(type) === typename);\n\n return Atom.make<Type.AnyEntity | undefined>((get) => {\n let previous = read();\n\n const unsubscribe = registry.changed.on(() => {\n const next = read();\n // The registry also holds operations, skills, and routines, whose churn must not re-run\n // consumers keyed to an unrelated typename.\n if (next !== previous) {\n previous = next;\n get.setSelf(next);\n }\n });\n get.addFinalizer(() => unsubscribe());\n\n return previous;\n });\n },\n);\n\n/**\n * Reactive atom for the type entity registered under `typename`, or `undefined` while unregistered.\n */\nexport const makeTypeAtom = (registry: Registry.Registry, typename: string): Atom.Atom<Type.AnyEntity | undefined> =>\n typeEntityFamily([registry, typename]);\n","// Copyright 2026 DXOS.org\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\n\nimport { type ReadOnlyEvent } from '@dxos/async';\n\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport type * as Filter from './Filter.ts';\nimport * as registryAtoms from './internal/Registry/atoms.ts';\nimport type * as Query from './Query.ts';\n\n/**\n * Identifier denoting an ECHO Registry.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Registry');\nexport type TypeId = typeof TypeId;\n\n/**\n * Composable, in-memory registry of keyed ECHO entities.\n *\n * Entities are stored by id and queried via the standard ECHO Query API.\n * A registry may delegate to an optional upstream registry: results from the local\n * registry take precedence and upstream results fill in anything not found locally.\n *\n * Intended use cases include caches of schemas, operations, skills, routines, plugins,\n * etc., sourced from 3rd-party plugins, local code, or local space objects.\n *\n * Types (schema-definition entities produced by `Type.makeObject` / `Type.makeRelation`) are\n * stored the same way as any other entity — via `add()`. Use `list().filter(Type.isType)` to\n * retrieve them.\n *\n * Scope: a Registry is independent of any ECHO space or Hypergraph — it is a process-local,\n * in-memory cache. Wire one per space (e.g. as a Layer scoped to the space's Effect runtime)\n * or share a single instance across spaces depending on the use case.\n *\n * The concrete implementation (and the `makeRegistry` / `registryLayer` factories) lives in\n * `@dxos/echo-client`; this module declares only the interface so that the `@dxos/echo` API surface\n * stays free of query-matching dependencies.\n */\nexport interface Registry {\n readonly [TypeId]: TypeId;\n\n /**\n * Stable per-instance identifier. Used to key process-local resources (e.g. memoized\n * reactive atoms) to a specific registry instance, analogous to {@link Database.spaceId}.\n */\n readonly id: string;\n\n /**\n * Fires whenever local registry contents change (add, remove, or clear).\n */\n readonly changed: ReadOnlyEvent<void>;\n\n /**\n * All locally-stored entities.\n * Does not include upstream entities — use {@link list} for that.\n *\n * @performance O(n); allocates a new array on every read.\n */\n readonly local: readonly Entity.Unknown[];\n\n /**\n * Add or replace one or more entities in the local registry.\n * Existing entries with the same id are replaced.\n * Also indexes type entities by DXN for fast lookup.\n *\n * @performance O(n) in entities, each indexed by id and URI, then one `changed` emission.\n */\n add(entities: readonly Entity.Unknown[]): void;\n\n /**\n * Remove an entity by id from the local registry.\n * @returns true if an entity was removed, false if it was not found.\n *\n * @performance O(u) in the URI index, which it scans for entries pointing at the entity.\n */\n remove(id: string): boolean;\n\n /**\n * Remove all locally-stored entities.\n * Does not affect the upstream registry.\n *\n * @performance O(1) map clears plus one `changed` emission.\n */\n clear(): void;\n\n /**\n * Get an entity by id.\n * Searches the local registry first, then falls back to the upstream registry.\n *\n * @performance O(1) map lookup, then the same in the upstream on a miss.\n */\n get(id: string): Entity.Unknown | undefined;\n\n /**\n * Get an entity by one of its addressing URIs — a type entity by its typename DXN (or, when\n * persisted, its identifier EID), a keyed entity by its `dxn:<key>[:<version>]`. Accepts legacy\n * DXN forms (normalized internally). Searches the local registry first, then falls back to the\n * upstream registry. Narrow the result with `Type.isType` when a type entity is required.\n *\n * @performance O(1) map lookup after URI normalization, then the same in the upstream on a miss.\n */\n getByURI(uri: string): Entity.Unknown | undefined;\n\n /**\n * List all entities.\n * Local entities take precedence over upstream entities with the same id.\n *\n * @performance O(n) in local plus upstream entities; allocates a merged array per call.\n */\n list(): Entity.Unknown[];\n\n /**\n * Run an ECHO query against the registry's entities (implements {@link Database.Queryable}).\n *\n * Matching happens in-memory over {@link list}. Scope (`from`) clauses are unwrapped and\n * ignored — a direct registry query always targets the registry's own entities. The primary\n * way to query registry contents is still through the database (`db.query(...).from(Scope.registry())`),\n * which fans the database and registry together; this method is for querying a registry directly.\n *\n * Only locally-evaluable AST nodes are supported: `select`, `filter`, `limit`, `from`, `options`,\n * and boolean combinators, plus full-text filters as case-insensitive all-terms containment.\n * Server-side concerns (order, traversal, vector search, timestamp filters) throw or match nothing.\n *\n * @performance O(n · filter size) linear scan of `list()` on every read; results are not cached between reads.\n */\n query: Database.QueryFn;\n}\n\n/**\n * Type guard for {@link Registry}.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isRegistry = (obj: unknown): obj is Registry =>\n obj != null && typeof obj === 'object' && TypeId in obj && (obj as { [TypeId]?: unknown })[TypeId] === TypeId;\n\n/**\n * Options for the registry factory (`makeRegistry` in `@dxos/echo-client`).\n */\nexport type Options = {\n /**\n * Optional upstream registry. Queries fall back to upstream when an entity\n * is not present in the local registry.\n */\n upstream?: Registry;\n\n /**\n * Initial set of entities to seed the local registry with.\n */\n initial?: readonly Entity.Unknown[];\n};\n\n/**\n * Effect Context tag for {@link Registry}.\n * Use this to inject a registry into Effect-based code.\n */\nexport class Service extends Context.Service<Service, Registry>()('@dxos/echo/Registry/Service') {}\n\n/**\n * Executes a query against the registry and returns the results.\n * Analogous to {@link Database.query} `.run` for the in-process registry.\n *\n * @performance O(n · filter size) linear scan of the registry.\n */\nexport const runQuery: {\n <Q extends Query.Any>(query: Q): Effect.Effect<Query.Type<Q>[], never, Service>;\n <F extends Filter.Any>(filter: F): Effect.Effect<Filter.Type<F>[], never, Service>;\n} = (queryOrFilter: Query.Any | Filter.Any) =>\n Effect.gen(function* () {\n const registry = yield* Service;\n return (yield* Effect.promise(() => registry.query(queryOrFilter as any).run())) as any;\n });\n\n//\n// Atoms\n//\n\n/**\n * Reactive lookup of the type entity registered under `typename`, or `undefined` while unregistered.\n * Memoized per (registry, typename), so consumers share one atom and one `changed` subscription.\n *\n * Registration is asynchronous, so anything deriving display state from a schema must read it here\n * rather than through a plain lookup, which freezes at whatever was registered on first evaluation.\n *\n * @example `const type = get(Registry.typeAtom(db.graph.registry, typename));`\n *\n * @performance O(1) memoized atom-family lookup, but rescans `list()` in O(n) on every registry change.\n */\nexport const typeAtom = registryAtoms.makeTypeAtom;\n"],"mappings":";;;;;;;;;;AAaA,IAAM,mBAAmB,KAAK,QAC3B,CAAC,UAAU,cAA2F;CACrG,MAAM,aACJ,SACG,KAAK,CAAA,CACL,OAAOA,MAAW,CAAA,CAClB,MAAM,SAASC,YAAiB,IAAI,MAAM,QAAQ;CAEvD,OAAO,KAAK,MAAkC,QAAQ;EACpD,IAAI,WAAW,KAAK;EAEpB,MAAM,cAAc,SAAS,QAAQ,SAAS;GAC5C,MAAM,OAAO,KAAK;GAGlB,IAAI,SAAS,UAAU;IACrB,WAAW;IACX,IAAI,QAAQ,IAAI;GAClB;EACF,CAAC;EACD,IAAI,mBAAmB,YAAY,CAAC;EAEpC,OAAO;CACT,CAAC;AACH,CACF;;;;AAKA,IAAa,gBAAgB,UAA6B,aACxD,iBAAiB,CAAC,UAAU,QAAQ,CAAC;;;;;;;;;;;;;AC1BvC,IAAa,SAAS,OAAO,IAAI,qBAAqB;;;;;;AAwHtD,IAAa,cAAc,QACzB,OAAO,QAAQ,OAAO,QAAQ,YAAY,UAAU,OAAQ,IAA+B,YAAY;;;;;AAsBzG,IAAa,UAAb,cAA6B,QAAQ,QAA2B,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC;;;;;;;AAQlG,IAAa,YAGR,kBACH,OAAO,IAAI,aAAa;CACtB,MAAM,WAAW,OAAO;CACxB,OAAQ,OAAO,OAAO,cAAc,SAAS,MAAM,aAAoB,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC;;;;;;;;;;;;AAiBH,IAAa,WAAWC"}
1
+ {"version":3,"file":"chunk-Registry.mjs","names":["Type.isType","Type.getTypename","registryAtoms.makeTypeAtom"],"sources":["../../src/internal/Registry/atoms.ts","../../src/Registry.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Atom from 'effect/reactivity/Atom';\n\nimport type * as Registry from '../../Registry.ts';\nimport * as Type from '../../Type.ts';\n\n/**\n * Atom family for the type entity registered under a typename.\n * Keyed by a structurally-equal tuple key `[registry, typename]` so nested families are avoided.\n */\nconst typeEntityFamily = Atom.family(\n ([registry, typename]: readonly [Registry.Registry, string]): Atom.Atom<Type.AnyEntity | undefined> => {\n const read = (): Type.AnyEntity | undefined =>\n registry\n .list()\n .filter(Type.isType)\n .find((type) => Type.getTypename(type) === typename);\n\n return Atom.make<Type.AnyEntity | undefined>((get) => {\n let previous = read();\n\n const unsubscribe = registry.changed.on(() => {\n const next = read();\n // The registry also holds operations, skills, and routines, whose churn must not re-run\n // consumers keyed to an unrelated typename.\n if (next !== previous) {\n previous = next;\n get.setSelf(next);\n }\n });\n get.addFinalizer(() => unsubscribe());\n\n return previous;\n });\n },\n);\n\n/**\n * Reactive atom for the type entity registered under `typename`, or `undefined` while unregistered.\n */\nexport const makeTypeAtom = (registry: Registry.Registry, typename: string): Atom.Atom<Type.AnyEntity | undefined> =>\n typeEntityFamily([registry, typename]);\n","// Copyright 2026 DXOS.org\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\n\nimport { type ReadOnlyEvent } from '@dxos/async';\n\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport type * as Filter from './Filter.ts';\nimport * as registryAtoms from './internal/Registry/atoms.ts';\nimport type * as Query from './Query.ts';\n\n/**\n * Identifier denoting an ECHO Registry.\n */\nexport const TypeId = Symbol.for('@dxos/echo/Registry');\nexport type TypeId = typeof TypeId;\n\n/**\n * Composable, in-memory registry of keyed ECHO entities.\n *\n * Entities are stored by id and queried via the standard ECHO Query API.\n * A registry may delegate to an optional upstream registry: results from the local\n * registry take precedence and upstream results fill in anything not found locally.\n *\n * Intended use cases include caches of schemas, operations, skills, routines, plugins,\n * etc., sourced from 3rd-party plugins, local code, or local space objects.\n *\n * Types (schema-definition entities produced by `Type.makeObject` / `Type.makeRelation`) are\n * stored the same way as any other entity — via `add()`. Use `list().filter(Type.isType)` to\n * retrieve them.\n *\n * Scope: a Registry is independent of any ECHO space or Hypergraph — it is a process-local,\n * in-memory cache. Wire one per space (e.g. as a Layer scoped to the space's Effect runtime)\n * or share a single instance across spaces depending on the use case.\n *\n * The concrete implementation (and the `makeRegistry` / `registryLayer` factories) lives in\n * `@dxos/echo-client`; this module declares only the interface so that the `@dxos/echo` API surface\n * stays free of query-matching dependencies.\n */\nexport interface Registry {\n readonly [TypeId]: TypeId;\n\n /**\n * Stable per-instance identifier. Used to key process-local resources (e.g. memoized\n * reactive atoms) to a specific registry instance, analogous to {@link Database.spaceId}.\n */\n readonly id: string;\n\n /**\n * Fires whenever local registry contents change (add, remove, or clear).\n */\n readonly changed: ReadOnlyEvent<void>;\n\n /**\n * All locally-stored entities.\n * Does not include upstream entities — use {@link list} for that.\n *\n * @performance O(n); allocates a new array on every read.\n */\n readonly local: readonly Entity.Unknown[];\n\n /**\n * Add or replace one or more entities in the local registry.\n * Existing entries with the same id are replaced.\n * Also indexes type entities by DXN for fast lookup.\n *\n * @performance O(n) in entities, each indexed by id and URI, then one `changed` emission.\n */\n add(entities: readonly Entity.Unknown[]): void;\n\n /**\n * Remove an entity by id from the local registry.\n * @returns true if an entity was removed, false if it was not found.\n *\n * @performance O(u) in the URI index, which it scans for entries pointing at the entity.\n */\n remove(id: string): boolean;\n\n /**\n * Remove all locally-stored entities.\n * Does not affect the upstream registry.\n *\n * @performance O(1) map clears plus one `changed` emission.\n */\n clear(): void;\n\n /**\n * Get an entity by id.\n * Searches the local registry first, then falls back to the upstream registry.\n *\n * @performance O(1) map lookup, then the same in the upstream on a miss.\n */\n get(id: string): Entity.Unknown | undefined;\n\n /**\n * Get an entity by one of its addressing URIs — a type entity by its typename DXN (or, when\n * persisted, its identifier EID), a keyed entity by its `dxn:<key>[:<version>]`. Accepts legacy\n * DXN forms (normalized internally). Searches the local registry first, then falls back to the\n * upstream registry. Narrow the result with `Type.isType` when a type entity is required.\n *\n * @performance O(1) map lookup after URI normalization, then the same in the upstream on a miss.\n */\n getByURI(uri: string): Entity.Unknown | undefined;\n\n /**\n * List all entities.\n * Local entities take precedence over upstream entities with the same id.\n *\n * @performance O(n) in local plus upstream entities; allocates a merged array per call.\n */\n list(): Entity.Unknown[];\n\n /**\n * Run an ECHO query against the registry's entities (implements {@link Database.Queryable}).\n *\n * Matching happens in-memory over {@link list}. Scope (`from`) clauses are unwrapped and\n * ignored — a direct registry query always targets the registry's own entities. The primary\n * way to query registry contents is still through the database (`db.query(...).from(Scope.registry())`),\n * which fans the database and registry together; this method is for querying a registry directly.\n *\n * Only locally-evaluable AST nodes are supported: `select`, `filter`, `limit`, `from`, `options`,\n * and boolean combinators, plus full-text filters as case-insensitive all-terms containment.\n * Server-side concerns (order, traversal, vector search, timestamp filters) throw or match nothing.\n *\n * @performance O(n · filter size) linear scan of `list()` on every read; results are not cached between reads.\n */\n query: Database.QueryFn;\n}\n\n/**\n * Type guard for {@link Registry}.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isRegistry = (obj: unknown): obj is Registry =>\n obj != null && typeof obj === 'object' && TypeId in obj && (obj as { [TypeId]?: unknown })[TypeId] === TypeId;\n\n/**\n * Options for the registry factory (`makeRegistry` in `@dxos/echo-client`).\n */\nexport type Options = {\n /**\n * Optional upstream registry. Queries fall back to upstream when an entity\n * is not present in the local registry.\n */\n upstream?: Registry;\n\n /**\n * Initial set of entities to seed the local registry with.\n */\n initial?: readonly Entity.Unknown[];\n};\n\n/**\n * Effect Context tag for {@link Registry}.\n * Use this to inject a registry into Effect-based code.\n */\nexport class Service extends Context.Service<Service, Registry>()('@dxos/echo/Registry/Service') {}\n\n/**\n * Executes a query against the registry and returns the results.\n * Analogous to {@link Database.query} `.run` for the in-process registry.\n *\n * @performance O(n · filter size) linear scan of the registry.\n */\nexport const runQuery: {\n <Q extends Query.Any>(query: Q): Effect.Effect<Query.Type<Q>[], never, Service>;\n <F extends Filter.Any>(filter: F): Effect.Effect<Filter.Type<F>[], never, Service>;\n} = (queryOrFilter: Query.Any | Filter.Any) =>\n Effect.gen(function* () {\n const registry = yield* Service;\n return (yield* Effect.promise(() => registry.query(queryOrFilter as any).run())) as any;\n });\n\n//\n// Atoms\n//\n\n/**\n * Reactive lookup of the type entity registered under `typename`, or `undefined` while unregistered.\n * Memoized per (registry, typename), so consumers share one atom and one `changed` subscription.\n *\n * Registration is asynchronous, so anything deriving display state from a schema must read it here\n * rather than through a plain lookup, which freezes at whatever was registered on first evaluation.\n *\n * @example `const type = get(Registry.typeAtom(db.graph.registry, typename));`\n *\n * @performance O(1) memoized atom-family lookup, but rescans `list()` in O(n) on every registry change.\n */\nexport const typeAtom = registryAtoms.makeTypeAtom;\n"],"mappings":";;;;;;;;;;AAaA,IAAM,mBAAmB,KAAK,QAC3B,CAAC,UAAU,cAA2F;CACrG,MAAM,aACJ,SACG,KAAK,CAAC,CACN,OAAOA,MAAW,CAAC,CACnB,MAAM,SAASC,YAAiB,IAAI,MAAM,QAAQ;CAEvD,OAAO,KAAK,MAAkC,QAAQ;EACpD,IAAI,WAAW,KAAK;EAEpB,MAAM,cAAc,SAAS,QAAQ,SAAS;GAC5C,MAAM,OAAO,KAAK;GAGlB,IAAI,SAAS,UAAU;IACrB,WAAW;IACX,IAAI,QAAQ,IAAI;GAClB;EACF,CAAC;EACD,IAAI,mBAAmB,YAAY,CAAC;EAEpC,OAAO;CACT,CAAC;AACH,CACF;;;;AAKA,IAAa,gBAAgB,UAA6B,aACxD,iBAAiB,CAAC,UAAU,QAAQ,CAAC;;;;;;;;;;;;;AC1BvC,IAAa,SAAS,OAAO,IAAI,qBAAqB;;;;;;AAwHtD,IAAa,cAAc,QACzB,OAAO,QAAQ,OAAO,QAAQ,YAAY,UAAU,OAAQ,IAA+B,YAAY;;;;;AAsBzG,IAAa,UAAb,cAA6B,QAAQ,QAA2B,CAAC,CAAC,6BAA6B,CAAC,CAAC,CAAC;;;;;;;AAQlG,IAAa,YAGR,kBACH,OAAO,IAAI,aAAa;CACtB,MAAM,WAAW,OAAO;CACxB,OAAQ,OAAO,OAAO,cAAc,SAAS,MAAM,aAAoB,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC;;;;;;;;;;;;AAiBH,IAAa,WAAWC"}
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { a as addTag$1, c as getMetaChecked, l as removeTag$1, o as deleteKeys$1, s as getKeys$1 } from "./chunk-entity-dictionary.mjs";
3
- import { A as objectToJSON, At as VersionTypeId$1, Dt as sort$1, I as isVersion$1, L as version$1, Ot as sortByLabel$1, Y as makeObject, f as makeRelation, g as setValue$1, h as getSnapshot$1, kt as sortByTypename$1, v as isDeleted$1 } from "./chunk-internal.mjs";
3
+ import { A as objectToJSON, At as sort$1, I as isVersion$1, L as version$1, Mt as sortByTypename$1, Nt as VersionTypeId$1, Y as makeObject, f as makeRelation, g as setValue$1, h as getSnapshot$1, jt as sortByLabel$1, v as isDeleted$1 } from "./chunk-internal.mjs";
4
4
  import { a as ANY_OBJECT_VERSION, i as ANY_OBJECT_TYPENAME, o as EntityKind } from "./chunk-util.mjs";
5
- import { A as isInstanceOf, At as getTypeAnnotation, Ct as getLabel$1, Ft as setDescription$1, Ht as ParentId, Jt as getType$1, Lt as setLabel$1, M as getDatabase$1, Mt as getTypeURI$1, N as getUri, Nt as getTypename$1, P as getObjectEchoUri, cn as RelationSourceId, ft as TypeAnnotationId, ln as RelationTargetDXNId, nn as MetaId, sn as RelationSourceDXNId, un as RelationTargetId, vt as getDescription$1 } from "./chunk-Database.mjs";
5
+ import { Bt as getTypeURI$1, Et as getDescription$1, F as getUri, Kt as setLabel$1, L as getObjectEchoUri, N as getDatabase$1, Rt as getTypeAnnotation, Vt as getTypename$1, Wt as setDescription$1, Zt as ParentId, _n as RelationSourceDXNId, bn as RelationTargetId, fn as MetaId, j as isInstanceOf, jt as getLabel$1, rn as getType$1, vn as RelationSourceId, yn as RelationTargetDXNId, yt as TypeAnnotationId } from "./chunk-Database.mjs";
6
6
  import { v as change, y as subscribe$1 } from "./chunk-ref.mjs";
7
7
  import { d as getSchema } from "./chunk-Type.mjs";
8
8
  import { n as Kind, o as SnapshotKindId, r as KindId } from "./chunk-Entity.mjs";
@@ -178,7 +178,7 @@ var getSourceURI = (value) => {
178
178
  invariant(EID.isEID(uri), void 0, {
179
179
  "~LogMeta": "~LogMeta",
180
180
  F: __dxlog_file,
181
- L: 272,
181
+ L: 271,
182
182
  S: void 0,
183
183
  A: ["EID.isEID(uri)", ""]
184
184
  });
@@ -198,7 +198,7 @@ var getTargetURI = (value) => {
198
198
  invariant(EID.isEID(uri), void 0, {
199
199
  "~LogMeta": "~LogMeta",
200
200
  F: __dxlog_file,
201
- L: 287,
201
+ L: 286,
202
202
  S: void 0,
203
203
  A: ["EID.isEID(uri)", ""]
204
204
  });
@@ -377,7 +377,7 @@ var deleteKeys = (entity, source) => deleteKeys$1(entity, source);
377
377
  * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`
378
378
  * parameters, so there is no compile-time error. Enforcement is runtime-only.
379
379
  *
380
- * @performance O(t) in the tag count; dedupes by ref URI before appending.
380
+ * @performance O(t) in the tag count; dedupes by tag id before appending.
381
381
  */
382
382
  var addTag = (entity, tag) => addTag$1(entity, tag);
383
383
  /**