@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-Relation.mjs","names":["internal.TypeAnnotationId","internal.ANY_OBJECT_TYPENAME","internal.ANY_OBJECT_VERSION","entityInternal.RelationSourceId","entityInternal.RelationTargetId","Type.getSchema","internal.getTypeAnnotation","internal.ParentId","internal.MetaId","internal.getObjectEchoUri","internal.RelationSourceDXNId","internal.RelationTargetDXNId","internal.makeObject","internal.isInstanceOf","Entity.KindId","Entity.SnapshotKindId","Obj.isObject","internal.RelationSourceId","internal.RelationTargetId","internal.getSnapshot","internal.subscribe","internal.setValue","internal.getUri","internal.getTypeURI","internal.getType","internal.getTypename","internal.getDatabase","internal.getMetaChecked","internal.getKeys","internal.deleteKeys","internal.addTag","internal.removeTag","internal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.setDescription","internal.objectToJSON","internal.sortByLabel","internal.sortByTypename","internal.sort","internal.VersionTypeId","internal.isVersion","internal.version","objInternal.makeRelation"],"sources":["../../src/Relation.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, type EntityId, type URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport * as entityInternal from './internal/Entity/index.ts';\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport * as Obj from './Obj.ts';\nimport type * as Ref from './Ref.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\nexport type Endpoints<Source, Target> = {\n [Source]: Source;\n [Target]: Target;\n};\n\n/**\n * Base type for all ECHO relations.\n * @private\n */\ninterface BaseRelation<Source, Target>\n extends internal.AnyEntity, Endpoints<Source, Target>, Entity.OfKind<internal.EntityKind.Relation> {}\n\n/**\n * Relation with no known properties beyond id, kind, source, and target.\n * Use this when the relation's schema/properties are not known.\n *\n * NOTE: This is a TypeScript type only, not a schema.\n * To validate that a value is an ECHO relation, use `Relation.isRelation`.\n */\nexport interface Unknown extends BaseRelation<Obj.Unknown, Obj.Unknown> {}\n\n/**\n * Runtime Effect schema for any ECHO relation.\n * Use for validation, parsing, or as a reference target for collections.\n * A relation has `id`, source, and target fields plus any additional properties.\n *\n * NOTE: `Schema.is(Type.Relation)` does STRUCTURAL validation only (checks for `id` field).\n * Use `Relation.isRelation()` 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.Relation)(unknownValue)) { ... }\n *\n * // ECHO instance type guard (checks KindId brand)\n * if (Relation.isRelation(unknownValue)) { ... }\n * ```\n */\n// TODO(dmaretskyi): Change ObjModule.Any to ObjModule.Unknown to have stricter types.\nexport const Unknown: internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Relation> = 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.Relation,\n typename: 'org.dxos.schema.anyRelation',\n version: '0.0.0',\n sourceSchema: DXN.make(internal.ANY_OBJECT_TYPENAME, internal.ANY_OBJECT_VERSION),\n targetSchema: DXN.make(internal.ANY_OBJECT_TYPENAME, internal.ANY_OBJECT_VERSION),\n },\n }),\n) as unknown as internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Relation>;\n\n/**\n * Relation type with specific source and target types.\n */\nexport type OfShape<Source extends Obj.Unknown, Target extends Obj.Unknown, Props> = BaseRelation<Source, Target> &\n Props;\n\n/**\n * Base type for snapshot relations (has SnapshotKindId instead of KindId).\n */\ninterface BaseRelationSnapshot<Source, Target> extends internal.AnyEntity, Endpoints<Source, Target> {\n readonly [Entity.SnapshotKindId]: internal.EntityKind.Relation;\n readonly id: EntityId;\n}\n\n/**\n * JSON-encoded properties for relations.\n */\nexport interface BaseRelationJson {\n id: string;\n [internal.ATTR_RELATION_SOURCE]: string;\n [internal.ATTR_RELATION_TARGET]: string;\n}\n\n/**\n * Immutable snapshot of an ECHO relation.\n * Branded with SnapshotKindId (not KindId).\n * Property values are frozen at the time the snapshot was created.\n * Returned by getSnapshot() and hooks.\n */\nexport type Snapshot<T extends Unknown = Unknown> = Omit<T, Entity.KindId> &\n BaseRelationSnapshot<Obj.Unknown, Obj.Unknown>;\n\nexport const Source: unique symbol = entityInternal.RelationSourceId as any;\nexport type Source = typeof Source;\n\nexport const Target: unique symbol = entityInternal.RelationTargetId as any;\nexport type Target = typeof Target;\n\n/**\n * Get relation source type.\n */\nexport type SourceOf<A> = A extends Endpoints<infer S, infer _T> ? S : never;\n\n/**\n * Get relation target type.\n */\nexport type TargetOf<A> = A extends Endpoints<infer _S, infer T> ? T : never;\n\n/**\n * Internal props type for relation instance creation.\n */\ntype MakePropsInternal<T extends Endpoints<any, any>> = {\n id?: EntityId;\n [Meta]?: Partial<internal.EntityMeta>;\n [Source]: T[Source];\n [Target]: T[Target];\n} & Entity.Properties<T>;\n\n/**\n * Props type for relation creation with a given schema. Accepts a `Type.AnyRelation`\n * entity (created with `Type.makeRelation`) and derives the props shape via\n * `Type.InstanceType`. Object-kind entities are rejected at the type level —\n * use `Obj.MakeProps` for those.\n */\nexport type MakeProps<S extends Type.AnyRelation> = MakePropsInternal<Type.InstanceType<S>>;\n\n/**\n * Creates new relation.\n * @param schema - Relation schema.\n * @param props - Relation properties. Endpoints are passed as [Relation.Source] and [Relation.Target] keys.\n * @param meta - Relation metadata. (deprecated; use [Obj.Meta] instead)\n * @returns\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 */\n// NOTE: Writing the definition this way (with generic over schema) makes typescript perfer to infer the type from the first param (this schema) rather than the second param (the props).\n// TODO(dmaretskyi): Move meta into props.\nexport const make = <T extends Type.AnyRelation>(\n type: T,\n props: NoInfer<MakeProps<T>>,\n): Type.InstanceType<T> & Entity.OfKind<typeof Entity.Kind.Relation> => {\n const schema = Type.getSchema(type);\n assertArgument(\n internal.getTypeAnnotation(schema)?.kind === internal.EntityKind.Relation,\n 'schema',\n 'Expected a relation schema',\n );\n assertArgument(props[internal.ParentId] === undefined, 'props', 'Parent is not allowed for relations');\n\n let meta: internal.EntityMeta | undefined = undefined;\n\n if (props[internal.MetaId] != null) {\n meta = props[internal.MetaId] as any;\n delete props[internal.MetaId];\n }\n\n const sourceDXN = internal.getObjectEchoUri(props[Source]) ?? raise(new Error('Unresolved relation source'));\n const targetDXN = internal.getObjectEchoUri(props[Target]) ?? raise(new Error('Unresolved relation target'));\n\n (props as any)[internal.RelationSourceDXNId] = sourceDXN;\n (props as any)[internal.RelationTargetDXNId] = targetDXN;\n\n // Pass the type entity through as `typeSource` so the resulting instance\n // carries a back-reference resolvable via `Relation.getType` / `Entity.getType`.\n return internal.makeObject(schema as any, props as any, meta, type as any) as any;\n};\n\n/**\n * Test if a value is an instance of a given relation type.\n *\n * Mirrors `Obj.instanceOf` but only accepts `Type.AnyRelation` — use\n * `Obj.instanceOf` for objects and `Type.isType` for `Type.Type` entities.\n *\n * @example\n * ```ts\n * const isEmployedBy = Relation.instanceOf(EmployedBy);\n * if (isEmployedBy(relation)) {\n * // relation is EmployedBy\n * }\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n <S extends Type.AnyRelation>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyRelation>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyRelation, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Type guard for relations.\n * Returns true for both reactive relations and relation snapshots.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isRelation = (value: unknown): value is Unknown => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (internal.ATTR_RELATION_SOURCE in value || internal.ATTR_RELATION_TARGET in value) {\n return true;\n }\n\n // Check for reactive relation (KindId) or snapshot (SnapshotKindId).\n const kind = (value as any)[Entity.KindId] ?? (value as any)[Entity.SnapshotKindId];\n return kind === internal.EntityKind.Relation;\n};\n\n/**\n * Determine if a value is an ECHO relation snapshot.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (value: unknown): value is Snapshot => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return (value as any)[Entity.SnapshotKindId] === internal.EntityKind.Relation;\n};\n\n/**\n * Sets a relation as the parent of an object: the object cascade-deletes with the relation and is\n * persisted transitively when the relation is added. The delete-cascade resolves the parent by id\n * regardless of kind. The object-parent counterpart is {@link Obj.setParent}.\n *\n * @performance O(1) slot write; unlike `Obj.setParent` it does not scan the parent.\n */\nexport const setParent = (entity: Obj.Unknown, parent: Unknown): Obj.Unknown => {\n assertArgument(Obj.isObject(entity), 'Expected an object');\n assertArgument(isRelation(parent), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(entity);\n assumeType<internal.InternalObjectProps>(parent);\n entity[internal.ParentId] = parent;\n return entity;\n};\n\n/**\n * @returns Relation source URI.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1) read of the stored endpoint URI.\n */\nexport const getSourceURI = (value: Unknown | Snapshot): EID.EID => {\n assertArgument(isRelation(value), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(value);\n const uri = (value as internal.InternalObjectProps)[internal.RelationSourceDXNId];\n invariant(EID.isEID(uri));\n return uri;\n};\n\n/**\n * @returns Relation target URI.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1) read of the stored endpoint URI.\n */\nexport const getTargetURI = (value: Unknown | Snapshot): EID.EID => {\n assertArgument(isRelation(value), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(value);\n const uri = (value as internal.InternalObjectProps)[internal.RelationTargetDXNId];\n invariant(EID.isEID(uri));\n return uri;\n};\n\n/**\n * @returns Relation source.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1); reads the endpoint slot (a working-set lookup for database relations, never a load).\n */\nexport const getSource = <T extends Unknown | Snapshot>(relation: T): SourceOf<T> => {\n assertArgument(isRelation(relation), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(relation);\n const obj = (relation as internal.InternalObjectProps)[internal.RelationSourceId];\n if (obj === undefined) {\n throw new Error(`Relation source could not be resolved.`);\n }\n return obj as SourceOf<T>;\n};\n\n/**\n * @returns Relation target.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1); reads the endpoint slot (a working-set lookup for database relations, never a load).\n */\nexport const getTarget = <T extends Unknown | Snapshot>(relation: T): TargetOf<T> => {\n assertArgument(isRelation(relation), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(relation);\n const obj = (relation as internal.InternalObjectProps)[internal.RelationTargetId];\n if (obj === undefined) {\n throw new Error(`Relation target could not be resolved.`);\n }\n return obj as TargetOf<T>;\n};\n\n//\n// Change\n//\n\n/**\n * Makes all properties mutable recursively.\n * Used to provide a mutable view of a relation within `Relation.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an echo relation 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 `Relation.update` will throw\n * an error for echo relations.\n *\n * @param relation - The echo relation to mutate. Use `Obj.update` for objects.\n * @param callback - The callback that performs mutations on the relation.\n *\n * @example\n * ```ts\n * const worksFor = Relation.make(EmployedBy, {\n * [Relation.Source]: person,\n * [Relation.Target]: company,\n * role: 'Engineer',\n * });\n *\n * // Mutate within Relation.update\n * Relation.update(worksFor, (obj) => {\n * obj.role = 'Senior Engineer';\n * });\n * ```\n *\n * Note: Only accepts relations. Use `Obj.update` for objects.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = <T extends Unknown>(relation: T, callback: internal.ChangeCallback<T>): void => {\n internal.change(relation, callback);\n};\n\n//\n// Snapshot\n//\n\n/**\n * Returns an immutable snapshot of a relation.\n * The snapshot is branded with SnapshotKindId instead of KindId,\n * making it distinguishable from the reactive relation 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>(rel: T) => Snapshot<T> = internal.getSnapshot as any;\n\n//\n// Subscribe\n//\n\n/**\n * Subscribe to relation updates.\n * The callback is called synchronously when the relation is modified.\n * Only accepts reactive relations (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 = (rel: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(rel, callback);\n};\n\n//\n// Property Access\n//\n\n/**\n * Get a deeply nested property from a relation.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(path length) property walk; no schema lookup.\n */\nexport const getValue = (rel: Unknown | Snapshot, path: readonly (string | number)[]): any => {\n return SchemaEx.getValue(rel, SchemaEx.createJsonPath(path));\n};\n\n/**\n * Set a deeply nested property on a relation.\n * Must be called within a `Relation.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(path length) schema-guided walk; each missing level scans its schema properties once.\n */\nexport const setValue: (rel: Mutable<Unknown>, path: readonly (string | number)[], value: any) => void =\n internal.setValue as any;\n\n//\n// Type\n//\n\n/**\n * Get the canonical URI of the relation. Returns `URI.URI` — today always an EID,\n * but future entity kinds may surface other URI schemes; narrow with `EID.parse(uri)`\n * or `DXN.tryMake(uri)` at the point of use. Accepts both reactive relations and snapshots.\n *\n * @param options.prefer - Controls the URI form (see {@link internal.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 internal.getUri(entity, options);\n\n/**\n * @returns The DXN of the relation's type.\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI: (obj: internal.AnyProperties) => URI.URI | undefined = internal.getTypeURI;\n\n/**\n * Get the type entity (`Type.AnyRelation`) the relation was created from.\n *\n * Returns `undefined` when the relation's type isn't registered in this\n * runtime (e.g. a freshly deserialized snapshot whose type entity hasn't been\n * wired up yet, or a relation loaded from storage before its schema is known).\n * To 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 = (relation: Unknown | Snapshot): Type.AnyRelation | undefined =>\n internal.getType(relation) as Type.AnyRelation | undefined;\n\n/**\n * @returns The typename of the relation's type.\n * Accepts both reactive relations and snapshots.\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 relation belongs to.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Unknown | Snapshot): Database.Database | undefined => internal.getDatabase(entity);\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 */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Mutable meta type returned by `Relation.getMeta` inside a `Relation.update` callback.\n */\nexport type Meta = internal.Meta;\n\n/**\n * Get the metadata for a relation.\n * Returns mutable meta when passed a mutable relation (inside `Relation.update` callback).\n * Returns read-only meta when passed a regular relation or snapshot.\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 relation from the specified source.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys = (entity: Unknown | Snapshot, source: string): ForeignKey[] => internal.getKeys(entity, source);\n\n/**\n * Delete all keys from the relation for the specified source.\n * Must be called within a `Relation.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 relation.\n * Must be called within a `Relation.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 relation.\n * Must be called within a `Relation.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 relation is deleted.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(1) slot read.\n */\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => internal.isDeleted(entity);\n\n//\n// Annotations\n//\n\n/**\n * Get the label of the relation.\n * Accepts both reactive relations and snapshots.\n *\n * @param options.fallback `'typename'` returns the relation'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 relation.\n * Must be called within a `Relation.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 relation.\n * Accepts both reactive relations 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 * Set the description of the relation.\n * Must be called within a `Relation.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// JSON\n//\n\n/**\n * JSON representation of a relation.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Converts relation to its JSON representation.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\nexport const toJSON = (entity: Unknown | Snapshot): JSON => internal.objectToJSON(entity);\n\n//\n// Sorting\n//\n\n/**\n * Comparator function type for sorting relations.\n * Accepts both reactive relations and snapshots.\n */\nexport type Comparator = internal.Comparator<Unknown | Snapshot>;\n\n/**\n * Comparator that orders relations 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 relations 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;\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/**\n * Represent relation version.\n */\nexport type Version = internal.EntityVersion;\n\n/**\n * Returns the version of the relation.\n * Accepts both reactive relations 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 a relation.\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeRelation;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,IAAa,UAA4E,OAAO,eAC9F,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC,GACnC,CAAC,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC,CAC/C,CAAC,CAAC,KACA,OAAO,SAAS,GACbA,mBAA4B;CAC3B,MAAA,KAAkB;CAClB,UAAU;CACV,SAAS;CACT,cAAc,IAAI,KAAKC,qBAA8BC,kBAA2B;CAChF,cAAc,IAAI,KAAKD,qBAA8BC,kBAA2B;AAClF,EACF,CAAC,CACH;AAkCA,IAAa,SAAwBC;AAGrC,IAAa,SAAwBC;;;;;;;;;;;AA2CrC,IAAa,QACX,MACA,UACsE;CACtE,MAAM,SAASC,UAAe,IAAI;CAClC,eACEC,kBAA2B,MAAM,CAAC,EAAE,SAAA,WAA6B,UACjE,UACA,4BACF;CACA,eAAe,MAAMC,cAAuB,KAAA,GAAW,SAAS,qCA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WAAW,aACtBC,UAAiB,QAAQ;;;;;;;AAQ3B,IAAa,eAAe,WAAmDC,cAAqB,MAAM;;;;;;;AAY1G,IAAa,eAAe,WAA8DC,cAAqB,MAAM;;;;;;AAWrH,IAAa,OAAOlB;AAsBpB,SAAgB,QAAQ,QAAoE;CAC1F,OAAOmB,eAAwB,MAAM;AACvC;;;;;;;AAQA,IAAa,WAAW,QAA4B,WAAiCC,UAAiB,QAAQ,MAAM;;;;;;;;;;AAWpH,IAAa,cAAc,QAA0B,WAAyBC,aAAoB,QAAQ,MAAM;;;;;;;;;;AAWhH,IAAa,UAAU,QAA0B,QAAgCC,SAAgB,QAAQ,GAAG;;;;;;;;;;AAW5G,IAAa,aAAa,QAA0B,QAAgCC,YAAmB,QAAQ,GAAG;;;;;;;AAQlH,IAAa,aAAa,WAAwCC,YAAmB,MAAM;;;;;;;;;;AAe3F,IAAa,YAAY,QAA4B,YACnDC,WAAkB,QAAQ,OAAO;;;;;;;;;;AAWnC,IAAa,YAAY,QAA0B,UAAwBC,WAAkB,QAAQ,KAAK;;;;;;;AAQ1G,IAAa,kBAAkB,WAAmDC,iBAAwB,MAAM;;;;;;;;;;AAWhH,IAAa,kBAAkB,QAA0B,gBACvDC,iBAAwB,QAAQ,WAAW;;;;;;;AAiB7C,IAAa,UAAU,WAAqCC,aAAsB,MAAM;;;;;;;AAkBxF,IAAa,cAA0BC;;;;;;AAMvC,IAAa,iBAA6BC;;;;;;AAM1C,IAAa,QAAQ,GAAG,gBAA0CC,OAAc,GAAG,WAAW;AAM9F,IAAa,gBAAgBC;;;;;;AAM7B,IAAa,YAAYC;;;;;;;AAazB,IAAa,WAAW,WAAwCC,UAAiB,MAAM;;;;;;AAWvF,IAAa,OAAOC"}
1
+ {"version":3,"file":"chunk-Relation.mjs","names":["internal.TypeAnnotationId","internal.ANY_OBJECT_TYPENAME","internal.ANY_OBJECT_VERSION","entityInternal.RelationSourceId","entityInternal.RelationTargetId","Type.getSchema","internal.getTypeAnnotation","internal.ParentId","internal.MetaId","internal.getObjectEchoUri","internal.RelationSourceDXNId","internal.RelationTargetDXNId","internal.makeObject","internal.isInstanceOf","Entity.KindId","Entity.SnapshotKindId","Obj.isObject","internal.RelationSourceId","internal.RelationTargetId","internal.getSnapshot","internal.subscribe","internal.setValue","internal.getUri","internal.getTypeURI","internal.getType","internal.getTypename","internal.getDatabase","internal.getMetaChecked","internal.getKeys","internal.deleteKeys","internal.addTag","internal.removeTag","internal.isDeleted","internal.getLabel","internal.setLabel","internal.getDescription","internal.setDescription","internal.objectToJSON","internal.sortByLabel","internal.sortByTypename","internal.sort","internal.VersionTypeId","internal.isVersion","internal.version","objInternal.makeRelation"],"sources":["../../src/Relation.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport { raise } from '@dxos/debug';\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport * as SchemaEx from '@dxos/effect/SchemaEx';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, type EntityId, type URI } from '@dxos/keys';\nimport { assumeType } from '@dxos/util';\n\nimport type * as Database from './Database.ts';\nimport * as Entity from './Entity.ts';\nimport * as entityInternal from './internal/Entity/index.ts';\nimport * as internal from './internal/index.ts';\nimport * as objInternal from './internal/Obj/index.ts';\nimport * as Obj from './Obj.ts';\nimport type * as Tag from './Tag.ts';\nimport * as Type from './Type.ts';\n\nexport type Endpoints<Source, Target> = {\n [Source]: Source;\n [Target]: Target;\n};\n\n/**\n * Base type for all ECHO relations.\n * @private\n */\ninterface BaseRelation<Source, Target>\n extends internal.AnyEntity, Endpoints<Source, Target>, Entity.OfKind<internal.EntityKind.Relation> {}\n\n/**\n * Relation with no known properties beyond id, kind, source, and target.\n * Use this when the relation's schema/properties are not known.\n *\n * NOTE: This is a TypeScript type only, not a schema.\n * To validate that a value is an ECHO relation, use `Relation.isRelation`.\n */\nexport interface Unknown extends BaseRelation<Obj.Unknown, Obj.Unknown> {}\n\n/**\n * Runtime Effect schema for any ECHO relation.\n * Use for validation, parsing, or as a reference target for collections.\n * A relation has `id`, source, and target fields plus any additional properties.\n *\n * NOTE: `Schema.is(Type.Relation)` does STRUCTURAL validation only (checks for `id` field).\n * Use `Relation.isRelation()` 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.Relation)(unknownValue)) { ... }\n *\n * // ECHO instance type guard (checks KindId brand)\n * if (Relation.isRelation(unknownValue)) { ... }\n * ```\n */\n// TODO(dmaretskyi): Change ObjModule.Any to ObjModule.Unknown to have stricter types.\nexport const Unknown: internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Relation> = 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.Relation,\n typename: 'org.dxos.schema.anyRelation',\n version: '0.0.0',\n sourceSchema: DXN.make(internal.ANY_OBJECT_TYPENAME, internal.ANY_OBJECT_VERSION),\n targetSchema: DXN.make(internal.ANY_OBJECT_TYPENAME, internal.ANY_OBJECT_VERSION),\n },\n }),\n) as unknown as internal.UnknownTypeSchema<Unknown, typeof Entity.Kind.Relation>;\n\n/**\n * Relation type with specific source and target types.\n */\nexport type OfShape<Source extends Obj.Unknown, Target extends Obj.Unknown, Props> = BaseRelation<Source, Target> &\n Props;\n\n/**\n * Base type for snapshot relations (has SnapshotKindId instead of KindId).\n */\ninterface BaseRelationSnapshot<Source, Target> extends internal.AnyEntity, Endpoints<Source, Target> {\n readonly [Entity.SnapshotKindId]: internal.EntityKind.Relation;\n readonly id: EntityId;\n}\n\n/**\n * JSON-encoded properties for relations.\n */\nexport interface BaseRelationJson {\n id: string;\n [internal.ATTR_RELATION_SOURCE]: string;\n [internal.ATTR_RELATION_TARGET]: string;\n}\n\n/**\n * Immutable snapshot of an ECHO relation.\n * Branded with SnapshotKindId (not KindId).\n * Property values are frozen at the time the snapshot was created.\n * Returned by getSnapshot() and hooks.\n */\nexport type Snapshot<T extends Unknown = Unknown> = Omit<T, Entity.KindId> &\n BaseRelationSnapshot<Obj.Unknown, Obj.Unknown>;\n\nexport const Source: unique symbol = entityInternal.RelationSourceId as any;\nexport type Source = typeof Source;\n\nexport const Target: unique symbol = entityInternal.RelationTargetId as any;\nexport type Target = typeof Target;\n\n/**\n * Get relation source type.\n */\nexport type SourceOf<A> = A extends Endpoints<infer S, infer _T> ? S : never;\n\n/**\n * Get relation target type.\n */\nexport type TargetOf<A> = A extends Endpoints<infer _S, infer T> ? T : never;\n\n/**\n * Internal props type for relation instance creation.\n */\ntype MakePropsInternal<T extends Endpoints<any, any>> = {\n id?: EntityId;\n [Meta]?: Partial<internal.EntityMeta>;\n [Source]: T[Source];\n [Target]: T[Target];\n} & Entity.Properties<T>;\n\n/**\n * Props type for relation creation with a given schema. Accepts a `Type.AnyRelation`\n * entity (created with `Type.makeRelation`) and derives the props shape via\n * `Type.InstanceType`. Object-kind entities are rejected at the type level —\n * use `Obj.MakeProps` for those.\n */\nexport type MakeProps<S extends Type.AnyRelation> = MakePropsInternal<Type.InstanceType<S>>;\n\n/**\n * Creates new relation.\n * @param schema - Relation schema.\n * @param props - Relation properties. Endpoints are passed as [Relation.Source] and [Relation.Target] keys.\n * @param meta - Relation metadata. (deprecated; use [Obj.Meta] instead)\n * @returns\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 */\n// NOTE: Writing the definition this way (with generic over schema) makes typescript perfer to infer the type from the first param (this schema) rather than the second param (the props).\n// TODO(dmaretskyi): Move meta into props.\nexport const make = <T extends Type.AnyRelation>(\n type: T,\n props: NoInfer<MakeProps<T>>,\n): Type.InstanceType<T> & Entity.OfKind<typeof Entity.Kind.Relation> => {\n const schema = Type.getSchema(type);\n assertArgument(\n internal.getTypeAnnotation(schema)?.kind === internal.EntityKind.Relation,\n 'schema',\n 'Expected a relation schema',\n );\n assertArgument(props[internal.ParentId] === undefined, 'props', 'Parent is not allowed for relations');\n\n let meta: internal.EntityMeta | undefined = undefined;\n\n if (props[internal.MetaId] != null) {\n meta = props[internal.MetaId] as any;\n delete props[internal.MetaId];\n }\n\n const sourceDXN = internal.getObjectEchoUri(props[Source]) ?? raise(new Error('Unresolved relation source'));\n const targetDXN = internal.getObjectEchoUri(props[Target]) ?? raise(new Error('Unresolved relation target'));\n\n (props as any)[internal.RelationSourceDXNId] = sourceDXN;\n (props as any)[internal.RelationTargetDXNId] = targetDXN;\n\n // Pass the type entity through as `typeSource` so the resulting instance\n // carries a back-reference resolvable via `Relation.getType` / `Entity.getType`.\n return internal.makeObject(schema as any, props as any, meta, type as any) as any;\n};\n\n/**\n * Test if a value is an instance of a given relation type.\n *\n * Mirrors `Obj.instanceOf` but only accepts `Type.AnyRelation` — use\n * `Obj.instanceOf` for objects and `Type.isType` for `Type.Type` entities.\n *\n * @example\n * ```ts\n * const isEmployedBy = Relation.instanceOf(EmployedBy);\n * if (isEmployedBy(relation)) {\n * // relation is EmployedBy\n * }\n * ```\n *\n * @performance O(1) type-URI comparison with a typename fallback; no schema validation.\n */\nexport const instanceOf: {\n <S extends Type.AnyRelation>(schema: S): (value: unknown) => value is Type.InstanceType<S>;\n <S extends Type.AnyRelation>(schema: S, value: unknown): value is Type.InstanceType<S>;\n} = ((...args: [schema: Type.AnyRelation, value?: unknown]) => {\n if (args.length === 1) {\n return (entity: unknown) => internal.isInstanceOf(args[0], entity);\n }\n return internal.isInstanceOf(args[0], args[1]);\n}) as any;\n\n/**\n * Type guard for relations.\n * Returns true for both reactive relations and relation snapshots.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isRelation = (value: unknown): value is Unknown => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (internal.ATTR_RELATION_SOURCE in value || internal.ATTR_RELATION_TARGET in value) {\n return true;\n }\n\n // Check for reactive relation (KindId) or snapshot (SnapshotKindId).\n const kind = (value as any)[Entity.KindId] ?? (value as any)[Entity.SnapshotKindId];\n return kind === internal.EntityKind.Relation;\n};\n\n/**\n * Determine if a value is an ECHO relation snapshot.\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isSnapshot = (value: unknown): value is Snapshot => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return (value as any)[Entity.SnapshotKindId] === internal.EntityKind.Relation;\n};\n\n/**\n * Sets a relation as the parent of an object: the object cascade-deletes with the relation and is\n * persisted transitively when the relation is added. The delete-cascade resolves the parent by id\n * regardless of kind. The object-parent counterpart is {@link Obj.setParent}.\n *\n * @performance O(1) slot write; unlike `Obj.setParent` it does not scan the parent.\n */\nexport const setParent = (entity: Obj.Unknown, parent: Unknown): Obj.Unknown => {\n assertArgument(Obj.isObject(entity), 'Expected an object');\n assertArgument(isRelation(parent), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(entity);\n assumeType<internal.InternalObjectProps>(parent);\n entity[internal.ParentId] = parent;\n return entity;\n};\n\n/**\n * @returns Relation source URI.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1) read of the stored endpoint URI.\n */\nexport const getSourceURI = (value: Unknown | Snapshot): EID.EID => {\n assertArgument(isRelation(value), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(value);\n const uri = (value as internal.InternalObjectProps)[internal.RelationSourceDXNId];\n invariant(EID.isEID(uri));\n return uri;\n};\n\n/**\n * @returns Relation target URI.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1) read of the stored endpoint URI.\n */\nexport const getTargetURI = (value: Unknown | Snapshot): EID.EID => {\n assertArgument(isRelation(value), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(value);\n const uri = (value as internal.InternalObjectProps)[internal.RelationTargetDXNId];\n invariant(EID.isEID(uri));\n return uri;\n};\n\n/**\n * @returns Relation source.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1); reads the endpoint slot (a working-set lookup for database relations, never a load).\n */\nexport const getSource = <T extends Unknown | Snapshot>(relation: T): SourceOf<T> => {\n assertArgument(isRelation(relation), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(relation);\n const obj = (relation as internal.InternalObjectProps)[internal.RelationSourceId];\n if (obj === undefined) {\n throw new Error(`Relation source could not be resolved.`);\n }\n return obj as SourceOf<T>;\n};\n\n/**\n * @returns Relation target.\n * Accepts both reactive relations and snapshots.\n * @throws If the object is not a relation.\n *\n * @performance O(1); reads the endpoint slot (a working-set lookup for database relations, never a load).\n */\nexport const getTarget = <T extends Unknown | Snapshot>(relation: T): TargetOf<T> => {\n assertArgument(isRelation(relation), 'Expected a relation');\n assumeType<internal.InternalObjectProps>(relation);\n const obj = (relation as internal.InternalObjectProps)[internal.RelationTargetId];\n if (obj === undefined) {\n throw new Error(`Relation target could not be resolved.`);\n }\n return obj as TargetOf<T>;\n};\n\n//\n// Change\n//\n\n/**\n * Makes all properties mutable recursively.\n * Used to provide a mutable view of a relation within `Relation.update`.\n */\nexport type Mutable<T> = internal.Mutable<T>;\n\n/**\n * Perform mutations on an echo relation 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 `Relation.update` will throw\n * an error for echo relations.\n *\n * @param relation - The echo relation to mutate. Use `Obj.update` for objects.\n * @param callback - The callback that performs mutations on the relation.\n *\n * @example\n * ```ts\n * const worksFor = Relation.make(EmployedBy, {\n * [Relation.Source]: person,\n * [Relation.Target]: company,\n * role: 'Engineer',\n * });\n *\n * // Mutate within Relation.update\n * Relation.update(worksFor, (obj) => {\n * obj.role = 'Senior Engineer';\n * });\n * ```\n *\n * Note: Only accepts relations. Use `Obj.update` for objects.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = <T extends Unknown>(relation: T, callback: internal.ChangeCallback<T>): void => {\n internal.change(relation, callback);\n};\n\n//\n// Snapshot\n//\n\n/**\n * Returns an immutable snapshot of a relation.\n * The snapshot is branded with SnapshotKindId instead of KindId,\n * making it distinguishable from the reactive relation 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>(rel: T) => Snapshot<T> = internal.getSnapshot as any;\n\n//\n// Subscribe\n//\n\n/**\n * Subscribe to relation updates.\n * The callback is called synchronously when the relation is modified.\n * Only accepts reactive relations (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 = (rel: Unknown, callback: () => void): (() => void) => {\n return internal.subscribe(rel, callback);\n};\n\n//\n// Property Access\n//\n\n/**\n * Get a deeply nested property from a relation.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(path length) property walk; no schema lookup.\n */\nexport const getValue = (rel: Unknown | Snapshot, path: readonly (string | number)[]): any => {\n return SchemaEx.getValue(rel, SchemaEx.createJsonPath(path));\n};\n\n/**\n * Set a deeply nested property on a relation.\n * Must be called within a `Relation.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(path length) schema-guided walk; each missing level scans its schema properties once.\n */\nexport const setValue: (rel: Mutable<Unknown>, path: readonly (string | number)[], value: any) => void =\n internal.setValue as any;\n\n//\n// Type\n//\n\n/**\n * Get the canonical URI of the relation. Returns `URI.URI` — today always an EID,\n * but future entity kinds may surface other URI schemes; narrow with `EID.parse(uri)`\n * or `DXN.tryMake(uri)` at the point of use. Accepts both reactive relations and snapshots.\n *\n * @param options.prefer - Controls the URI form (see {@link internal.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 internal.getUri(entity, options);\n\n/**\n * @returns The DXN of the relation's type.\n *\n * @performance O(1) read of the stored type URI.\n */\nexport const getTypeURI: (obj: internal.AnyProperties) => URI.URI | undefined = internal.getTypeURI;\n\n/**\n * Get the type entity (`Type.AnyRelation`) the relation was created from.\n *\n * Returns `undefined` when the relation's type isn't registered in this\n * runtime (e.g. a freshly deserialized snapshot whose type entity hasn't been\n * wired up yet, or a relation loaded from storage before its schema is known).\n * To 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 = (relation: Unknown | Snapshot): Type.AnyRelation | undefined =>\n internal.getType(relation) as Type.AnyRelation | undefined;\n\n/**\n * @returns The typename of the relation's type.\n * Accepts both reactive relations and snapshots.\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 relation belongs to.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (entity: Unknown | Snapshot): Database.Database | undefined => internal.getDatabase(entity);\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 */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Mutable meta type returned by `Relation.getMeta` inside a `Relation.update` callback.\n */\nexport type Meta = internal.Meta;\n\n/**\n * Get the metadata for a relation.\n * Returns mutable meta when passed a mutable relation (inside `Relation.update` callback).\n * Returns read-only meta when passed a regular relation or snapshot.\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 relation from the specified source.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(k) in the foreign-key count; allocates a filtered array.\n */\nexport const getKeys = (entity: Unknown | Snapshot, source: string): ForeignKey[] => internal.getKeys(entity, source);\n\n/**\n * Delete all keys from the relation for the specified source.\n * Must be called within a `Relation.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 relation.\n * Must be called within a `Relation.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 relation.\n * Must be called within a `Relation.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 relation is deleted.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(1) slot read.\n */\nexport const isDeleted = (entity: Unknown | Snapshot): boolean => internal.isDeleted(entity);\n\n//\n// Annotations\n//\n\n/**\n * Get the label of the relation.\n * Accepts both reactive relations and snapshots.\n *\n * @param options.fallback `'typename'` returns the relation'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 relation.\n * Must be called within a `Relation.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 relation.\n * Accepts both reactive relations 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 * Set the description of the relation.\n * Must be called within a `Relation.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// JSON\n//\n\n/**\n * JSON representation of a relation.\n */\nexport type JSON = internal.ObjectJSON;\n\n/**\n * Converts relation to its JSON representation.\n * Accepts both reactive relations and snapshots.\n *\n * @performance O(n) in entity size; serializes the whole entity on every call.\n */\nexport const toJSON = (entity: Unknown | Snapshot): JSON => internal.objectToJSON(entity);\n\n//\n// Sorting\n//\n\n/**\n * Comparator function type for sorting relations.\n * Accepts both reactive relations and snapshots.\n */\nexport type Comparator = internal.Comparator<Unknown | Snapshot>;\n\n/**\n * Comparator that orders relations 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 relations 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;\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/**\n * Represent relation version.\n */\nexport type Version = internal.EntityVersion;\n\n/**\n * Returns the version of the relation.\n * Accepts both reactive relations 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 a relation.\n *\n * @performance O(1) memoized atom-family lookup; every emission takes an O(n) `getSnapshot` of the entity.\n */\nexport const atom = objInternal.makeRelation;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,IAAa,UAA4E,OAAO,eAC9F,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC,GACnC,CAAC,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC,CAC/C,CAAC,CAAC,KACA,OAAO,SAAS,GACbA,mBAA4B;CAC3B,MAAA,KAAkB;CAClB,UAAU;CACV,SAAS;CACT,cAAc,IAAI,KAAKC,qBAA8BC,kBAA2B;CAChF,cAAc,IAAI,KAAKD,qBAA8BC,kBAA2B;AAClF,EACF,CAAC,CACH;AAkCA,IAAa,SAAwBC;AAGrC,IAAa,SAAwBC;;;;;;;;;;;AA2CrC,IAAa,QACX,MACA,UACsE;CACtE,MAAM,SAASC,UAAe,IAAI;CAClC,eACEC,kBAA2B,MAAM,CAAC,EAAE,SAAA,WAA6B,UACjE,UACA,4BACF;CACA,eAAe,MAAMC,cAAuB,KAAA,GAAW,SAAS,qCAAqC;CAErG,IAAI,OAAwC,KAAA;CAE5C,IAAI,MAAMC,WAAoB,MAAM;EAClC,OAAO,MAAMA;EACb,OAAO,MAAMA;CACf;CAEA,MAAM,YAAYC,iBAA0B,MAAM,OAAO,K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AOlB;AAsBpB,SAAgB,QAAQ,QAAoE;CAC1F,OAAOmB,eAAwB,MAAM;AACvC;;;;;;;AAQA,IAAa,WAAW,QAA4B,WAAiCC,UAAiB,QAAQ,MAAM;;;;;;;;;;AAWpH,IAAa,cAAc,QAA0B,WAAyBC,aAAoB,QAAQ,MAAM;;;;;;;;;;AAWhH,IAAa,UAAU,QAA0B,QAAuBC,SAAgB,QAAQ,GAAG;;;;;;;;;;AAWnG,IAAa,aAAa,QAA0B,QAAuBC,YAAmB,QAAQ,GAAG;;;;;;;AAQzG,IAAa,aAAa,WAAwCC,YAAmB,MAAM;;;;;;;;;;AAe3F,IAAa,YAAY,QAA4B,YACnDC,WAAkB,QAAQ,OAAO;;;;;;;;;;AAWnC,IAAa,YAAY,QAA0B,UAAwBC,WAAkB,QAAQ,KAAK;;;;;;;AAQ1G,IAAa,kBAAkB,WAAmDC,iBAAwB,MAAM;;;;;;;;;;AAWhH,IAAa,kBAAkB,QAA0B,gBACvDC,iBAAwB,QAAQ,WAAW;;;;;;;AAiB7C,IAAa,UAAU,WAAqCC,aAAsB,MAAM;;;;;;;AAkBxF,IAAa,cAA0BC;;;;;;AAMvC,IAAa,iBAA6BC;;;;;;AAM1C,IAAa,QAAQ,GAAG,gBAA0CC,OAAc,GAAG,WAAW;AAM9F,IAAa,gBAAgBC;;;;;;AAM7B,IAAa,YAAYC;;;;;;;AAazB,IAAa,WAAW,WAAwCC,UAAiB,MAAM;;;;;;AAWvF,IAAa,OAAOC"}
@@ -51,13 +51,27 @@ var registry = (location = "local") => ({
51
51
  * @example
52
52
  * ```ts
53
53
  * db.query(Query.select(Filter.feedCursor(cursor)).from(Scope.feed(feedUri)));
54
+ * db.query(Query.select(Filter.everything()).from(Scope.feed(feedUri, { branches: [null] })));
55
+ *
56
+ * // Walk the root branch and then the branch, 50 items at a time.
57
+ * db.query(
58
+ * Query.select(Filter.feedCursor({ begin: cursor, positions: 'local' }))
59
+ * .from(Scope.feed(feedUri, { walk: { branch } }))
60
+ * .orderBy(Order.natural('asc'))
61
+ * .limit(50),
62
+ * );
54
63
  * ```
55
64
  *
56
65
  * @performance O(1); builds a scope node.
57
66
  */
58
- var feed = (feedUri) => ({
67
+ var feed = (feedUri, options) => ({
59
68
  _tag: "feed",
60
- feedUri
69
+ feedUri,
70
+ ...options?.branches === void 0 ? {} : { branches: options.branches === "all" ? "all" : [...options.branches] },
71
+ ...options?.walk === void 0 ? {} : { walk: {
72
+ ...options.walk.branch !== void 0 ? { branch: options.walk.branch } : {},
73
+ ...options.walk.forks !== void 0 ? { forks: options.walk.forks } : {}
74
+ } }
61
75
  });
62
76
  //#endregion
63
77
  export { space as i, feed as n, registry as r, Scope_exports as t };
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Scope.mjs","names":[],"sources":["../../src/Scope.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\n/**\n * Scope targeting a space's automerge documents.\n *\n * With no `spaceId`, targets the owning space — i.e. the space of whichever database\n * executes the query — so callers can reference \"this space\" without looking up its id.\n *\n * @example\n * ```ts\n * db.query(Filter.type(Person).from(Scope.space())); // owning space\n * db.query(Filter.type(Person).from(Scope.space({ id: otherSpaceId }))); // a specific space\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const space = (options?: { id?: string; includeAllFeeds?: boolean }): QueryAST.SpaceScope => ({\n _tag: 'space',\n ...(options?.id !== undefined ? { spaceId: options.id } : {}),\n ...(options?.includeAllFeeds ? { includeAllFeeds: true } : {}),\n});\n\n/**\n * Scope targeting a code-shipped object/type registry.\n *\n * - `'local'` — the in-process registry attached to the hypergraph (default).\n * - `'remote'` — a remote registry service (not yet implemented).\n *\n * @example\n * ```ts\n * // Discover all types — persisted in the space and code-shipped in the registry.\n * db.query(Filter.type(Type.Type).from(Scope.space(), Scope.registry()));\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const registry = (location: 'local' | 'remote' = 'local'): QueryAST.RegistryScope => ({\n _tag: 'registry',\n location,\n});\n\n/**\n * Scope targeting a specific feed (by its underlying queue EID).\n *\n * To read only what follows a cursor, select with {@link Filter.feedCursor} — the bound is part of\n * the query, not of the scope.\n *\n * @example\n * ```ts\n * db.query(Query.select(Filter.feedCursor(cursor)).from(Scope.feed(feedUri)));\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const feed = (feedUri: string): QueryAST.FeedScope => ({\n _tag: 'feed',\n feedUri,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,SAAS,aAA+E;CACnG,MAAM;CACN,GAAI,SAAS,OAAO,KAAA,IAAY,EAAE,SAAS,QAAQ,GAAG,IAAI,CAAC;CAC3D,GAAI,SAAS,kBAAkB,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;AAgBA,IAAa,YAAY,WAA+B,aAAqC;CAC3F,MAAM;CACN;AACF;;;;;;;;;;;;;;AAeA,IAAa,QAAQ,aAAyC;CAC5D,MAAM;CACN;AACF"}
1
+ {"version":3,"file":"chunk-Scope.mjs","names":[],"sources":["../../src/Scope.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport { type QueryAST } from '@dxos/echo-protocol';\n\nimport type * as Feed from './Feed.ts';\n\n/**\n * Scope targeting a space's automerge documents.\n *\n * With no `spaceId`, targets the owning space — i.e. the space of whichever database\n * executes the query — so callers can reference \"this space\" without looking up its id.\n *\n * @example\n * ```ts\n * db.query(Filter.type(Person).from(Scope.space())); // owning space\n * db.query(Filter.type(Person).from(Scope.space({ id: otherSpaceId }))); // a specific space\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const space = (options?: { id?: string; includeAllFeeds?: boolean }): QueryAST.SpaceScope => ({\n _tag: 'space',\n ...(options?.id !== undefined ? { spaceId: options.id } : {}),\n ...(options?.includeAllFeeds ? { includeAllFeeds: true } : {}),\n});\n\n/**\n * Scope targeting a code-shipped object/type registry.\n *\n * - `'local'` — the in-process registry attached to the hypergraph (default).\n * - `'remote'` — a remote registry service (not yet implemented).\n *\n * @example\n * ```ts\n * // Discover all types — persisted in the space and code-shipped in the registry.\n * db.query(Filter.type(Type.Type).from(Scope.space(), Scope.registry()));\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const registry = (location: 'local' | 'remote' = 'local'): QueryAST.RegistryScope => ({\n _tag: 'registry',\n location,\n});\n\n/** Options for {@link feed}. */\nexport type FeedScopeOptions = {\n /**\n * Only items that are members of these branches: a branch id, or `null` for the main branch;\n * `'all'` reads every branch. Omit to read the main branch only.\n *\n * The filter is by membership only: a branch's ancestor items up to its fork point are not\n * included — read them with `Feed.readBranch` over the whole feed.\n */\n branches?: ReadonlyArray<Feed.BranchId | null> | 'all';\n\n /**\n * Reads the feed as a walk along the path from the root branch to `branch`, in local order; select\n * with {@link Filter.feedCursor} to start after a local cursor and order with `Order.natural` for the\n * direction. `'all'` walks every branch in local order. `forks` also gives the base item of each\n * branch that forks at a block the walk gives.\n */\n walk?: { branch?: Feed.BranchId | null | 'all'; forks?: boolean };\n};\n\n/**\n * Scope targeting a specific feed (by its underlying queue EID).\n *\n * To read only what follows a cursor, select with {@link Filter.feedCursor} — the bound is part of\n * the query, not of the scope.\n *\n * @example\n * ```ts\n * db.query(Query.select(Filter.feedCursor(cursor)).from(Scope.feed(feedUri)));\n * db.query(Query.select(Filter.everything()).from(Scope.feed(feedUri, { branches: [null] })));\n *\n * // Walk the root branch and then the branch, 50 items at a time.\n * db.query(\n * Query.select(Filter.feedCursor({ begin: cursor, positions: 'local' }))\n * .from(Scope.feed(feedUri, { walk: { branch } }))\n * .orderBy(Order.natural('asc'))\n * .limit(50),\n * );\n * ```\n *\n * @performance O(1); builds a scope node.\n */\nexport const feed = (feedUri: string, options?: FeedScopeOptions): QueryAST.FeedScope => ({\n _tag: 'feed',\n feedUri,\n ...(options?.branches === undefined\n ? {}\n : { branches: options.branches === 'all' ? ('all' as const) : [...options.branches] }),\n ...(options?.walk === undefined\n ? {}\n : {\n walk: {\n ...(options.walk.branch !== undefined ? { branch: options.walk.branch } : {}),\n ...(options.walk.forks !== undefined ? { forks: options.walk.forks } : {}),\n },\n }),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,SAAS,aAA+E;CACnG,MAAM;CACN,GAAI,SAAS,OAAO,KAAA,IAAY,EAAE,SAAS,QAAQ,GAAG,IAAI,CAAC;CAC3D,GAAI,SAAS,kBAAkB,EAAE,iBAAiB,KAAK,IAAI,CAAC;AAC9D;;;;;;;;;;;;;;;AAgBA,IAAa,YAAY,WAA+B,aAAqC;CAC3F,MAAM;CACN;AACF;;;;;;;;;;;;;;;;;;;;;;;AA4CA,IAAa,QAAQ,SAAiB,aAAoD;CACxF,MAAM;CACN;CACA,GAAI,SAAS,aAAa,KAAA,IACtB,CAAC,IACD,EAAE,UAAU,QAAQ,aAAa,QAAS,QAAkB,CAAC,GAAG,QAAQ,QAAQ,EAAE;CACtF,GAAI,SAAS,SAAS,KAAA,IAClB,CAAC,IACD,EACE,MAAM;EACJ,GAAI,QAAQ,KAAK,WAAW,KAAA,IAAY,EAAE,QAAQ,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC3E,GAAI,QAAQ,KAAK,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,KAAK,MAAM,IAAI,CAAC;CAC1E,EACF;AACN"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { _ as TagTypeDXN } from "./chunk-entity-dictionary.mjs";
3
- import { rt as LabelAnnotation } from "./chunk-Database.mjs";
2
+ import { v as TagTypeDXN } from "./chunk-entity-dictionary.mjs";
3
+ import { ct as LabelAnnotation } from "./chunk-Database.mjs";
4
4
  import { y as makeObject } from "./chunk-Type.mjs";
5
5
  import { G as make$1, at as update, n as Meta, w as getMeta } from "./chunk-Obj.mjs";
6
6
  import { F as type, m as foreignKeys } from "./chunk-Filter.mjs";
@@ -18,10 +18,10 @@ var Tag_exports = /* @__PURE__ */ __exportAll({
18
18
  make: () => make,
19
19
  sortTags: () => sortTags
20
20
  });
21
- var Tag = class extends makeObject(TagTypeDXN)(Schema.Struct({
21
+ var Tag = class extends makeObject(TagTypeDXN)({
22
22
  label: Schema.String,
23
23
  hue: Schema.optional(Schema.String)
24
- }).pipe(LabelAnnotation.set(["label"]))) {};
24
+ }, LabelAnnotation.set(["label"])) {};
25
25
  /**
26
26
  * Creates a new tag object.
27
27
  *
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Tag.mjs","names":["Type.makeObject","internal.TagTypeDXN","Obj.make","Obj.getMeta","Filter.foreignKeys","Obj.Meta","Filter.type"],"sources":["../../src/Tag.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\n\nimport type * as Database from './Database.ts';\nimport * as Filter from './Filter.ts';\nimport * as internal from './internal/index.ts';\nimport * as Obj from './Obj.ts';\nimport * as Type from './Type.ts';\n\nexport class Tag extends Type.makeObject<Tag>(internal.TagTypeDXN)(\n Schema.Struct({\n label: Schema.String,\n hue: Schema.optional(Schema.String), // TODO(burdon): Color name?\n }).pipe(internal.LabelAnnotation.set(['label'])),\n) {}\n\n/**\n * Creates a new tag object.\n *\n * @performance O(1); allocates an in-memory tag object.\n */\nexport const make = (props: Obj.MakeProps<typeof Tag>) => Obj.make(Tag, props);\n\nexport type Map = Record<string, Type.InstanceType<typeof Tag>>;\n\n/**\n * Origin domain for DXOS's own canonical tags — provider-agnostic identities (starred, sent, …) that\n * each provider maps its own vocabulary onto, so a Gmail star, a JMAP `$flagged` keyword and a\n * locally-toggled star all resolve to the same {@link Tag}.\n */\nexport const CANONICAL_ORIGIN = 'org.dxos.tag';\n\n/**\n * The tag's origin domain, or `undefined` when the user created it. Says who owns the tag and\n * therefore who may change it — see `Tag.md` §\"Tag origin\":\n *\n * - `undefined` — a user tag: rename, recolour, apply and remove are all the user's to do.\n * - {@link CANONICAL_ORIGIN} — a canonical DXOS tag: applied and removed locally, but its label and\n * hue are fixed (a provider may be mapping its own vocabulary onto it).\n * - anything else — a foreign provider domain (e.g. `com.google.gmail`): read-only, since sync owns\n * both the tag and which objects carry it.\n *\n * Read from the tag's first foreign key, which is where {@link findOrCreate} records it; a tag never\n * carries more than one origin. Requires a live entity or snapshot — a spread copy (e.g. from\n * {@link createTagList}) has no metadata and throws rather than reporting a false `undefined`.\n *\n * @performance O(1) meta read.\n */\nexport const getOrigin = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) =>\n Obj.getMeta(tag).keys[0]?.source;\n\n/**\n * Whether the user created this tag (and so may edit and apply it freely). See {@link getOrigin}.\n *\n * @performance O(1) meta read.\n */\nexport const isUserTag = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) =>\n getOrigin(tag) === undefined;\n\n/**\n * Whether a foreign provider owns this tag, making it read-only in the app: it cannot be renamed,\n * recoloured, or attached to / detached from an object by hand. Canonical DXOS tags are **not**\n * provider tags — they stay locally toggleable. See {@link getOrigin}.\n *\n * @performance O(1) meta read.\n */\nexport const isProviderTag = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) => {\n const origin = getOrigin(tag);\n return origin !== undefined && origin !== CANONICAL_ORIGIN;\n};\n\n/**\n * Comparator that orders tags by label.\n *\n * @performance O(label length) locale comparison.\n */\nexport const sortTags = (\n { label: a }: Pick<Type.InstanceType<typeof Tag>, 'label'>,\n { label: b }: Pick<Type.InstanceType<typeof Tag>, 'label'>,\n) => a.localeCompare(b);\n\n/**\n * Convert a tag map into a list sorted by label.\n *\n * @performance O(n log n) in tags; copies and sorts them.\n */\nexport const createTagList = (tags: Map): Type.InstanceType<typeof Tag>[] =>\n Object.entries(tags)\n .map(([id, tag]) => ({ ...tag, id }))\n .sort(sortTags);\n\n/**\n * Find a tag by case-insensitive label.\n *\n * @performance O(n) linear scan of the map.\n */\nexport const findTagByLabel = (tags: Map | undefined, name: string): Type.InstanceType<typeof Tag> | undefined => {\n const entry = Object.entries(tags ?? {}).find(([_, tag]) => tag.label.toLowerCase() === name.toLowerCase());\n return entry ? { ...entry[1], id: entry[0] } : undefined;\n};\n\n/**\n * Finds a tag by a superseded key and rewrites that key to `key`, so the tag keeps its identity (and\n * every reference to it) across a key-source rename. Returns `undefined` when none match.\n */\nconst adoptLegacyKey = async (\n db: Pick<Database.Database, 'query' | 'add'>,\n key: ForeignKey,\n legacyKeys: readonly ForeignKey[] | undefined,\n): Promise<Type.InstanceType<typeof Tag> | undefined> => {\n if (!legacyKeys?.length) {\n return undefined;\n }\n\n const [existing] = await db.query(Filter.foreignKeys(Tag, [...legacyKeys])).run();\n if (!existing) {\n return undefined;\n }\n\n Obj.update(existing, (existing) => {\n const keys = Obj.getMeta(existing).keys;\n const index = keys.findIndex((candidate) =>\n legacyKeys.some((legacy) => legacy.source === candidate.source && legacy.id === candidate.id),\n );\n if (index >= 0) {\n keys.splice(index, 1, key);\n }\n });\n\n return existing;\n};\n\n/**\n * Finds or creates a {@link Tag} object in the database.\n *\n * - With a foreign `key` (system/provider tags): matched by that key; the label is kept current on\n * re-sync. Use a stable key (e.g. `{ source: 'google.com/gmail/label', id }`) for tags whose\n * identity is external or well-known.\n * - Without a key (user tags): matched by case-insensitive label among tags that carry **no**\n * foreign key, so it never collides with a keyed system/provider tag of the same label.\n *\n * `legacyKeys` lets a caller rename its key source without orphaning existing tags: when the primary\n * key misses, they are tried in order and the first match is rewritten to `key` in place. Without it\n * a rename silently creates a parallel tag on the next sync, while objects keep pointing at the old\n * one. Drop the legacy key once the rename has shipped.\n *\n * @performance Async; a keyed lookup is one foreign-key query, but a label lookup queries and scans every tag in the\n * space (O(n)).\n */\nexport const findOrCreate = async (\n db: Pick<Database.Database, 'query' | 'add'>,\n options: { label: string; hue?: string; key?: ForeignKey; legacyKeys?: readonly ForeignKey[] },\n): Promise<Type.InstanceType<typeof Tag>> => {\n const { label, hue, key, legacyKeys } = options;\n const withHue = hue ? { hue } : {};\n if (key) {\n const [matched] = await db.query(Filter.foreignKeys(Tag, [key])).run();\n const existing = matched ?? (await adoptLegacyKey(db, key, legacyKeys));\n if (existing) {\n // Keep label (and hue, when provided) current on re-sync. `hue` is only touched when supplied,\n // so a label-only re-sync (e.g. Gmail) doesn't wipe a user-set colour.\n if (existing.label !== label || (hue !== undefined && existing.hue !== hue)) {\n Obj.update(existing, (existing) => {\n existing.label = label;\n if (hue !== undefined) {\n existing.hue = hue;\n }\n });\n }\n return existing;\n }\n\n return db.add(Obj.make(Tag, { [Obj.Meta]: { keys: [key] }, label, ...withHue }));\n }\n\n const lowered = label.toLowerCase();\n const candidates = await db.query(Filter.type(Tag)).run();\n const existing = candidates.find(\n (tag) => tag.label.toLowerCase() === lowered && (Obj.getMeta(tag).keys ?? []).length === 0,\n );\n return existing ?? db.add(make({ label, ...withHue }));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,MAAb,cAAyBA,WAAqBC,UAAmB,CAAC,CAChE,OAAO,OAAO;CACZ,OAAO,OAAO;CACd,KAAK,OAAO,SAAS,OAAO,MAAM;AACpC,CAAC,CAAC,CAAC,KAAA,gBAA8B,IAAI,CAAC,OAAO,CAAC,CAAC,CACjD,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,QAAQ,UAAqCC,OAAS,KAAK,KAAK;;;;;;AAS7E,IAAa,mBAAmB;;;;;;;;;;;;;;;;;AAkBhC,IAAa,aAAa,QACxBC,QAAY,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;;;;;;AAO5B,IAAa,aAAa,QACxB,UAAU,GAAG,MAAM,KAAA;;;;;;;;AASrB,IAAa,iBAAiB,QAAqF;CACjH,MAAM,SAAS,UAAU,GAAG;CAC5B,OAAO,WAAW,KAAA,KAAa,WAAA;AACjC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M,eAAe,IAAI,KAAK,UAAU;EACrE,IAAI,UAAU;GAGZ,IAAI,SAAS,UAAU,SAAU,QAAQ,KAAA,KAAa,SAAS,QAAQ,KACrE,OAAW,WAAW,aAAa;IACjC,SAAS,QAAQ;IACjB,IAAI,QAAQ,KAAA,GACV,SAAS,MAAM;GAEnB,CAAC;GAEH,OAAO;EACT;EAEA,OAAO,GAAG,IAAIF,OAAS,KAAK;IAAGG,OAAW,EAAE,MAAM,CAAC,GAAG,EAAE;GAAG;GAAO,GAAG;EAAQ,CAAC,CAAC;CACjF;CAEA,MAAM,UAAU,MAAM,YAAY;CAKlC,QAHiB,MADQ,GAAG,MAAMC,KAAY,GAAG,CAAC,CAAC,CAAC,IAAI,EAAA,CAC5B,MACzB,QAAQ,IAAI,MAAM,YAAY,MAAM,YAAYH,QAAY,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAA,CAAG,WAAW,CAEpF,KAAY,GAAG,IAAI,KAAK;EAAE;EAAO,GAAG;CAAQ,CAAC,CAAC;AACvD"}
1
+ {"version":3,"file":"chunk-Tag.mjs","names":["Type.makeObject","internal.TagTypeDXN","Obj.make","Obj.getMeta","Filter.foreignKeys","Obj.Meta","Filter.type"],"sources":["../../src/Tag.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\n\nimport type * as Database from './Database.ts';\nimport * as Filter from './Filter.ts';\nimport * as internal from './internal/index.ts';\nimport * as Obj from './Obj.ts';\nimport * as Type from './Type.ts';\n\nexport class Tag extends Type.makeObject<Tag>(internal.TagTypeDXN)(\n {\n label: Schema.String,\n hue: Schema.optional(Schema.String), // TODO(burdon): Color name?\n },\n internal.LabelAnnotation.set(['label']),\n) {}\n\n/**\n * Creates a new tag object.\n *\n * @performance O(1); allocates an in-memory tag object.\n */\nexport const make = (props: Obj.MakeProps<typeof Tag>) => Obj.make(Tag, props);\n\nexport type Map = Record<string, Type.InstanceType<typeof Tag>>;\n\n/**\n * Origin domain for DXOS's own canonical tags — provider-agnostic identities (starred, sent, …) that\n * each provider maps its own vocabulary onto, so a Gmail star, a JMAP `$flagged` keyword and a\n * locally-toggled star all resolve to the same {@link Tag}.\n */\nexport const CANONICAL_ORIGIN = 'org.dxos.tag';\n\n/**\n * The tag's origin domain, or `undefined` when the user created it. Says who owns the tag and\n * therefore who may change it — see `Tag.md` §\"Tag origin\":\n *\n * - `undefined` — a user tag: rename, recolour, apply and remove are all the user's to do.\n * - {@link CANONICAL_ORIGIN} — a canonical DXOS tag: applied and removed locally, but its label and\n * hue are fixed (a provider may be mapping its own vocabulary onto it).\n * - anything else — a foreign provider domain (e.g. `com.google.gmail`): read-only, since sync owns\n * both the tag and which objects carry it.\n *\n * Read from the tag's first foreign key, which is where {@link findOrCreate} records it; a tag never\n * carries more than one origin. Requires a live entity or snapshot — a spread copy (e.g. from\n * {@link createTagList}) has no metadata and throws rather than reporting a false `undefined`.\n *\n * @performance O(1) meta read.\n */\nexport const getOrigin = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) =>\n Obj.getMeta(tag).keys[0]?.source;\n\n/**\n * Whether the user created this tag (and so may edit and apply it freely). See {@link getOrigin}.\n *\n * @performance O(1) meta read.\n */\nexport const isUserTag = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) =>\n getOrigin(tag) === undefined;\n\n/**\n * Whether a foreign provider owns this tag, making it read-only in the app: it cannot be renamed,\n * recoloured, or attached to / detached from an object by hand. Canonical DXOS tags are **not**\n * provider tags — they stay locally toggleable. See {@link getOrigin}.\n *\n * @performance O(1) meta read.\n */\nexport const isProviderTag = (tag: Type.InstanceType<typeof Tag> | Obj.Snapshot<Type.InstanceType<typeof Tag>>) => {\n const origin = getOrigin(tag);\n return origin !== undefined && origin !== CANONICAL_ORIGIN;\n};\n\n/**\n * Comparator that orders tags by label.\n *\n * @performance O(label length) locale comparison.\n */\nexport const sortTags = (\n { label: a }: Pick<Type.InstanceType<typeof Tag>, 'label'>,\n { label: b }: Pick<Type.InstanceType<typeof Tag>, 'label'>,\n) => a.localeCompare(b);\n\n/**\n * Convert a tag map into a list sorted by label.\n *\n * @performance O(n log n) in tags; copies and sorts them.\n */\nexport const createTagList = (tags: Map): Type.InstanceType<typeof Tag>[] =>\n Object.entries(tags)\n .map(([id, tag]) => ({ ...tag, id }))\n .sort(sortTags);\n\n/**\n * Find a tag by case-insensitive label.\n *\n * @performance O(n) linear scan of the map.\n */\nexport const findTagByLabel = (tags: Map | undefined, name: string): Type.InstanceType<typeof Tag> | undefined => {\n const entry = Object.entries(tags ?? {}).find(([_, tag]) => tag.label.toLowerCase() === name.toLowerCase());\n return entry ? { ...entry[1], id: entry[0] } : undefined;\n};\n\n/**\n * Finds a tag by a superseded key and rewrites that key to `key`, so the tag keeps its identity (and\n * every reference to it) across a key-source rename. Returns `undefined` when none match.\n */\nconst adoptLegacyKey = async (\n db: Pick<Database.Database, 'query' | 'add'>,\n key: ForeignKey,\n legacyKeys: readonly ForeignKey[] | undefined,\n): Promise<Type.InstanceType<typeof Tag> | undefined> => {\n if (!legacyKeys?.length) {\n return undefined;\n }\n\n const [existing] = await db.query(Filter.foreignKeys(Tag, [...legacyKeys])).run();\n if (!existing) {\n return undefined;\n }\n\n Obj.update(existing, (existing) => {\n const keys = Obj.getMeta(existing).keys;\n const index = keys.findIndex((candidate) =>\n legacyKeys.some((legacy) => legacy.source === candidate.source && legacy.id === candidate.id),\n );\n if (index >= 0) {\n keys.splice(index, 1, key);\n }\n });\n\n return existing;\n};\n\n/**\n * Finds or creates a {@link Tag} object in the database.\n *\n * - With a foreign `key` (system/provider tags): matched by that key; the label is kept current on\n * re-sync. Use a stable key (e.g. `{ source: 'google.com/gmail/label', id }`) for tags whose\n * identity is external or well-known.\n * - Without a key (user tags): matched by case-insensitive label among tags that carry **no**\n * foreign key, so it never collides with a keyed system/provider tag of the same label.\n *\n * `legacyKeys` lets a caller rename its key source without orphaning existing tags: when the primary\n * key misses, they are tried in order and the first match is rewritten to `key` in place. Without it\n * a rename silently creates a parallel tag on the next sync, while objects keep pointing at the old\n * one. Drop the legacy key once the rename has shipped.\n *\n * @performance Async; a keyed lookup is one foreign-key query, but a label lookup queries and scans every tag in the\n * space (O(n)).\n */\nexport const findOrCreate = async (\n db: Pick<Database.Database, 'query' | 'add'>,\n options: { label: string; hue?: string; key?: ForeignKey; legacyKeys?: readonly ForeignKey[] },\n): Promise<Type.InstanceType<typeof Tag>> => {\n const { label, hue, key, legacyKeys } = options;\n const withHue = hue ? { hue } : {};\n if (key) {\n const [matched] = await db.query(Filter.foreignKeys(Tag, [key])).run();\n const existing = matched ?? (await adoptLegacyKey(db, key, legacyKeys));\n if (existing) {\n // Keep label (and hue, when provided) current on re-sync. `hue` is only touched when supplied,\n // so a label-only re-sync (e.g. Gmail) doesn't wipe a user-set colour.\n if (existing.label !== label || (hue !== undefined && existing.hue !== hue)) {\n Obj.update(existing, (existing) => {\n existing.label = label;\n if (hue !== undefined) {\n existing.hue = hue;\n }\n });\n }\n return existing;\n }\n\n return db.add(Obj.make(Tag, { [Obj.Meta]: { keys: [key] }, label, ...withHue }));\n }\n\n const lowered = label.toLowerCase();\n const candidates = await db.query(Filter.type(Tag)).run();\n const existing = candidates.find(\n (tag) => tag.label.toLowerCase() === lowered && (Obj.getMeta(tag).keys ?? []).length === 0,\n );\n return existing ?? db.add(make({ label, ...withHue }));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,IAAa,MAAb,cAAyBA,WAAqBC,UAAmB,CAAC,CAChE;CACE,OAAO,OAAO;CACd,KAAK,OAAO,SAAS,OAAO,MAAM;AACpC,GAAA,gBACyB,IAAI,CAAC,OAAO,CAAC,CACxC,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,QAAQ,UAAqCC,OAAS,KAAK,KAAK;;;;;;AAS7E,IAAa,mBAAmB;;;;;;;;;;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YAC2C;CAC3C,MAAM,EAAE,OAAO,KAAK,KAAK,eAAe;CACxC,MAAM,UAAU,MAAM,EAAE,IAAI,IAAI,CAAC;CACjC,IAAI,KAAK;EACP,MAAM,CAAC,WAAW,MAAM,GAAG,MAAMC,YAAmB,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI;EACrE,MAAM,WAAW,WAAY,MAAM,eAAe,IAAI,KAAK,UAAU;EACrE,IAAI,UAAU;GAGZ,IAAI,SAAS,UAAU,SAAU,QAAQ,KAAA,KAAa,SAAS,QAAQ,KACrE,OAAW,WAAW,aAAa;IACjC,SAAS,QAAQ;IACjB,IAAI,QAAQ,KAAA,GACV,SAAS,MAAM;GAEnB,CAAC;GAEH,OAAO;EACT;EAEA,OAAO,GAAG,IAAIF,OAAS,KAAK;IAAGG,OAAW,EAAE,MAAM,CAAC,GAAG,EAAE;GAAG;GAAO,GAAG;EAAQ,CAAC,CAAC;CACjF;CAEA,MAAM,UAAU,MAAM,YAAY;CAKlC,QAHiB,MADQ,GAAG,MAAMC,KAAY,GAAG,CAAC,CAAC,CAAC,IAAI,EAAA,CAC5B,MACzB,QAAQ,IAAI,MAAM,YAAY,MAAM,YAAYH,QAAY,GAAG,CAAC,CAAC,QAAQ,CAAC,EAAA,CAAG,WAAW,CAEpF,KAAY,GAAG,IAAI,KAAK;EAAE;EAAO,GAAG;CAAQ,CAAC,CAAC;AACvD"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { c as TextEditNotFoundError, l as TextNotSupportedError } from "./chunk-Error.mjs";
3
- import { D as getProxyTarget, E as getProxyHandler, O as isProxy } from "./chunk-ref.mjs";
2
+ import { C as getProxyHandler, T as isProxy, w as getProxyTarget } from "./chunk-ref.mjs";
3
+ import { l as TextEditNotFoundError, u as TextNotSupportedError } from "./chunk-Error.mjs";
4
4
  import { I as getValue } from "./chunk-Obj.mjs";
5
5
  //#region src/Text.ts
6
6
  var Text_exports = /* @__PURE__ */ __exportAll({
@@ -2,10 +2,11 @@ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
2
  import { c as getMetaChecked } from "./chunk-entity-dictionary.mjs";
3
3
  import { H as makeRelationType, L as version, W as makeObjectType, Y as makeObject$1, a as updateFieldsInSchema, i as updateFieldNameInSchema, n as addFieldsToSchema, r as removeFieldsFromSchema, t as TypeSchema } from "./chunk-internal.mjs";
4
4
  import { c as InstancePhantomId$1, g as getStaticTypeSchema, h as getSchemaKind, m as getEntityKindBrand, o as EntityKind } from "./chunk-util.mjs";
5
- import { Ct as getLabel$1, M as getDatabase$1, Ot as getSchemaURI, k as getTypeURIFromSpecifier, pt as TypeIdentifierAnnotationId } from "./chunk-Database.mjs";
5
+ import { A as getTypeURIFromSpecifier, It as getSchemaURI, N as getDatabase$1, bt as TypeIdentifierAnnotationId, jt as getLabel$1 } from "./chunk-Database.mjs";
6
6
  import { v as change } from "./chunk-ref.mjs";
7
7
  import { i as toJsonSchema, r as toEffectSchema } from "./chunk-json-schema.mjs";
8
8
  import { DXN, EID } from "@dxos/keys";
9
+ import * as Schema from "effect/Schema";
9
10
  import { assertArgument, invariant } from "@dxos/invariant";
10
11
  import { raise } from "@dxos/debug";
11
12
  //#region src/Type.ts
@@ -54,17 +55,30 @@ var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/echo/src/Type.ts";
54
55
  * declaration emit: structural expansion (which can pull in unnameable union
55
56
  * members from referenced schemas) is replaced by a reference to the class.
56
57
  *
58
+ * The second call takes either a schema, or struct fields (wrapped in `Schema.Struct`) with an optional function
59
+ * that pipes annotations onto the struct.
60
+ *
57
61
  * @example
58
62
  * ```ts
59
63
  * export class Person extends Type.makeObject<Person>(DXN.make('com.example.type.myType', '0.1.0'))(Schema.Struct({
60
64
  * name: Schema.String,
61
65
  * })) {}
66
+ *
67
+ * export class Tag extends Type.makeObject<Tag>(DXN.make('com.example.type.tag', '0.1.0'))(
68
+ * { label: Schema.String },
69
+ * Annotation.LabelAnnotation.set(['label']),
70
+ * ) {}
62
71
  * ```
63
72
  *
64
73
  * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not
65
74
  * per use.
66
75
  */
67
- var makeObject = (dxn, options) => (schema) => makeObjectType(dxn, schema, options);
76
+ var makeObject = (dxn, options) => ((input, annotate) => makeObjectType(dxn, buildSchema(input, annotate), options));
77
+ /** Wraps struct fields in `Schema.Struct` and applies the optional annotate function. */
78
+ var buildSchema = (input, annotate) => {
79
+ const schema = Schema.isSchema(input) ? input : Schema.Struct(input);
80
+ return annotate ? annotate(schema) : schema;
81
+ };
68
82
  /**
69
83
  * ECHO meta-schema entity — stores `{ name?, typename, version, jsonSchema }`.
70
84
  * Type-kind sibling of `Type.makeObject(...)` / `Type.makeRelation(...)` outputs.
@@ -134,18 +148,23 @@ var makeRelationFromJsonSchema = (props) => {
134
148
  * class WorksFor extends Type.makeRelation<WorksFor>(DXN.make('com.example.type.worksFor', '0.1.0'))(
135
149
  * { source: Person, target: Company },
136
150
  * )(Schema.Struct({ role: Schema.String })) {}
151
+ *
152
+ * // Like `makeObject`, the last call also takes struct fields and an optional annotate function.
153
+ * class Employs extends Type.makeRelation<Employs>(DXN.make('com.example.type.employs', '0.1.0'))(
154
+ * { source: Company, target: Person },
155
+ * )({ role: Schema.String }, Annotation.LabelAnnotation.set(['role'])) {}
137
156
  * ```
138
157
  *
139
158
  * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not
140
159
  * per use.
141
160
  */
142
- var makeRelation = (dxn) => (opts) => (schema) => makeRelationType({
161
+ var makeRelation = (dxn) => (opts) => ((input, annotate) => makeRelationType({
143
162
  dxn,
144
163
  source: opts.source,
145
164
  target: opts.target,
146
- schema,
165
+ schema: buildSchema(input, annotate),
147
166
  id: opts.id
148
- });
167
+ }));
149
168
  /**
150
169
  * Type guard: narrows a `Type.AnyEntity` to an object-kind entity. Checks
151
170
  * ENTITIES, not instances — use `Obj.isObject` for instances. Raw
@@ -253,7 +272,7 @@ var getTypename = (input) => {
253
272
  invariant(typeof typename === "string" && typename.length > 0, "Invalid typename", {
254
273
  "~LogMeta": "~LogMeta",
255
274
  F: __dxlog_file,
256
- L: 504,
275
+ L: 557,
257
276
  S: void 0,
258
277
  A: ["typeof typename === 'string' && typename.length > 0", "'Invalid typename'"]
259
278
  });
@@ -279,7 +298,7 @@ var getVersion = (input) => {
279
298
  invariant(typeof semver === "string" && semver.match(/^\d+\.\d+\.\d+$/), "Invalid version", {
280
299
  "~LogMeta": "~LogMeta",
281
300
  F: __dxlog_file,
282
- L: 530,
301
+ L: 583,
283
302
  S: void 0,
284
303
  A: ["typeof semver === 'string' && semver.match(/^\\d+\\.\\d+\\.\\d+$/)", "'Invalid version'"]
285
304
  });
@@ -1 +1 @@
1
- {"version":3,"file":"chunk-Type.mjs","names":["internal.makeObjectType","typeInternal.TypeSchema","internal.makeObject","internal.getStaticTypeSchema","internal.getTypeURIFromSpecifier","internal.makeRelationType","internal.getSchemaKind","internal.getSchemaURI","internal.getMetaChecked","internal.version","internal.getEntityKindBrand","internal.getDatabase","internal.getLabel","internal.InstancePhantomId","internal.toEffectSchema","internal.TypeIdentifierAnnotationId","typeInternal.addFieldsToSchema","internal.toJsonSchema","typeInternal.updateFieldsInSchema","typeInternal.updateFieldNameInSchema","typeInternal.removeFieldsFromSchema"],"sources":["../../src/Type.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport { raise } from '@dxos/debug';\nimport { type EncodedReference } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, type EntityId, type URI } from '@dxos/keys';\n\nimport type * as Database from './Database.ts';\nimport type * as EntityModule from './Entity.ts';\nimport * as internal from './internal/index.ts';\nimport * as typeInternal from './internal/Type/index.ts';\nimport type * as RelationModule from './Relation.ts';\n\n//\n// Internal types (not exported)\n//\n\n/**\n * Structural base shared by the three sibling type-entity interfaces\n * ({@link Obj}, {@link Relation}, {@link Type}). NOT exported — callers\n * should constrain on {@link AnyEntity} when they want \"any of the three\"\n * and on the specific kind interface otherwise.\n */\ninterface BaseTypeEntity<A> {\n /**\n * Entity-kind brand of the type-entity value itself — always `EntityKind.Type`.\n * The kind of instance the type *describes* lives on `[SchemaKindId]`\n * (Object / Relation / Type). Lets `Obj.isObject` / `Relation.isRelation`\n * reject type entities by a single `[KindId]` check.\n */\n readonly [internal.KindId]: internal.EntityKind.Type;\n\n /**\n * Object id. Like all ECHO entities, type entities always carry an id —\n * stamped at construction for in-memory (static) declarations and assigned by\n * the database once persisted. The id does NOT determine the entity's URI:\n * static types resolve to their typename DXN, persisted types to `echo:///<id>`\n * (see `getTypeURIFromSpecifier`).\n */\n readonly id: EntityId;\n\n readonly name?: string;\n // NOTE: `typename` / `version` are intentionally NOT fields on any type-entity\n // interface. Both static and persisted entities carry them in `EntityMeta`\n // (`key` / `version`); read them via `Type.getTypename(self)` /\n // `Type.getVersion(self)` — never as a direct property.\n readonly jsonSchema: internal.JsonSchemaType;\n readonly [InstancePhantomId]?: A;\n}\n\n//\n// Obj — `Type.Type` value for an ECHO object schema.\n//\n\n/**\n * TypeScript type for an ECHO object type — a `Type.Type<A>` entity.\n *\n * `T` is the instance type produced by `Obj.make(Foo, props)`. `Fields` is\n * retained as a structural hint (the runtime value still carries `.fields`),\n * but consumers should derive instance/encoded types via `Type.InstanceType`.\n *\n * **Not a `Schema.Schema`.** `Foo.ast` / `Schema.Schema.Type<typeof Foo>` /\n * `Schema.extend(Foo)` no longer typecheck — extract the Effect Schema via\n * `Type.getSchema(Foo)` first, or derive instance types via\n * `Type.InstanceType<typeof Foo>`.\n *\n * @example\n * ```ts\n * class Person extends Type.makeObject<Person>(DXN.make('com.example.type.person', '0.1.0'))(\n * Schema.Struct({ name: Schema.String }),\n * ) {}\n * ```\n */\nexport interface Obj<T, Fields extends Schema.Struct.Fields = Schema.Struct.Fields> extends BaseTypeEntity<\n T & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n> {\n /** Schema-kind brand (object). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Object;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n /**\n * The fields defined in the original struct schema.\n * Allows accessing field definitions for introspection.\n */\n readonly fields: Fields;\n}\n\n/**\n * Return type for {@link makeObject}.\n *\n * Not to be used directly, but must be exported for typescript to infer the type.\n */\nexport interface ObjClass<Self, T, Fields extends Schema.Struct.Fields> extends Obj<Self, Fields> {\n new (_: never): T & EntityModule.OfKind<typeof EntityModule.Kind.Object>;\n}\n\n/**\n * Type that represents any ECHO object type — a `Type.Type` entity branded\n * with the object entity kind, i.e. what `Type.makeObject(dxn)` produces.\n */\nexport type AnyObj = Obj<unknown>;\n\n/**\n * Factory function to create an ECHO object type.\n *\n * Returns a `Type.Type` entity — a live, in-memory `TypeSchema` instance,\n * NOT a `Schema.Schema`. Use `Type.InstanceType<typeof Foo>` for the instance\n * type and `Type.getSchema(Foo)` to obtain the underlying Effect Schema.\n *\n * The entity's id defaults to `EntityId.deterministic(typename, version)` so\n * constructing a type never reaches `crypto.getRandomValues()` — required for\n * Cloudflare workerd, which forbids RNG calls in global (module-evaluation)\n * scope. Pass `{ id }` to override (e.g. with `EntityId.random()` from a\n * request handler).\n *\n * Giving the type a nominal class name keeps its inferred type portable for\n * declaration emit: structural expansion (which can pull in unnameable union\n * members from referenced schemas) is replaced by a reference to the class.\n *\n * @example\n * ```ts\n * export class Person extends Type.makeObject<Person>(DXN.make('com.example.type.myType', '0.1.0'))(Schema.Struct({\n * name: Schema.String,\n * })) {}\n * ```\n *\n * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not\n * per use.\n */\n// TODO(burdon): Require { typename, version } in options.\nexport const makeObject: {\n <Self>(\n dxn: DXN.DXN,\n options?: { id?: EntityId },\n ): <_Schema extends Schema.Top>(schema: _Schema) => ObjClass<Self, Schema.Schema.Type<_Schema>, {}>;\n // Boundary cast: overload implementation bodies cannot access outer generic params (`Self`),\n // so TypeScript cannot verify that makeObjectType's return matches the declared ObjClass<Self,…>.\n} = (dxn, options) => (schema) => internal.makeObjectType(dxn, schema, options) as any;\n\n//\n// Type — the ECHO entity that holds a schema and metadata.\n// Persisted via `db.addType()`; subscribed to via `Filter.type(Type.Type)`.\n//\n\n/**\n * ECHO meta-schema entity — stores `{ name?, typename, version, jsonSchema }`.\n * Type-kind sibling of `Type.makeObject(...)` / `Type.makeRelation(...)` outputs.\n * Stored types live under this entity; filter via `Filter.type(Type.Type)`.\n */\nexport const Type: Type<typeInternal.TypeSchema> = typeInternal.TypeSchema as any;\n\n/**\n * Default version stamped on draft (unnamed) types created via\n * {@link makeObjectFromJsonSchema} / {@link makeRelationFromJsonSchema} when\n * the caller does not supply one. Pure dynamic drafts surface as `'0.0.0'`\n * until they are persisted, at which point automerge-heads suffix the version.\n */\nconst DRAFT_VERSION = '0.0.0';\n\n/**\n * Common props shared by the type-kind factories. Typename and version are\n * optional — drafts omit typename and default version to {@link DRAFT_VERSION}.\n */\ntype MakeTypeProps = {\n jsonSchema: internal.JsonSchemaType;\n typename?: string;\n version?: string;\n name?: string;\n id?: EntityId;\n};\n\n/**\n * Construct a new object-kind type entity from raw metadata — for cases where\n * an Effect Schema isn't available (e.g. JSON-Schema arriving over the network\n * or from a UI editor). Parallel to {@link makeObject} but takes pre-built\n * `jsonSchema` instead of piping through an Effect schema.\n *\n * The returned entity is in-memory; persist it with `db.addType(entity)`.\n *\n * @performance O(schema size); validates the JSON schema into a new in-memory type entity, with no database I/O.\n */\nexport const makeObjectFromJsonSchema = (props: MakeTypeProps): Type<typeInternal.TypeSchema> => {\n const { typename, version, ...data } = props;\n // `typename` / `version` are routed through `EntityMeta` (`key` / `version`)\n // — the canonical registry-provenance pair — not data fields. Drafts default\n // to `'0.0.0'`; the version is omitted from meta entirely when the caller\n // doesn't supply one so the proxy projection can apply its own default.\n return internal.makeObject(\n internal.getStaticTypeSchema(typeInternal.TypeSchema) as any,\n data as any,\n {\n keys: [],\n key: typename,\n version: version ?? DRAFT_VERSION,\n },\n typeInternal.TypeSchema,\n ) as unknown as Type<typeInternal.TypeSchema>;\n};\n\n/**\n * Construct a new relation-kind type entity from raw metadata. Parallel to\n * {@link makeRelation} but takes pre-built `jsonSchema` instead of piping\n * through an Effect schema. `source` / `target` accept either a static\n * `Type.Obj` entity or the well-known `Obj.Unknown` schema.\n *\n * The returned entity is in-memory; persist it with `db.addType(entity)`.\n *\n * @performance O(schema size); validates the JSON schema into a new in-memory type entity, with no database I/O.\n */\nexport const makeRelationFromJsonSchema = (\n props: MakeTypeProps & {\n source: AnyObj | internal.UnknownTypeSchema<any, typeof EntityModule.Kind.Object>;\n target: AnyObj | internal.UnknownTypeSchema<any, typeof EntityModule.Kind.Object>;\n },\n): Type<typeInternal.TypeSchema> => {\n const { source, target, jsonSchema, typename, version, ...rest } = props;\n // Embed source/target DXNs + relation entity-kind into the jsonSchema so the\n // entity round-trips correctly through `toEffectSchema` / queries / refs.\n const sourceURI = internal.getTypeURIFromSpecifier(source);\n const targetURI = internal.getTypeURIFromSpecifier(target);\n const enrichedJsonSchema: internal.JsonSchemaType = {\n ...jsonSchema,\n entityKind: internal.EntityKind.Relation,\n relationSource: { $ref: sourceURI },\n relationTarget: { $ref: targetURI },\n };\n // `typename` / `version` route through `EntityMeta` (see\n // {@link makeObjectFromJsonSchema}); drafts default version to `'0.0.0'`.\n return internal.makeObject(\n internal.getStaticTypeSchema(typeInternal.TypeSchema) as any,\n { ...rest, jsonSchema: enrichedJsonSchema } as any,\n {\n keys: [],\n key: typename,\n version: version ?? DRAFT_VERSION,\n },\n typeInternal.TypeSchema,\n ) as unknown as Type<typeInternal.TypeSchema>;\n};\n\n/**\n * TypeScript type for an ECHO relation type — a `Type.Type<A>` entity.\n *\n * `T` is the instance-property type produced by `Relation.make(...)` (excluding\n * source/target endpoints). `Source` and `Target` are the endpoint types.\n *\n * **Not a `Schema.Schema`.** See {@link Obj}'s note.\n */\nexport interface Relation<\n T,\n Source,\n Target,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> extends BaseTypeEntity<\n RelationModule.Endpoints<Source, Target> & T & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n> {\n /** Schema-kind brand (relation). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Relation;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n /**\n * The fields defined in the original struct schema.\n * Allows accessing field definitions for introspection.\n */\n readonly fields: Fields;\n}\n\n/**\n * Return type for {@link makeRelation}.\n *\n * Not to be used directly, but must be exported for typescript to infer the type.\n */\nexport interface RelationClass<Self, T, Source, Target, Fields extends Schema.Struct.Fields> extends Relation<\n Self,\n Source,\n Target,\n Fields\n> {\n new (_: never): RelationModule.Endpoints<Source, Target> & T & EntityModule.OfKind<typeof EntityModule.Kind.Relation>;\n}\n\n/**\n * Type that represents any ECHO relation type — a `Type.Type` entity branded\n * with the relation entity kind, i.e. what `Type.makeRelation(...)` produces.\n */\nexport type AnyRelation = Relation<unknown, unknown, unknown>;\n\n/**\n * Factory function to create an ECHO relation schema.\n * Adds relation metadata annotations to an Effect schema.\n *\n * @example\n * ```ts\n * class WorksFor extends Type.makeRelation<WorksFor>(DXN.make('com.example.type.worksFor', '0.1.0'))(\n * { source: Person, target: Company },\n * )(Schema.Struct({ role: Schema.String })) {}\n * ```\n *\n * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not\n * per use.\n */\nexport const makeRelation: {\n <Self>(dxn: DXN.DXN): <SourceInstance, TargetInstance>(opts: {\n source: Obj<SourceInstance, any> | internal.UnknownTypeSchema<SourceInstance, typeof EntityModule.Kind.Object>;\n target: Obj<TargetInstance, any> | internal.UnknownTypeSchema<TargetInstance, typeof EntityModule.Kind.Object>;\n /**\n * Override the entity id. Defaults to `EntityId.deterministic(typename, version)`;\n * see `Type.makeObject` for the workerd motivation.\n */\n id?: EntityId;\n }) => <_Schema extends Schema.Top>(\n schema: _Schema,\n ) => RelationClass<\n Self,\n Schema.Schema.Type<_Schema>,\n SourceInstance & EntityModule.OfKind<typeof EntityModule.Kind.Object>,\n TargetInstance & EntityModule.OfKind<typeof EntityModule.Kind.Object>,\n {}\n >;\n} = (dxn) => (opts) => (schema) =>\n // Boundary cast: makeRelationType erases generic params since the constructor/prototype\n // wiring cannot thread them through the type system.\n internal.makeRelationType({\n dxn,\n source: opts.source,\n target: opts.target,\n schema,\n id: opts.id,\n }) as any;\n\n/**\n * Type that represents any ECHO type-kind entity — a `Type.Type` meta-schema\n * value (static `Type.Type` or a persisted draft from `db.addType(...)`).\n * Mirrors {@link AnyObj} / {@link AnyRelation} for the third sibling kind.\n */\nexport type AnyType = Type<unknown>;\n\n/**\n * Any ECHO type-entity — one of the three sibling kinds: object-kind, relation-kind,\n * or type-kind (the meta-schema). APIs that want \"any ECHO type\" use this union;\n * the underlying Effect Schema is retrieved via `Type.getSchema`.\n */\nexport type AnyEntity = AnyObj | AnyRelation | AnyType;\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to an object-kind entity. Checks\n * ENTITIES, not instances — use `Obj.isObject` for instances. Raw\n * `Schema.Schema` values (including the branded `Obj.Unknown` companion)\n * are intentionally not accepted; inspect their `TypeAnnotation` directly.\n *\n * @performance O(1) brand read.\n */\nexport const isObject = (entity: AnyEntity): entity is AnyObj => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Object;\n};\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to a relation-kind entity. Checks\n * ENTITIES, not instances — use `Relation.isRelation` for instances.\n *\n * @performance O(1) brand read.\n */\nexport const isRelation = (entity: AnyEntity): entity is AnyRelation => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Relation;\n};\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to the type-kind meta-schema\n * (e.g. `Type.Type`). Mirrors {@link isObject} / {@link isRelation}.\n *\n * @performance O(1) brand read.\n */\nexport const isTypeKind = (entity: AnyEntity): entity is Type => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Type;\n};\n\n/**\n * Narrow a `Type.AnyEntity` (e.g. one returned from `schemaRegistry.query(...)`)\n * to `AnyObj`, throwing if it describes a relation or the type-kind\n * meta-schema. Use at call sites that need to pass the value to `Obj.make`,\n * `Filter.type`, or other object-only APIs.\n *\n * @performance O(1) brand read.\n */\nexport const assertObject = (entity: AnyEntity): AnyObj => {\n assertArgument(isObject(entity), 'entity', 'Expected an object-kind Type entity.');\n return entity;\n};\n\n/**\n * Narrow a `Type.AnyEntity` to `AnyRelation`, throwing otherwise.\n *\n * @performance O(1) brand read.\n */\nexport const expectRelation = (entity: AnyEntity): AnyRelation => {\n assertArgument(isRelation(entity), 'entity', 'Expected a relation-kind Type entity.');\n return entity;\n};\n\n/**\n * Narrow a `Type.AnyEntity` to the `Type.Type` meta-schema, throwing otherwise.\n *\n * @performance O(1) brand read.\n */\nexport const expectTypeKind = (entity: AnyEntity): Type => {\n assertArgument(isTypeKind(entity), 'entity', 'Expected a type-kind Type entity.');\n return entity;\n};\n\n/**\n * Type that represents any Ref schema (with unknown target type).\n * This is a schema type, not an instance type.\n */\nexport type AnyRef = Schema.Codec<internal.Ref<any>, EncodedReference>;\n\n//\n// Schema utility functions\n//\n\n/**\n * Returns the URI identifying a type entity. Always defined.\n *\n * - Static `Type.Obj` / `Type.Relation` → typename DXN (e.g. `dxn:com.example.type.person:0.1.0`).\n * - Persisted `Type.Type` instance (has `id`) → local `EID` (`echo:///<objectId>`).\n * - In-memory `Type.Type` draft (has `id`, no typename) → local `EID`.\n *\n * When `options.prefer === 'named'` the result is forced to a DXN — for\n * persisted type entities the typename + version from meta are used to\n * construct the DXN; static types already return a DXN by default.\n *\n * Only accepts `Type.AnyEntity` entities. Raw `Schema.Schema` values and the\n * branded `Obj.Unknown` / `Relation.Unknown` schemas are intentionally not\n * supported — use `internal.getSchemaURI` or the schema's typename annotation\n * directly when working at the schema level.\n *\n * @performance O(1); reads the id or schema identifier annotation, allocating a new URI string.\n */\nexport const getURI = (input: AnyEntity, options?: internal.GetURIOptions): URI.URI => {\n // For Type entities, route through `getTypeURIFromSpecifier` (id → EID,\n // typename/version → DXN). For Obj/Relation entities, unwrap to the source\n // Effect Schema first and read its annotations.\n if (isType(input)) {\n const uri = internal.getTypeURIFromSpecifier(input);\n if (options?.prefer === 'named' && !DXN.isDXN(uri)) {\n // Persisted type — the auto-detected URI is an EID, but caller wants a\n // DXN. Construct from typename + version (both live in EntityMeta).\n const typename = getTypename(input);\n const version = getMeta(input).version;\n if (typename && version) {\n return DXN.make(typename, version);\n }\n }\n return uri;\n }\n return internal.getSchemaURI(getSchema(input)) ?? raise(new TypeError('Type entity has no URI'));\n};\n\n/**\n * @returns The typename. Example: `com.example.type.person`.\n *\n * Persisted `Type.Type` entities carry typename in `EntityMeta.key` (the\n * canonical registry-provenance field); unnamed drafts fall back to the\n * entity's object id so the helper always returns a string. Any `dxn:` or\n * `echo:/` prefix is stripped — typename is a bare identifier, not a URI.\n *\n * @performance O(1) meta read with `jsonSchema` and id fallbacks.\n */\n// TODO(wittjosiah): For in-database types this should return the object id once the registry\n// has more robust options for shadowing types (so callers can disambiguate db-stored copies).\nexport const getTypename = (input: AnyEntity): string => {\n // Both in-memory and in-database entities carry typename in `EntityMeta.key`\n // — the canonical registry-provenance field. In-memory entities attach meta\n // eagerly (see `makeEchoTypeSchema`), so a single meta-backed read covers\n // both forms.\n const meta = internal.getMetaChecked(input);\n let typename: string | undefined = meta.key as string | undefined;\n // `meta.key` is a denormalized copy of the typename. The authoritative source\n // for a type entity is its `jsonSchema.typename` (`getSchema` rebuilds the\n // Effect Schema from `jsonSchema`). A type loaded from a snapshot can arrive\n // with `meta.key` absent (the meta round-trip dropped the denormalized copy)\n // while `jsonSchema.typename` is always present — consult it before the\n // last-resort id fallback so callers never receive a bare object id where a\n // typename is expected (e.g. `Filter.typename`, which rejects non-typenames).\n if (typename == null) {\n typename = input.jsonSchema?.typename;\n }\n // Unnamed drafts (no meta.key, no jsonSchema typename) fall back to the id.\n typename ??= input.id as string;\n // Typename is a bare identifier — strip URI prefixes if a caller seeded\n // meta.key with one accidentally (or if a static entity carries a DXN-\n // style typename).\n typename = stripTypenamePrefix(typename);\n invariant(typeof typename === 'string' && typename.length > 0, 'Invalid typename');\n return typename;\n};\n\n/**\n * Gets the version.\n * @example 0.1.0\n * @example 0.1.0-<heads> (in-database, versioned by automerge heads)\n *\n * The registry-provenance semver lives in `EntityMeta.version`; unversioned\n * drafts default to {@link DRAFT_VERSION} (`'0.0.0'`). In-database entities are\n * additionally versioned by their automerge heads, which are exposed as the\n * semver pre-release tag (`<semver>-<heads>`). In-memory declarations have no\n * heads and surface the bare semver. Read the registry semver alone via\n * `Type.getMeta(input).version`.\n *\n * @performance O(h log h) in Automerge heads for database types (sorted into the suffix per call); O(1) for in-memory\n * types.\n */\nexport const getVersion = (input: AnyEntity): string => {\n const meta = internal.getMetaChecked(input);\n // As with `getTypename`: `meta.version` is a denormalized copy; the\n // authoritative semver lives in `jsonSchema.version`. Prefer meta, fall back\n // to jsonSchema (always present on persisted types, survives serialization),\n // then to `DRAFT_VERSION` for unversioned drafts.\n const semver = (meta.version as string | undefined) ?? input.jsonSchema?.version ?? DRAFT_VERSION;\n invariant(typeof semver === 'string' && semver.match(/^\\d+\\.\\d+\\.\\d+$/), 'Invalid version');\n // In-database entities are versioned by their automerge heads; expose them as\n // the semver pre-release tag. In-memory drafts carry no heads → bare semver.\n const heads = internal.version(input).automergeHeads;\n if (heads != null && heads.length > 0) {\n return `${semver}-${[...heads].sort().join('.')}`;\n }\n return semver;\n};\n\n/**\n * Strip URI prefixes (`dxn:`, `echo:/`, `echo://`, `echo:///`) from a typename string.\n * Typename is a bare identifier — callers reading from meta or from a\n * caller-supplied seed value shouldn't propagate URI prefixes downstream.\n */\nconst stripTypenamePrefix = (value: string): string => {\n if (value.startsWith('dxn:')) {\n return value.slice('dxn:'.length);\n }\n // Strip the `echo:` scheme along with any leading slashes so every local form\n // (`echo:///<id>`, `echo:///<id>`) and the qualified `echo://<space>/<id>` collapse consistently.\n if (value.startsWith('echo:')) {\n return value.slice('echo:'.length).replace(/^\\/+/, '');\n }\n return value;\n};\n\n/**\n * Type predicate: true iff the value is any type-kind ECHO entity — a static\n * `Type.Obj` / `Type.Relation` produced by `Type.makeObject` / `Type.makeRelation`, a\n * static meta `Type.Type`, or a persisted `Type.Type` returned by the database.\n *\n * All three branches stamp `[KindId] = Type`, so this is a single brand check.\n * Use {@link isObject} / {@link isRelation} / {@link isTypeKind}\n * when you need to discriminate further; use {@link getDatabase} when you mean\n * \"is this a db-attached type\" (vs. an in-memory declaration).\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isType = (value: unknown): value is AnyEntity =>\n internal.getEntityKindBrand(value) === internal.EntityKind.Type;\n\n/**\n * Get the database the type entity belongs to, or `undefined` if it is an\n * in-memory declaration (`Type.makeObject` / `Type.makeRelation` result) not\n * yet attached to a database. Mirrors `Obj.getDatabase` / `Relation.getDatabase`.\n *\n * Database attachment is the canonical discriminator between in-memory and\n * in-database type entities — both are live reactive `TypeSchema` instances and\n * are otherwise indistinguishable.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (input: AnyEntity): Database.Database | undefined => internal.getDatabase(input);\n\n/**\n * Mutable meta type returned by `Type.getMeta` inside a `Type.update` callback.\n * Mirrors `Obj.Meta` / `Relation.Meta` — `Type.Type` is an Entity like its\n * siblings, so its meta is the same `EntityMeta` record:\n * `{ keys, tags?, key?, version? }`.\n *\n * `key` / `version` here are the canonical registry-provenance pair\n * (typename + semver) on persisted Type.Type entities; they are absent on\n * unnamed drafts. Use {@link getTypename} / {@link getVersion} when you want\n * a non-`undefined` value with id / {@link DRAFT_VERSION} fallbacks.\n */\nexport type Meta = internal.Meta;\n\n/**\n * Deeply read-only version of {@link Meta}.\n * Prevents mutation at all nesting levels (e.g., `meta.keys.push()` is a TS error).\n */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Returns the entity's `EntityMeta`. Same semantics as `Obj.getMeta` /\n * `Relation.getMeta` — `Type.Type` is an Entity and carries the canonical\n * `EntityMeta` directly. Returns mutable meta when passed a mutable type\n * (inside a `Type.update` callback), read-only meta otherwise.\n *\n * For persisted Type entities, `meta.key` holds the typename and\n * `meta.version` holds the semver. Use {@link getTypename} / {@link getVersion}\n * if you want the helpers' id / {@link DRAFT_VERSION} fallbacks for drafts.\n *\n * Both persisted and in-memory type entities (`Type.makeObject` /\n * `Type.makeRelation` results) carry their `EntityMeta` via `[MetaId]`, so the\n * lookup is uniform.\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\nexport function getMeta(entity: internal.Mutable<AnyEntity>): Meta;\nexport function getMeta(entity: Mutable): Meta;\nexport function getMeta(entity: AnyEntity): ReadonlyMeta;\nexport function getMeta(entity: AnyEntity | internal.Mutable<AnyEntity> | Mutable): ReadonlyMeta | Meta {\n // The `Mutable` overload accepts the narrowed view passed to `Type.update`\n // callbacks; at runtime that draft IS the underlying persisted Type entity,\n // so the same `MetaId` lookup works.\n assertArgument(isType(entity), 'entity', 'Expected a Type entity.');\n // Both persisted and in-memory type entities carry runtime `EntityMeta` via\n // `[MetaId]`, so the lookup is uniform.\n return internal.getMetaChecked(entity);\n}\n\n/**\n * Get the display label of a type entity.\n * Reads the field(s) nominated by the type's {@link LabelAnnotation} (e.g. `name` on persisted schemas).\n * Returns `undefined` if no label field is populated.\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: AnyEntity, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * String key used to phantom-carry the instance type produced by a `Type.Type`.\n * Used by `Type.InstanceType<typeof Foo>` to recover the schema instance type\n * since `Type.makeObject(dxn)` does not return a `Schema.Schema`.\n *\n * Re-exported from the internal types layer so both `Type.ts` and internal\n * helpers (`makeObject`, `createObject`) reference the same phantom key.\n */\nexport const InstancePhantomId = internal.InstancePhantomId;\nexport type InstancePhantomId = internal.InstancePhantomId;\n\n/**\n * Sibling of {@link Obj} / {@link Relation} for the third ECHO entity kind:\n * **type-kind** entities (meta-schemas). The singleton {@link Type} const is\n * the canonical example — it describes stored type definitions themselves.\n *\n * Not a `Schema.Schema`. Use `Type.getSchema(value)` to obtain the underlying\n * Effect Schema and `Type.update(value, draft => ...)` to mutate.\n *\n * `A` is the instance-type phantom — what `Obj.make(value, ...)` would produce.\n * Merged with the `Type` const value via TypeScript declaration merging.\n */\nexport interface Type<A = unknown> extends BaseTypeEntity<A & EntityModule.OfKind<typeof EntityModule.Kind.Type>> {\n /** Schema-kind brand (type — the meta-schema kind). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Type;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n}\n\n/**\n * Instance type produced by a Type entity.\n *\n * Accepts ONLY {@link AnyEntity} inputs — `Type.Obj`, `Type.Relation`, or\n * `Type.Type`. Raw Effect `Schema.Schema` values are rejected: for those, use\n * `Schema.Schema.Type<typeof Foo>` directly. This separation keeps the type\n * system honest about which values represent ECHO entities versus plain\n * Effect schemas.\n *\n * Dispatches on the entity kind:\n * - `Relation<Props, S, T>` → `Endpoints<S,T> & Props & OfKind<Relation>`\n * - `Obj<A>` → `A & OfKind<Object>`\n * - `Type<A>` → `A & OfKind<Type>`\n */\nexport type InstanceType<T extends AnyEntity> =\n T extends RelationClass<any, infer Props, infer Source, infer Target, any>\n ? RelationModule.Endpoints<Source, Target> & Props & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n : T extends Relation<infer Props, infer Source, infer Target, any>\n ? RelationModule.Endpoints<Source, Target> & Props & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n : T extends ObjClass<any, infer A, any>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n : T extends Obj<infer A, any>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n : T extends Type<infer A>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Type>\n : never;\n\n/**\n * Returns the Effect Schema for a type entity.\n *\n * - For static `Type.Obj` / `Type.Relation` entities the source Effect Schema is\n * read from a hidden slot — these overloads preserve the instance type.\n * - For `Type.Type` entities (the meta-schema kind) the schema is rebuilt from\n * `type.jsonSchema`; the instance type isn't statically knowable so the wide\n * `AnyEntity` overload widens to `Schema.Codec<any, any>`.\n *\n * Always call this when you need to interact with the Effect Schema API\n * (e.g. before passing to Effect.Schema functions). For ECHO-side APIs\n * (`Obj.make`, `Filter.type`, `Ref`) pass the type entity directly.\n *\n * Only accepts `Type.AnyEntity` — raw `Schema.Schema` values can be used\n * directly without unwrapping.\n *\n * @performance O(1) cached read; a persisted type rebuilds its Effect Schema from `jsonSchema` (O(schema size)) on\n * first access.\n */\nexport function getSchema<T extends AnyObj>(type: T): Schema.Codec<InstanceType<T>, unknown>;\nexport function getSchema<T extends AnyRelation>(type: T): Schema.Codec<InstanceType<T>, unknown>;\nexport function getSchema(type: AnyEntity): Schema.Codec<any, any>;\nexport function getSchema(type: AnyEntity): Schema.Codec<any, any> {\n // Static `Type.Type` entities carry the source Effect Schema on a hidden\n // slot so we can return it without round-tripping through JsonSchema.\n const staticSchema = internal.getStaticTypeSchema(type);\n if (staticSchema != null) {\n return staticSchema;\n }\n assertArgument(isType(type), 'type', 'Expected a Type entity.');\n // Persisted `Type.Type` entity — build the Effect Schema from its stored\n // jsonSchema and re-attach the TypeIdentifierAnnotation so the rebuilt\n // schema's URI (via getSchemaURI) matches the entity's local EID.\n const rebuilt = internal.toEffectSchema(type.jsonSchema);\n if (typeof type.id === 'string') {\n return rebuilt.annotate({\n [internal.TypeIdentifierAnnotationId]: EID.make({ entityId: type.id }),\n });\n }\n return rebuilt;\n}\n\n/**\n * Mutable view of a `Type.Type` — the shape passed to the `Type.update` callback.\n * Outside `Type.update`, `Type.Type` fields are read-only (both at the type level\n * and at runtime — direct assignment throws). Use this to constrain mutation to\n * the change context, analogous to `Obj.update(obj, (draft) => ...)`.\n *\n * NOTE: `typename` and `version` are intentionally absent — they live in\n * `EntityMeta` (`key` / `version` — the canonical registry-provenance pair).\n * Read them via {@link getTypename} / {@link getVersion} / {@link getMeta};\n * `typename` is treated as immutable on persisted entities.\n *\n * Unlike `Obj.update` — whose mutable view is inferred as `Mutable<A>` over the\n * whole instance type because every data field is editable — a `Type.Type`\n * exposes only `name` and `jsonSchema` for mutation. The rest of its shape\n * (`id`, the `[KindId]` / `[SchemaKindId]` brands, and `typename` / `version`\n * in meta) is immutable, so this view is declared explicitly rather than\n * derived from `InstanceType<Type.Type>`.\n */\nexport interface Mutable {\n name?: string;\n // Deep-mutable within the change context — `Type.update`'s purpose is to allow\n // mutation, so the draft exposes `jsonSchema` as writable (the readonly\n // `JsonSchemaType` would force callers to cast).\n jsonSchema: Types.DeepMutable<internal.JsonSchemaType>;\n}\n\n/**\n * Perform mutations on a `Type.Type` within a change context.\n *\n * The callback receives a {@link Mutable} view of the type — direct mutation of\n * a `Type.Type` outside `Type.update` throws at runtime, mirroring `Obj.update`.\n * Delegates to the same automerge-transaction primitive `Obj.update(obj, cb)` uses.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = (type: AnyEntity, callback: (mutable: Mutable) => void): void => {\n // `Type.Type` is an ECHO object; the change machinery is the same as `Obj.update`.\n internal.change(type, callback as internal.ChangeCallback<AnyEntity>);\n};\n\n//\n// Field-level helpers for mutating persisted types.\n// These are thin wrappers over `Type.update` plus the JsonSchema manipulation\n// utilities. Callers pass a persisted `Type.Type` (e.g. one returned by\n// `db.addType(schemaEntity)`) and the helper drives the change context.\n//\n\n/**\n * Add fields to a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const addFields = (type: AnyEntity, fields: Schema.Struct.Fields): void => {\n const extended = typeInternal.addFieldsToSchema(getSchema(type), fields);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(extended);\n });\n};\n\n/**\n * Replace existing fields on a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const updateFields = (type: AnyEntity, fields: Schema.Struct.Fields): void => {\n const updated = typeInternal.updateFieldsInSchema(getSchema(type), fields);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(updated);\n });\n};\n\n/**\n * Rename a field on a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const updateFieldPropertyName = (\n type: Type,\n { before, after }: { before: PropertyKey; after: PropertyKey },\n): void => {\n const renamed = typeInternal.updateFieldNameInSchema(getSchema(type), { before, after });\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(renamed);\n });\n};\n\n/**\n * Remove fields from a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const removeFields = (type: AnyEntity, fieldNames: string[]): void => {\n const removed = typeInternal.removeFieldsFromSchema(getSchema(type), fieldNames);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(removed);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA,IAAa,cAOR,KAAK,aAAa,WAAWA,eAAwB,KAAK,QAAQ,OAAO;;;;;;AAY9E,IAAa,OAAsCC;;;;;;;AAQnD,IAAM,gBAAgB;;;;;;;;;;;AAwBtB,IAAa,4BAA4B,UAAwD;CAC/F,MAAM,EAAE,UAAU,SAAS,GAAG,SAAS;CAKvC,OAAOC,aACLC,oBAA6BF,UAAuB,GACpD,MACA;EACE,MAAM,CAAC;EAC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,MAAM,UAAUE,wBAAqC,UAAU,IAAI,GAAG;EAAE;EAAQ;CAAM,CAAC;CACvF,OAAO,OAAO,UAAU;EACtB,MAAM,aAAaF,aAAsB,OAAO;CAClD,CAAC;AACH;;;;;;;AAQA,IAAa,gBAAgB,MAAiB,eAA+B;CAC3E,MAAM,UAAUG,uBAAoC,UAAU,IAAI,GAAG,UAAU;CAC/E,OAAO,OAAO,UAAU;EACtB,MAAM,aAAaH,aAAsB,OAAO;CAClD,CAAC;AACH"}
1
+ {"version":3,"file":"chunk-Type.mjs","names":["internal.makeObjectType","typeInternal.TypeSchema","internal.makeObject","internal.getStaticTypeSchema","internal.getTypeURIFromSpecifier","internal.makeRelationType","internal.getSchemaKind","internal.getSchemaURI","internal.getMetaChecked","internal.version","internal.getEntityKindBrand","internal.getDatabase","internal.getLabel","internal.InstancePhantomId","internal.toEffectSchema","internal.TypeIdentifierAnnotationId","typeInternal.addFieldsToSchema","internal.toJsonSchema","typeInternal.updateFieldsInSchema","typeInternal.updateFieldNameInSchema","typeInternal.removeFieldsFromSchema"],"sources":["../../src/Type.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Schema from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport { raise } from '@dxos/debug';\nimport { type EncodedReference } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { DXN, EID, type EntityId, type URI } from '@dxos/keys';\n\nimport type * as Database from './Database.ts';\nimport type * as EntityModule from './Entity.ts';\nimport * as internal from './internal/index.ts';\nimport * as typeInternal from './internal/Type/index.ts';\nimport type * as RelationModule from './Relation.ts';\n\n//\n// Internal types (not exported)\n//\n\n/**\n * Structural base shared by the three sibling type-entity interfaces\n * ({@link Obj}, {@link Relation}, {@link Type}). NOT exported — callers\n * should constrain on {@link AnyEntity} when they want \"any of the three\"\n * and on the specific kind interface otherwise.\n */\ninterface BaseTypeEntity<A> {\n /**\n * Entity-kind brand of the type-entity value itself — always `EntityKind.Type`.\n * The kind of instance the type *describes* lives on `[SchemaKindId]`\n * (Object / Relation / Type). Lets `Obj.isObject` / `Relation.isRelation`\n * reject type entities by a single `[KindId]` check.\n */\n readonly [internal.KindId]: internal.EntityKind.Type;\n\n /**\n * Object id. Like all ECHO entities, type entities always carry an id —\n * stamped at construction for in-memory (static) declarations and assigned by\n * the database once persisted. The id does NOT determine the entity's URI:\n * static types resolve to their typename DXN, persisted types to `echo:///<id>`\n * (see `getTypeURIFromSpecifier`).\n */\n readonly id: EntityId;\n\n readonly name?: string;\n // NOTE: `typename` / `version` are intentionally NOT fields on any type-entity\n // interface. Both static and persisted entities carry them in `EntityMeta`\n // (`key` / `version`); read them via `Type.getTypename(self)` /\n // `Type.getVersion(self)` — never as a direct property.\n readonly jsonSchema: internal.JsonSchemaType;\n readonly [InstancePhantomId]?: A;\n}\n\n//\n// Obj — `Type.Type` value for an ECHO object schema.\n//\n\n/**\n * TypeScript type for an ECHO object type — a `Type.Type<A>` entity.\n *\n * `T` is the instance type produced by `Obj.make(Foo, props)`. `Fields` is\n * retained as a structural hint (the runtime value still carries `.fields`),\n * but consumers should derive instance/encoded types via `Type.InstanceType`.\n *\n * **Not a `Schema.Schema`.** `Foo.ast` / `Schema.Schema.Type<typeof Foo>` /\n * `Schema.extend(Foo)` no longer typecheck — extract the Effect Schema via\n * `Type.getSchema(Foo)` first, or derive instance types via\n * `Type.InstanceType<typeof Foo>`.\n *\n * @example\n * ```ts\n * class Person extends Type.makeObject<Person>(DXN.make('com.example.type.person', '0.1.0'))(\n * Schema.Struct({ name: Schema.String }),\n * ) {}\n * ```\n */\nexport interface Obj<T, Fields extends Schema.Struct.Fields = Schema.Struct.Fields> extends BaseTypeEntity<\n T & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n> {\n /** Schema-kind brand (object). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Object;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n /**\n * The fields defined in the original struct schema.\n * Allows accessing field definitions for introspection.\n */\n readonly fields: Fields;\n}\n\n/**\n * Return type for {@link makeObject}.\n *\n * Not to be used directly, but must be exported for typescript to infer the type.\n */\nexport interface ObjClass<Self, T, Fields extends Schema.Struct.Fields> extends Obj<Self, Fields> {\n new (_: never): T & EntityModule.OfKind<typeof EntityModule.Kind.Object>;\n}\n\n/**\n * Type that represents any ECHO object type — a `Type.Type` entity branded\n * with the object entity kind, i.e. what `Type.makeObject(dxn)` produces.\n */\nexport type AnyObj = Obj<unknown>;\n\n/**\n * Factory function to create an ECHO object type.\n *\n * Returns a `Type.Type` entity — a live, in-memory `TypeSchema` instance,\n * NOT a `Schema.Schema`. Use `Type.InstanceType<typeof Foo>` for the instance\n * type and `Type.getSchema(Foo)` to obtain the underlying Effect Schema.\n *\n * The entity's id defaults to `EntityId.deterministic(typename, version)` so\n * constructing a type never reaches `crypto.getRandomValues()` — required for\n * Cloudflare workerd, which forbids RNG calls in global (module-evaluation)\n * scope. Pass `{ id }` to override (e.g. with `EntityId.random()` from a\n * request handler).\n *\n * Giving the type a nominal class name keeps its inferred type portable for\n * declaration emit: structural expansion (which can pull in unnameable union\n * members from referenced schemas) is replaced by a reference to the class.\n *\n * The second call takes either a schema, or struct fields (wrapped in `Schema.Struct`) with an optional function\n * that pipes annotations onto the struct.\n *\n * @example\n * ```ts\n * export class Person extends Type.makeObject<Person>(DXN.make('com.example.type.myType', '0.1.0'))(Schema.Struct({\n * name: Schema.String,\n * })) {}\n *\n * export class Tag extends Type.makeObject<Tag>(DXN.make('com.example.type.tag', '0.1.0'))(\n * { label: Schema.String },\n * Annotation.LabelAnnotation.set(['label']),\n * ) {}\n * ```\n *\n * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not\n * per use.\n */\n// TODO(burdon): Require { typename, version } in options.\nexport const makeObject: {\n <Self>(dxn: DXN.DXN, options?: { id?: EntityId }): MakeObject<Self>;\n // Boundary cast: overload implementation bodies cannot access outer generic params (`Self`),\n // so TypeScript cannot verify that makeObjectType's return matches the declared ObjClass<Self,…>.\n} = (dxn, options) =>\n ((input: Schema.Top | Schema.Struct.Fields, annotate?: (schema: Schema.Top) => Schema.Top) =>\n internal.makeObjectType(dxn, buildSchema(input, annotate), options)) as any;\n\n/** Wraps struct fields in `Schema.Struct` and applies the optional annotate function. */\nconst buildSchema = (\n input: Schema.Top | Schema.Struct.Fields,\n annotate?: (schema: Schema.Top) => Schema.Top,\n): Schema.Top => {\n const schema = Schema.isSchema(input) ? input : Schema.Struct(input);\n return annotate ? annotate(schema) : schema;\n};\n\n/**\n * Second stage of {@link makeObject}: takes a schema, or struct fields plus an optional annotation pipe.\n */\n// A single generic signature (not overloads) so that `Schema.Struct(...).pipe(Type.makeObject(dxn))` still infers.\nexport type MakeObject<Self> = <\n const Input extends Schema.Top | Schema.Struct.Fields,\n _Schema extends Schema.Top = ToSchema<Input>,\n>(\n input: Input,\n annotate?: (schema: ToSchema<Input>) => _Schema,\n) => ObjClass<Self, Schema.Schema.Type<_Schema>, {}>;\n\n/**\n * Schema for the input of {@link MakeObject} / {@link MakeRelation}: a schema as is, or struct fields wrapped in `Schema.Struct`.\n */\nexport type ToSchema<Input> = Input extends Schema.Top\n ? Input\n : Input extends Schema.Struct.Fields\n ? Schema.Struct<Input>\n : never;\n\n//\n// Type — the ECHO entity that holds a schema and metadata.\n// Persisted via `db.addType()`; subscribed to via `Filter.type(Type.Type)`.\n//\n\n/**\n * ECHO meta-schema entity — stores `{ name?, typename, version, jsonSchema }`.\n * Type-kind sibling of `Type.makeObject(...)` / `Type.makeRelation(...)` outputs.\n * Stored types live under this entity; filter via `Filter.type(Type.Type)`.\n */\nexport const Type: Type<typeInternal.TypeSchema> = typeInternal.TypeSchema as any;\n\n/**\n * Default version stamped on draft (unnamed) types created via\n * {@link makeObjectFromJsonSchema} / {@link makeRelationFromJsonSchema} when\n * the caller does not supply one. Pure dynamic drafts surface as `'0.0.0'`\n * until they are persisted, at which point automerge-heads suffix the version.\n */\nconst DRAFT_VERSION = '0.0.0';\n\n/**\n * Common props shared by the type-kind factories. Typename and version are\n * optional — drafts omit typename and default version to {@link DRAFT_VERSION}.\n */\ntype MakeTypeProps = {\n jsonSchema: internal.JsonSchemaType;\n typename?: string;\n version?: string;\n name?: string;\n id?: EntityId;\n};\n\n/**\n * Construct a new object-kind type entity from raw metadata — for cases where\n * an Effect Schema isn't available (e.g. JSON-Schema arriving over the network\n * or from a UI editor). Parallel to {@link makeObject} but takes pre-built\n * `jsonSchema` instead of piping through an Effect schema.\n *\n * The returned entity is in-memory; persist it with `db.addType(entity)`.\n *\n * @performance O(schema size); validates the JSON schema into a new in-memory type entity, with no database I/O.\n */\nexport const makeObjectFromJsonSchema = (props: MakeTypeProps): Type<typeInternal.TypeSchema> => {\n const { typename, version, ...data } = props;\n // `typename` / `version` are routed through `EntityMeta` (`key` / `version`)\n // — the canonical registry-provenance pair — not data fields. Drafts default\n // to `'0.0.0'`; the version is omitted from meta entirely when the caller\n // doesn't supply one so the proxy projection can apply its own default.\n return internal.makeObject(\n internal.getStaticTypeSchema(typeInternal.TypeSchema) as any,\n data as any,\n {\n keys: [],\n key: typename,\n version: version ?? DRAFT_VERSION,\n },\n typeInternal.TypeSchema,\n ) as unknown as Type<typeInternal.TypeSchema>;\n};\n\n/**\n * Construct a new relation-kind type entity from raw metadata. Parallel to\n * {@link makeRelation} but takes pre-built `jsonSchema` instead of piping\n * through an Effect schema. `source` / `target` accept either a static\n * `Type.Obj` entity or the well-known `Obj.Unknown` schema.\n *\n * The returned entity is in-memory; persist it with `db.addType(entity)`.\n *\n * @performance O(schema size); validates the JSON schema into a new in-memory type entity, with no database I/O.\n */\nexport const makeRelationFromJsonSchema = (\n props: MakeTypeProps & {\n source: AnyObj | internal.UnknownTypeSchema<any, typeof EntityModule.Kind.Object>;\n target: AnyObj | internal.UnknownTypeSchema<any, typeof EntityModule.Kind.Object>;\n },\n): Type<typeInternal.TypeSchema> => {\n const { source, target, jsonSchema, typename, version, ...rest } = props;\n // Embed source/target DXNs + relation entity-kind into the jsonSchema so the\n // entity round-trips correctly through `toEffectSchema` / queries / refs.\n const sourceURI = internal.getTypeURIFromSpecifier(source);\n const targetURI = internal.getTypeURIFromSpecifier(target);\n const enrichedJsonSchema: internal.JsonSchemaType = {\n ...jsonSchema,\n entityKind: internal.EntityKind.Relation,\n relationSource: { $ref: sourceURI },\n relationTarget: { $ref: targetURI },\n };\n // `typename` / `version` route through `EntityMeta` (see\n // {@link makeObjectFromJsonSchema}); drafts default version to `'0.0.0'`.\n return internal.makeObject(\n internal.getStaticTypeSchema(typeInternal.TypeSchema) as any,\n { ...rest, jsonSchema: enrichedJsonSchema } as any,\n {\n keys: [],\n key: typename,\n version: version ?? DRAFT_VERSION,\n },\n typeInternal.TypeSchema,\n ) as unknown as Type<typeInternal.TypeSchema>;\n};\n\n/**\n * TypeScript type for an ECHO relation type — a `Type.Type<A>` entity.\n *\n * `T` is the instance-property type produced by `Relation.make(...)` (excluding\n * source/target endpoints). `Source` and `Target` are the endpoint types.\n *\n * **Not a `Schema.Schema`.** See {@link Obj}'s note.\n */\nexport interface Relation<\n T,\n Source,\n Target,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> extends BaseTypeEntity<\n RelationModule.Endpoints<Source, Target> & T & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n> {\n /** Schema-kind brand (relation). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Relation;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n\n /**\n * The fields defined in the original struct schema.\n * Allows accessing field definitions for introspection.\n */\n readonly fields: Fields;\n}\n\n/**\n * Return type for {@link makeRelation}.\n *\n * Not to be used directly, but must be exported for typescript to infer the type.\n */\nexport interface RelationClass<Self, T, Source, Target, Fields extends Schema.Struct.Fields> extends Relation<\n Self,\n Source,\n Target,\n Fields\n> {\n new (_: never): RelationModule.Endpoints<Source, Target> & T & EntityModule.OfKind<typeof EntityModule.Kind.Relation>;\n}\n\n/**\n * Type that represents any ECHO relation type — a `Type.Type` entity branded\n * with the relation entity kind, i.e. what `Type.makeRelation(...)` produces.\n */\nexport type AnyRelation = Relation<unknown, unknown, unknown>;\n\n/**\n * Factory function to create an ECHO relation schema.\n * Adds relation metadata annotations to an Effect schema.\n *\n * @example\n * ```ts\n * class WorksFor extends Type.makeRelation<WorksFor>(DXN.make('com.example.type.worksFor', '0.1.0'))(\n * { source: Person, target: Company },\n * )(Schema.Struct({ role: Schema.String })) {}\n *\n * // Like `makeObject`, the last call also takes struct fields and an optional annotate function.\n * class Employs extends Type.makeRelation<Employs>(DXN.make('com.example.type.employs', '0.1.0'))(\n * { source: Company, target: Person },\n * )({ role: Schema.String }, Annotation.LabelAnnotation.set(['role'])) {}\n * ```\n *\n * @performance O(schema size) once at definition time; builds the type entity eagerly, so call it at module scope, not\n * per use.\n */\nexport const makeRelation: {\n <Self>(dxn: DXN.DXN): <SourceInstance, TargetInstance>(opts: {\n source: Obj<SourceInstance, any> | internal.UnknownTypeSchema<SourceInstance, typeof EntityModule.Kind.Object>;\n target: Obj<TargetInstance, any> | internal.UnknownTypeSchema<TargetInstance, typeof EntityModule.Kind.Object>;\n /**\n * Override the entity id. Defaults to `EntityId.deterministic(typename, version)`;\n * see `Type.makeObject` for the workerd motivation.\n */\n id?: EntityId;\n }) => MakeRelation<Self, SourceInstance, TargetInstance>;\n} = (dxn) => (opts) =>\n // Boundary cast: makeRelationType erases generic params since the constructor/prototype\n // wiring cannot thread them through the type system.\n ((input: Schema.Top | Schema.Struct.Fields, annotate?: (schema: Schema.Top) => Schema.Top) =>\n internal.makeRelationType({\n dxn,\n source: opts.source,\n target: opts.target,\n schema: buildSchema(input, annotate),\n id: opts.id,\n })) as any;\n\n/**\n * Last stage of {@link makeRelation}: takes a schema, or struct fields plus an optional annotation pipe.\n */\n// A single generic signature (not overloads); see {@link MakeObject}.\nexport type MakeRelation<Self, SourceInstance, TargetInstance> = <\n const Input extends Schema.Top | Schema.Struct.Fields,\n _Schema extends Schema.Top = ToSchema<Input>,\n>(\n input: Input,\n annotate?: (schema: ToSchema<Input>) => _Schema,\n) => RelationClass<\n Self,\n Schema.Schema.Type<_Schema>,\n SourceInstance & EntityModule.OfKind<typeof EntityModule.Kind.Object>,\n TargetInstance & EntityModule.OfKind<typeof EntityModule.Kind.Object>,\n {}\n>;\n\n/**\n * Type that represents any ECHO type-kind entity — a `Type.Type` meta-schema\n * value (static `Type.Type` or a persisted draft from `db.addType(...)`).\n * Mirrors {@link AnyObj} / {@link AnyRelation} for the third sibling kind.\n */\nexport type AnyType = Type<unknown>;\n\n/**\n * Any ECHO type-entity — one of the three sibling kinds: object-kind, relation-kind,\n * or type-kind (the meta-schema). APIs that want \"any ECHO type\" use this union;\n * the underlying Effect Schema is retrieved via `Type.getSchema`.\n */\nexport type AnyEntity = AnyObj | AnyRelation | AnyType;\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to an object-kind entity. Checks\n * ENTITIES, not instances — use `Obj.isObject` for instances. Raw\n * `Schema.Schema` values (including the branded `Obj.Unknown` companion)\n * are intentionally not accepted; inspect their `TypeAnnotation` directly.\n *\n * @performance O(1) brand read.\n */\nexport const isObject = (entity: AnyEntity): entity is AnyObj => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Object;\n};\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to a relation-kind entity. Checks\n * ENTITIES, not instances — use `Relation.isRelation` for instances.\n *\n * @performance O(1) brand read.\n */\nexport const isRelation = (entity: AnyEntity): entity is AnyRelation => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Relation;\n};\n\n/**\n * Type guard: narrows a `Type.AnyEntity` to the type-kind meta-schema\n * (e.g. `Type.Type`). Mirrors {@link isObject} / {@link isRelation}.\n *\n * @performance O(1) brand read.\n */\nexport const isTypeKind = (entity: AnyEntity): entity is Type => {\n return internal.getSchemaKind(entity) === internal.EntityKind.Type;\n};\n\n/**\n * Narrow a `Type.AnyEntity` (e.g. one returned from `schemaRegistry.query(...)`)\n * to `AnyObj`, throwing if it describes a relation or the type-kind\n * meta-schema. Use at call sites that need to pass the value to `Obj.make`,\n * `Filter.type`, or other object-only APIs.\n *\n * @performance O(1) brand read.\n */\nexport const assertObject = (entity: AnyEntity): AnyObj => {\n assertArgument(isObject(entity), 'entity', 'Expected an object-kind Type entity.');\n return entity;\n};\n\n/**\n * Narrow a `Type.AnyEntity` to `AnyRelation`, throwing otherwise.\n *\n * @performance O(1) brand read.\n */\nexport const expectRelation = (entity: AnyEntity): AnyRelation => {\n assertArgument(isRelation(entity), 'entity', 'Expected a relation-kind Type entity.');\n return entity;\n};\n\n/**\n * Narrow a `Type.AnyEntity` to the `Type.Type` meta-schema, throwing otherwise.\n *\n * @performance O(1) brand read.\n */\nexport const expectTypeKind = (entity: AnyEntity): Type => {\n assertArgument(isTypeKind(entity), 'entity', 'Expected a type-kind Type entity.');\n return entity;\n};\n\n/**\n * Type that represents any Ref schema (with unknown target type).\n * This is a schema type, not an instance type.\n */\nexport type AnyRef = Schema.Codec<internal.Ref<any>, EncodedReference>;\n\n//\n// Schema utility functions\n//\n\n/**\n * Returns the URI identifying a type entity. Always defined.\n *\n * - Static `Type.Obj` / `Type.Relation` → typename DXN (e.g. `dxn:com.example.type.person:0.1.0`).\n * - Persisted `Type.Type` instance (has `id`) → local `EID` (`echo:///<objectId>`).\n * - In-memory `Type.Type` draft (has `id`, no typename) → local `EID`.\n *\n * When `options.prefer === 'named'` the result is forced to a DXN — for\n * persisted type entities the typename + version from meta are used to\n * construct the DXN; static types already return a DXN by default.\n *\n * Only accepts `Type.AnyEntity` entities. Raw `Schema.Schema` values and the\n * branded `Obj.Unknown` / `Relation.Unknown` schemas are intentionally not\n * supported — use `internal.getSchemaURI` or the schema's typename annotation\n * directly when working at the schema level.\n *\n * @performance O(1); reads the id or schema identifier annotation, allocating a new URI string.\n */\nexport const getURI = (input: AnyEntity, options?: internal.GetURIOptions): URI.URI => {\n // For Type entities, route through `getTypeURIFromSpecifier` (id → EID,\n // typename/version → DXN). For Obj/Relation entities, unwrap to the source\n // Effect Schema first and read its annotations.\n if (isType(input)) {\n const uri = internal.getTypeURIFromSpecifier(input);\n if (options?.prefer === 'named' && !DXN.isDXN(uri)) {\n // Persisted type — the auto-detected URI is an EID, but caller wants a\n // DXN. Construct from typename + version (both live in EntityMeta).\n const typename = getTypename(input);\n const version = getMeta(input).version;\n if (typename && version) {\n return DXN.make(typename, version);\n }\n }\n return uri;\n }\n return internal.getSchemaURI(getSchema(input)) ?? raise(new TypeError('Type entity has no URI'));\n};\n\n/**\n * @returns The typename. Example: `com.example.type.person`.\n *\n * Persisted `Type.Type` entities carry typename in `EntityMeta.key` (the\n * canonical registry-provenance field); unnamed drafts fall back to the\n * entity's object id so the helper always returns a string. Any `dxn:` or\n * `echo:/` prefix is stripped — typename is a bare identifier, not a URI.\n *\n * @performance O(1) meta read with `jsonSchema` and id fallbacks.\n */\n// TODO(wittjosiah): For in-database types this should return the object id once the registry\n// has more robust options for shadowing types (so callers can disambiguate db-stored copies).\nexport const getTypename = (input: AnyEntity): string => {\n // Both in-memory and in-database entities carry typename in `EntityMeta.key`\n // — the canonical registry-provenance field. In-memory entities attach meta\n // eagerly (see `makeEchoTypeSchema`), so a single meta-backed read covers\n // both forms.\n const meta = internal.getMetaChecked(input);\n let typename: string | undefined = meta.key as string | undefined;\n // `meta.key` is a denormalized copy of the typename. The authoritative source\n // for a type entity is its `jsonSchema.typename` (`getSchema` rebuilds the\n // Effect Schema from `jsonSchema`). A type loaded from a snapshot can arrive\n // with `meta.key` absent (the meta round-trip dropped the denormalized copy)\n // while `jsonSchema.typename` is always present — consult it before the\n // last-resort id fallback so callers never receive a bare object id where a\n // typename is expected (e.g. `Filter.typename`, which rejects non-typenames).\n if (typename == null) {\n typename = input.jsonSchema?.typename;\n }\n // Unnamed drafts (no meta.key, no jsonSchema typename) fall back to the id.\n typename ??= input.id as string;\n // Typename is a bare identifier — strip URI prefixes if a caller seeded\n // meta.key with one accidentally (or if a static entity carries a DXN-\n // style typename).\n typename = stripTypenamePrefix(typename);\n invariant(typeof typename === 'string' && typename.length > 0, 'Invalid typename');\n return typename;\n};\n\n/**\n * Gets the version.\n * @example 0.1.0\n * @example 0.1.0-<heads> (in-database, versioned by automerge heads)\n *\n * The registry-provenance semver lives in `EntityMeta.version`; unversioned\n * drafts default to {@link DRAFT_VERSION} (`'0.0.0'`). In-database entities are\n * additionally versioned by their automerge heads, which are exposed as the\n * semver pre-release tag (`<semver>-<heads>`). In-memory declarations have no\n * heads and surface the bare semver. Read the registry semver alone via\n * `Type.getMeta(input).version`.\n *\n * @performance O(h log h) in Automerge heads for database types (sorted into the suffix per call); O(1) for in-memory\n * types.\n */\nexport const getVersion = (input: AnyEntity): string => {\n const meta = internal.getMetaChecked(input);\n // As with `getTypename`: `meta.version` is a denormalized copy; the\n // authoritative semver lives in `jsonSchema.version`. Prefer meta, fall back\n // to jsonSchema (always present on persisted types, survives serialization),\n // then to `DRAFT_VERSION` for unversioned drafts.\n const semver = (meta.version as string | undefined) ?? input.jsonSchema?.version ?? DRAFT_VERSION;\n invariant(typeof semver === 'string' && semver.match(/^\\d+\\.\\d+\\.\\d+$/), 'Invalid version');\n // In-database entities are versioned by their automerge heads; expose them as\n // the semver pre-release tag. In-memory drafts carry no heads → bare semver.\n const heads = internal.version(input).automergeHeads;\n if (heads != null && heads.length > 0) {\n return `${semver}-${[...heads].sort().join('.')}`;\n }\n return semver;\n};\n\n/**\n * Strip URI prefixes (`dxn:`, `echo:/`, `echo://`, `echo:///`) from a typename string.\n * Typename is a bare identifier — callers reading from meta or from a\n * caller-supplied seed value shouldn't propagate URI prefixes downstream.\n */\nconst stripTypenamePrefix = (value: string): string => {\n if (value.startsWith('dxn:')) {\n return value.slice('dxn:'.length);\n }\n // Strip the `echo:` scheme along with any leading slashes so every local form\n // (`echo:///<id>`, `echo:///<id>`) and the qualified `echo://<space>/<id>` collapse consistently.\n if (value.startsWith('echo:')) {\n return value.slice('echo:'.length).replace(/^\\/+/, '');\n }\n return value;\n};\n\n/**\n * Type predicate: true iff the value is any type-kind ECHO entity — a static\n * `Type.Obj` / `Type.Relation` produced by `Type.makeObject` / `Type.makeRelation`, a\n * static meta `Type.Type`, or a persisted `Type.Type` returned by the database.\n *\n * All three branches stamp `[KindId] = Type`, so this is a single brand check.\n * Use {@link isObject} / {@link isRelation} / {@link isTypeKind}\n * when you need to discriminate further; use {@link getDatabase} when you mean\n * \"is this a db-attached type\" (vs. an in-memory declaration).\n *\n * @performance O(1) brand check; no allocation.\n */\nexport const isType = (value: unknown): value is AnyEntity =>\n internal.getEntityKindBrand(value) === internal.EntityKind.Type;\n\n/**\n * Get the database the type entity belongs to, or `undefined` if it is an\n * in-memory declaration (`Type.makeObject` / `Type.makeRelation` result) not\n * yet attached to a database. Mirrors `Obj.getDatabase` / `Relation.getDatabase`.\n *\n * Database attachment is the canonical discriminator between in-memory and\n * in-database type entities — both are live reactive `TypeSchema` instances and\n * are otherwise indistinguishable.\n *\n * @performance O(1) slot read.\n */\nexport const getDatabase = (input: AnyEntity): Database.Database | undefined => internal.getDatabase(input);\n\n/**\n * Mutable meta type returned by `Type.getMeta` inside a `Type.update` callback.\n * Mirrors `Obj.Meta` / `Relation.Meta` — `Type.Type` is an Entity like its\n * siblings, so its meta is the same `EntityMeta` record:\n * `{ keys, tags?, key?, version? }`.\n *\n * `key` / `version` here are the canonical registry-provenance pair\n * (typename + semver) on persisted Type.Type entities; they are absent on\n * unnamed drafts. Use {@link getTypename} / {@link getVersion} when you want\n * a non-`undefined` value with id / {@link DRAFT_VERSION} fallbacks.\n */\nexport type Meta = internal.Meta;\n\n/**\n * Deeply read-only version of {@link Meta}.\n * Prevents mutation at all nesting levels (e.g., `meta.keys.push()` is a TS error).\n */\nexport type ReadonlyMeta = internal.ReadonlyMeta;\n\n/**\n * Returns the entity's `EntityMeta`. Same semantics as `Obj.getMeta` /\n * `Relation.getMeta` — `Type.Type` is an Entity and carries the canonical\n * `EntityMeta` directly. Returns mutable meta when passed a mutable type\n * (inside a `Type.update` callback), read-only meta otherwise.\n *\n * For persisted Type entities, `meta.key` holds the typename and\n * `meta.version` holds the semver. Use {@link getTypename} / {@link getVersion}\n * if you want the helpers' id / {@link DRAFT_VERSION} fallbacks for drafts.\n *\n * Both persisted and in-memory type entities (`Type.makeObject` /\n * `Type.makeRelation` results) carry their `EntityMeta` via `[MetaId]`, so the\n * lookup is uniform.\n *\n * @performance O(1); returns the live (memoized) meta proxy, not a copy.\n */\nexport function getMeta(entity: internal.Mutable<AnyEntity>): Meta;\nexport function getMeta(entity: Mutable): Meta;\nexport function getMeta(entity: AnyEntity): ReadonlyMeta;\nexport function getMeta(entity: AnyEntity | internal.Mutable<AnyEntity> | Mutable): ReadonlyMeta | Meta {\n // The `Mutable` overload accepts the narrowed view passed to `Type.update`\n // callbacks; at runtime that draft IS the underlying persisted Type entity,\n // so the same `MetaId` lookup works.\n assertArgument(isType(entity), 'entity', 'Expected a Type entity.');\n // Both persisted and in-memory type entities carry runtime `EntityMeta` via\n // `[MetaId]`, so the lookup is uniform.\n return internal.getMetaChecked(entity);\n}\n\n/**\n * Get the display label of a type entity.\n * Reads the field(s) nominated by the type's {@link LabelAnnotation} (e.g. `name` on persisted schemas).\n * Returns `undefined` if no label field is populated.\n *\n * @performance O(label accessors); reads the fields named by the schema `LabelAnnotation`.\n */\nexport const getLabel = (entity: AnyEntity, options?: internal.GetLabelOptions): string | undefined =>\n internal.getLabel(entity, options);\n\n/**\n * String key used to phantom-carry the instance type produced by a `Type.Type`.\n * Used by `Type.InstanceType<typeof Foo>` to recover the schema instance type\n * since `Type.makeObject(dxn)` does not return a `Schema.Schema`.\n *\n * Re-exported from the internal types layer so both `Type.ts` and internal\n * helpers (`makeObject`, `createObject`) reference the same phantom key.\n */\nexport const InstancePhantomId = internal.InstancePhantomId;\nexport type InstancePhantomId = internal.InstancePhantomId;\n\n/**\n * Sibling of {@link Obj} / {@link Relation} for the third ECHO entity kind:\n * **type-kind** entities (meta-schemas). The singleton {@link Type} const is\n * the canonical example — it describes stored type definitions themselves.\n *\n * Not a `Schema.Schema`. Use `Type.getSchema(value)` to obtain the underlying\n * Effect Schema and `Type.update(value, draft => ...)` to mutate.\n *\n * `A` is the instance-type phantom — what `Obj.make(value, ...)` would produce.\n * Merged with the `Type` const value via TypeScript declaration merging.\n */\nexport interface Type<A = unknown> extends BaseTypeEntity<A & EntityModule.OfKind<typeof EntityModule.Kind.Type>> {\n /** Schema-kind brand (type — the meta-schema kind). */\n readonly [internal.SchemaKindId]: internal.EntityKind.Type;\n\n /** Source Effect Schema — used internally by `Type.getSchema(self)`. */\n readonly [internal.StaticTypeSchemaSlot]: Schema.Codec<any, any>;\n}\n\n/**\n * Instance type produced by a Type entity.\n *\n * Accepts ONLY {@link AnyEntity} inputs — `Type.Obj`, `Type.Relation`, or\n * `Type.Type`. Raw Effect `Schema.Schema` values are rejected: for those, use\n * `Schema.Schema.Type<typeof Foo>` directly. This separation keeps the type\n * system honest about which values represent ECHO entities versus plain\n * Effect schemas.\n *\n * Dispatches on the entity kind:\n * - `Relation<Props, S, T>` → `Endpoints<S,T> & Props & OfKind<Relation>`\n * - `Obj<A>` → `A & OfKind<Object>`\n * - `Type<A>` → `A & OfKind<Type>`\n */\nexport type InstanceType<T extends AnyEntity> =\n T extends RelationClass<any, infer Props, infer Source, infer Target, any>\n ? RelationModule.Endpoints<Source, Target> & Props & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n : T extends Relation<infer Props, infer Source, infer Target, any>\n ? RelationModule.Endpoints<Source, Target> & Props & EntityModule.OfKind<typeof EntityModule.Kind.Relation>\n : T extends ObjClass<any, infer A, any>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n : T extends Obj<infer A, any>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Object>\n : T extends Type<infer A>\n ? A & EntityModule.OfKind<typeof EntityModule.Kind.Type>\n : never;\n\n/**\n * Returns the Effect Schema for a type entity.\n *\n * - For static `Type.Obj` / `Type.Relation` entities the source Effect Schema is\n * read from a hidden slot — these overloads preserve the instance type.\n * - For `Type.Type` entities (the meta-schema kind) the schema is rebuilt from\n * `type.jsonSchema`; the instance type isn't statically knowable so the wide\n * `AnyEntity` overload widens to `Schema.Codec<any, any>`.\n *\n * Always call this when you need to interact with the Effect Schema API\n * (e.g. before passing to Effect.Schema functions). For ECHO-side APIs\n * (`Obj.make`, `Filter.type`, `Ref`) pass the type entity directly.\n *\n * Only accepts `Type.AnyEntity` — raw `Schema.Schema` values can be used\n * directly without unwrapping.\n *\n * @performance O(1) cached read; a persisted type rebuilds its Effect Schema from `jsonSchema` (O(schema size)) on\n * first access.\n */\nexport function getSchema<T extends AnyObj>(type: T): Schema.Codec<InstanceType<T>, unknown>;\nexport function getSchema<T extends AnyRelation>(type: T): Schema.Codec<InstanceType<T>, unknown>;\nexport function getSchema(type: AnyEntity): Schema.Codec<any, any>;\nexport function getSchema(type: AnyEntity): Schema.Codec<any, any> {\n // Static `Type.Type` entities carry the source Effect Schema on a hidden\n // slot so we can return it without round-tripping through JsonSchema.\n const staticSchema = internal.getStaticTypeSchema(type);\n if (staticSchema != null) {\n return staticSchema;\n }\n assertArgument(isType(type), 'type', 'Expected a Type entity.');\n // Persisted `Type.Type` entity — build the Effect Schema from its stored\n // jsonSchema and re-attach the TypeIdentifierAnnotation so the rebuilt\n // schema's URI (via getSchemaURI) matches the entity's local EID.\n const rebuilt = internal.toEffectSchema(type.jsonSchema);\n if (typeof type.id === 'string') {\n return rebuilt.annotate({\n [internal.TypeIdentifierAnnotationId]: EID.make({ entityId: type.id }),\n });\n }\n return rebuilt;\n}\n\n/**\n * Mutable view of a `Type.Type` — the shape passed to the `Type.update` callback.\n * Outside `Type.update`, `Type.Type` fields are read-only (both at the type level\n * and at runtime — direct assignment throws). Use this to constrain mutation to\n * the change context, analogous to `Obj.update(obj, (draft) => ...)`.\n *\n * NOTE: `typename` and `version` are intentionally absent — they live in\n * `EntityMeta` (`key` / `version` — the canonical registry-provenance pair).\n * Read them via {@link getTypename} / {@link getVersion} / {@link getMeta};\n * `typename` is treated as immutable on persisted entities.\n *\n * Unlike `Obj.update` — whose mutable view is inferred as `Mutable<A>` over the\n * whole instance type because every data field is editable — a `Type.Type`\n * exposes only `name` and `jsonSchema` for mutation. The rest of its shape\n * (`id`, the `[KindId]` / `[SchemaKindId]` brands, and `typename` / `version`\n * in meta) is immutable, so this view is declared explicitly rather than\n * derived from `InstanceType<Type.Type>`.\n */\nexport interface Mutable {\n name?: string;\n // Deep-mutable within the change context — `Type.update`'s purpose is to allow\n // mutation, so the draft exposes `jsonSchema` as writable (the readonly\n // `JsonSchemaType` would force callers to cast).\n jsonSchema: Types.DeepMutable<internal.JsonSchemaType>;\n}\n\n/**\n * Perform mutations on a `Type.Type` within a change context.\n *\n * The callback receives a {@link Mutable} view of the type — direct mutation of\n * a `Type.Type` outside `Type.update` throws at runtime, mirroring `Obj.update`.\n * Delegates to the same automerge-transaction primitive `Obj.update(obj, cb)` uses.\n *\n * @performance Synchronous; costs the mutations made in the callback plus one batched notification.\n */\nexport const update = (type: AnyEntity, callback: (mutable: Mutable) => void): void => {\n // `Type.Type` is an ECHO object; the change machinery is the same as `Obj.update`.\n internal.change(type, callback as internal.ChangeCallback<AnyEntity>);\n};\n\n//\n// Field-level helpers for mutating persisted types.\n// These are thin wrappers over `Type.update` plus the JsonSchema manipulation\n// utilities. Callers pass a persisted `Type.Type` (e.g. one returned by\n// `db.addType(schemaEntity)`) and the helper drives the change context.\n//\n\n/**\n * Add fields to a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const addFields = (type: AnyEntity, fields: Schema.Struct.Fields): void => {\n const extended = typeInternal.addFieldsToSchema(getSchema(type), fields);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(extended);\n });\n};\n\n/**\n * Replace existing fields on a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const updateFields = (type: AnyEntity, fields: Schema.Struct.Fields): void => {\n const updated = typeInternal.updateFieldsInSchema(getSchema(type), fields);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(updated);\n });\n};\n\n/**\n * Rename a field on a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const updateFieldPropertyName = (\n type: Type,\n { before, after }: { before: PropertyKey; after: PropertyKey },\n): void => {\n const renamed = typeInternal.updateFieldNameInSchema(getSchema(type), { before, after });\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(renamed);\n });\n};\n\n/**\n * Remove fields from a persisted type's schema.\n * @throws if the type is not persisted.\n *\n * @performance O(schema size); rebuilds and re-encodes the whole JSON schema, then writes it in one change.\n */\nexport const removeFields = (type: AnyEntity, fieldNames: string[]): void => {\n const removed = typeInternal.removeFieldsFromSchema(getSchema(type), fieldNames);\n update(type, (draft) => {\n draft.jsonSchema = internal.toJsonSchema(removed);\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmJA,IAAa,cAIR,KAAK,cACN,OAA0C,aAC1CA,eAAwB,KAAK,YAAY,OAAO,QAAQ,GAAG,OAAO;;AAGtE,IAAM,eACJ,OACA,aACe;CACf,MAAM,SAAS,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAO,OAAO,KAAK;CACnE,OAAO,WAAW,SAAS,MAAM,IAAI;AACvC;;;;;;AAiCA,IAAa,OAAsCC;;;;;;;AAQnD,IAAM,gBAAgB;;;;;;;;;;;AAwBtB,IAAa,4BAA4B,UAAwD;CAC/F,MAAM,EAAE,UAAU,SAAS,GAAG,SA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AO,UAAU;EACtB,MAAM,aAAaD,aAAsB,OAAO;CAClD,CAAC;AACH;;;;;;;AAQA,IAAa,2BACX,MACA,EAAE,QAAQ,YACD;CACT,MAAM,UAAUE,wBAAqC,UAAU,IAAI,GAAG;EAAE;EAAQ;CAAM,CAAC;CACvF,OAAO,OAAO,UAAU;EACtB,MAAM,aAAaF,aAAsB,OAAO;CAClD,CAAC;AACH;;;;;;;AAQA,IAAa,gBAAgB,MAAiB,eAA+B;CAC3E,MAAM,UAAUG,uBAAoC,UAAU,IAAI,GAAG,UAAU;CAC/E,OAAO,OAAO,UAAU;EACtB,MAAM,aAAaH,aAAsB,OAAO;CAClD,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
- import { tt as IconAnnotation } from "./chunk-Database.mjs";
2
+ import { ot as IconAnnotation } from "./chunk-Database.mjs";
3
3
  import { u as JsonSchemaType } from "./chunk-json-schema.mjs";
4
4
  import { y as makeObject } from "./chunk-Type.mjs";
5
5
  import { G as make$1 } from "./chunk-Obj.mjs";