@dxos/echo 0.9.1-main.c7dcc2e112 → 0.9.1-staging.ee54ba693a
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.
- package/dist/lib/neutral/Annotation.mjs +22 -8
- package/dist/lib/neutral/Database.mjs +3 -3
- package/dist/lib/neutral/Entity.mjs +11 -11
- package/dist/lib/neutral/Err.mjs +7 -3
- package/dist/lib/neutral/Feed.mjs +15 -19
- package/dist/lib/neutral/Filter.mjs +13 -11
- package/dist/lib/neutral/Format.mjs +3 -7
- package/dist/lib/neutral/JsonSchema.mjs +7 -7
- package/dist/lib/neutral/Migration.mjs +11 -11
- package/dist/lib/neutral/Obj.mjs +15 -13
- package/dist/lib/neutral/Order.mjs +1 -1
- package/dist/lib/neutral/Query.mjs +17 -17
- package/dist/lib/neutral/QueryResult.mjs +1 -1
- package/dist/lib/neutral/Ref.mjs +6 -6
- package/dist/lib/neutral/Registry.mjs +1 -1
- package/dist/lib/neutral/Relation.mjs +12 -12
- package/dist/lib/neutral/Tag.mjs +15 -15
- package/dist/lib/neutral/Text.mjs +25 -0
- package/dist/lib/neutral/Text.mjs.map +7 -0
- package/dist/lib/neutral/Type.mjs +10 -10
- package/dist/lib/neutral/chunk-2HKGAQM4.mjs +1394 -0
- package/dist/lib/neutral/chunk-2HKGAQM4.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-O6BH7EPN.mjs → chunk-2ZHECXUR.mjs} +5 -4
- package/dist/lib/neutral/chunk-2ZHECXUR.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-AFANXSGV.mjs → chunk-3KTE2Y7Q.mjs} +20 -20
- package/dist/lib/neutral/chunk-3KTE2Y7Q.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-WZ32BF53.mjs → chunk-3TN2VMI4.mjs} +49 -37
- package/dist/lib/neutral/chunk-3TN2VMI4.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-E7IOTOZD.mjs → chunk-42L4HJ3Z.mjs} +11 -15
- package/dist/lib/neutral/chunk-42L4HJ3Z.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-K3S7D5PR.mjs → chunk-4A2NWKRJ.mjs} +5 -5
- package/dist/lib/neutral/chunk-ACFAOTKJ.mjs +1531 -0
- package/dist/lib/neutral/chunk-ACFAOTKJ.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-Z3WMRRAZ.mjs → chunk-BEFR7LEA.mjs} +11 -9
- package/dist/lib/neutral/{chunk-Z3WMRRAZ.mjs.map → chunk-BEFR7LEA.mjs.map} +1 -1
- package/dist/lib/neutral/{chunk-6M2Z6WBH.mjs → chunk-BXIKXT7Q.mjs} +2 -6
- package/dist/lib/neutral/{chunk-6M2Z6WBH.mjs.map → chunk-BXIKXT7Q.mjs.map} +1 -1
- package/dist/lib/neutral/{chunk-3JXQUMUI.mjs → chunk-C57XMMBY.mjs} +21 -20
- package/dist/lib/neutral/chunk-C57XMMBY.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-JZ6LFQU5.mjs → chunk-C62JYFAD.mjs} +82 -8
- package/dist/lib/neutral/chunk-C62JYFAD.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-TF5BSLF6.mjs → chunk-FSGX2R62.mjs} +3 -3
- package/dist/lib/neutral/chunk-FSGX2R62.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-6CEISA3V.mjs → chunk-HBXT3GSB.mjs} +29 -15
- package/dist/lib/neutral/chunk-HBXT3GSB.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-WU3GIANS.mjs → chunk-IQR45HAD.mjs} +1 -1
- package/dist/lib/neutral/chunk-IQR45HAD.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-TFEWTY5A.mjs → chunk-KCBW4BR6.mjs} +4 -8
- package/dist/lib/neutral/chunk-KCBW4BR6.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-4TPQZPLY.mjs → chunk-L3E5IXAE.mjs} +198 -30
- package/dist/lib/neutral/chunk-L3E5IXAE.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-EVK6XBXO.mjs → chunk-PRC4FEKJ.mjs} +2 -2
- package/dist/lib/neutral/chunk-PRC4FEKJ.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-NOL7O3BL.mjs → chunk-SCT6FFCR.mjs} +9 -4
- package/dist/lib/neutral/chunk-SCT6FFCR.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-BBFJWWAV.mjs → chunk-TOCVVFK2.mjs} +26 -2
- package/dist/lib/neutral/chunk-TOCVVFK2.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-A53NTBHE.mjs → chunk-U53LSQQA.mjs} +3 -3
- package/dist/lib/neutral/{chunk-A53NTBHE.mjs.map → chunk-U53LSQQA.mjs.map} +1 -1
- package/dist/lib/neutral/{chunk-PLDMJJJC.mjs → chunk-UGFFV2FR.mjs} +2 -2
- package/dist/lib/neutral/{chunk-35INCYOE.mjs → chunk-UWLP4RFM.mjs} +1 -1
- package/dist/lib/neutral/chunk-UWLP4RFM.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-SZ5WB6HF.mjs → chunk-UZHCQ6NI.mjs} +13 -11
- package/dist/lib/neutral/{chunk-SZ5WB6HF.mjs.map → chunk-UZHCQ6NI.mjs.map} +3 -3
- package/dist/lib/neutral/{chunk-L3OBWBV2.mjs → chunk-WKIT2YY5.mjs} +2 -2
- package/dist/lib/neutral/{chunk-HGWQR5KH.mjs → chunk-XB6ISRAO.mjs} +27 -15
- package/dist/lib/neutral/chunk-XB6ISRAO.mjs.map +7 -0
- package/dist/lib/neutral/chunk-XXL42WCB.mjs +84 -0
- package/dist/lib/neutral/chunk-XXL42WCB.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-5GAIWRQB.mjs → chunk-XXWK4J53.mjs} +27 -42
- package/dist/lib/neutral/chunk-XXWK4J53.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +30 -26
- package/dist/lib/neutral/internal/index.mjs +91 -69
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/lib/neutral/testing/index.mjs +79 -60
- package/dist/lib/neutral/testing/index.mjs.map +3 -3
- package/dist/types/src/Annotation.d.ts +35 -1
- package/dist/types/src/Annotation.d.ts.map +1 -1
- package/dist/types/src/Collection.d.ts +9 -8
- package/dist/types/src/Collection.d.ts.map +1 -1
- package/dist/types/src/Database.d.ts +16 -0
- package/dist/types/src/Database.d.ts.map +1 -1
- package/dist/types/src/Dataset.d.ts +1 -16
- package/dist/types/src/Dataset.d.ts.map +1 -1
- package/dist/types/src/Err.d.ts +67 -0
- package/dist/types/src/Err.d.ts.map +1 -1
- package/dist/types/src/Feed.d.ts +56 -80
- package/dist/types/src/Feed.d.ts.map +1 -1
- package/dist/types/src/Filter.d.ts +9 -1
- package/dist/types/src/Filter.d.ts.map +1 -1
- package/dist/types/src/Hypergraph.d.ts +2 -9
- package/dist/types/src/Hypergraph.d.ts.map +1 -1
- package/dist/types/src/Migration.d.ts +1 -1
- package/dist/types/src/Migration.d.ts.map +1 -1
- package/dist/types/src/Obj.d.ts +31 -6
- package/dist/types/src/Obj.d.ts.map +1 -1
- package/dist/types/src/Order.d.ts +1 -1
- package/dist/types/src/Order.d.ts.map +1 -1
- package/dist/types/src/Query.d.ts +1 -1
- package/dist/types/src/Query.d.ts.map +1 -1
- package/dist/types/src/QueryResult.d.ts +2 -2
- package/dist/types/src/QueryResult.d.ts.map +1 -1
- package/dist/types/src/Ref.d.ts +8 -4
- package/dist/types/src/Ref.d.ts.map +1 -1
- package/dist/types/src/Registry.d.ts +1 -1
- package/dist/types/src/Relation.d.ts.map +1 -1
- package/dist/types/src/Tag.d.ts +11 -13
- package/dist/types/src/Tag.d.ts.map +1 -1
- package/dist/types/src/Text.d.ts +41 -0
- package/dist/types/src/Text.d.ts.map +1 -0
- package/dist/types/src/Text.test.d.ts +2 -0
- package/dist/types/src/Text.test.d.ts.map +1 -0
- package/dist/types/src/Type.d.ts +33 -20
- package/dist/types/src/Type.d.ts.map +1 -1
- package/dist/types/src/View.d.ts +8 -9
- package/dist/types/src/View.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/internal/Annotation/annotations.d.ts +9 -0
- package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
- package/dist/types/src/internal/Annotation/atoms.d.ts +14 -0
- package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -0
- package/dist/types/src/internal/Annotation/entity-dictionary.d.ts +13 -0
- package/dist/types/src/internal/Annotation/entity-dictionary.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/guard.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/model.d.ts +1 -1
- package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/object.d.ts +5 -1
- package/dist/types/src/internal/Entity/object.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/relation.d.ts +7 -0
- package/dist/types/src/internal/Entity/relation.d.ts.map +1 -1
- package/dist/types/src/internal/Entity/type-uri.d.ts.map +1 -1
- package/dist/types/src/internal/Filter/index.d.ts +2 -0
- package/dist/types/src/internal/Filter/index.d.ts.map +1 -0
- package/dist/types/src/internal/Filter/match.d.ts +22 -0
- package/dist/types/src/internal/Filter/match.d.ts.map +1 -0
- package/dist/types/src/internal/Format/format.d.ts +0 -2
- package/dist/types/src/internal/Format/format.d.ts.map +1 -1
- package/dist/types/src/internal/Format/index.d.ts +2 -2
- package/dist/types/src/internal/Format/index.d.ts.map +1 -1
- package/dist/types/src/internal/Format/string.d.ts +0 -8
- package/dist/types/src/internal/Format/string.d.ts.map +1 -1
- package/dist/types/src/internal/Format/types.d.ts +2 -1
- package/dist/types/src/internal/Format/types.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/atoms.d.ts +7 -3
- package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/clone.d.ts +2 -1
- package/dist/types/src/internal/Obj/clone.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/create-object.d.ts +3 -4
- package/dist/types/src/internal/Obj/create-object.d.ts.map +1 -1
- package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
- package/dist/types/src/internal/Query/index.d.ts +1 -0
- package/dist/types/src/internal/Query/index.d.ts.map +1 -1
- package/dist/types/src/internal/Query/query-result-effect.d.ts +9 -0
- package/dist/types/src/internal/Query/query-result-effect.d.ts.map +1 -0
- package/dist/types/src/internal/Ref/atoms.d.ts +1 -2
- package/dist/types/src/internal/Ref/atoms.d.ts.map +1 -1
- package/dist/types/src/internal/Ref/ref.d.ts +13 -6
- package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
- package/dist/types/src/internal/common/atom-snapshot.d.ts +8 -0
- package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -0
- package/dist/types/src/internal/common/proxy/make-object.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/proxy-types.d.ts +12 -0
- package/dist/types/src/internal/common/proxy/proxy-types.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/proxy-utils.d.ts +25 -0
- package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/schema-validator.d.ts +5 -0
- package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
- package/dist/types/src/internal/common/proxy/typed-handler.d.ts +17 -0
- package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
- package/dist/types/src/internal/common/types/entity.d.ts +4 -4
- package/dist/types/src/internal/common/types/entity.d.ts.map +1 -1
- package/dist/types/src/internal/common/types/meta.d.ts +2 -4
- package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
- package/dist/types/src/internal/index.d.ts +1 -0
- package/dist/types/src/internal/index.d.ts.map +1 -1
- package/dist/types/src/testing/test-schema.d.ts +42 -171
- package/dist/types/src/testing/test-schema.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +20 -13
- package/src/Annotation.test.ts +257 -10
- package/src/Annotation.ts +55 -6
- package/src/Collection.ts +10 -12
- package/src/Database.ts +22 -20
- package/src/Err.ts +22 -0
- package/src/Feed.ts +114 -141
- package/src/Filter.test.ts +38 -0
- package/src/Filter.ts +17 -3
- package/src/Hypergraph.ts +2 -11
- package/src/Migration.ts +1 -1
- package/src/Obj.test.ts +92 -12
- package/src/Obj.ts +36 -5
- package/src/Order.ts +3 -3
- package/src/Query.test.ts +2 -2
- package/src/Query.ts +16 -16
- package/src/QueryResult.ts +2 -2
- package/src/Ref.ts +12 -4
- package/src/Registry.ts +1 -1
- package/src/Relation.ts +1 -1
- package/src/Tag.ts +12 -16
- package/src/Text.test.ts +186 -0
- package/src/Text.ts +116 -0
- package/src/Type.test.ts +52 -24
- package/src/Type.ts +69 -31
- package/src/View.ts +22 -30
- package/src/index.ts +1 -1
- package/src/internal/Annotation/annotations.ts +15 -2
- package/src/internal/Annotation/atoms.ts +107 -0
- package/src/internal/Annotation/entity-dictionary.ts +40 -37
- package/src/internal/Entity/api.ts +1 -1
- package/src/internal/Entity/guard.ts +2 -1
- package/src/internal/Entity/model.ts +2 -2
- package/src/internal/Entity/object.ts +14 -1
- package/src/internal/Entity/relation.ts +19 -0
- package/src/internal/Entity/type-uri.ts +3 -1
- package/src/internal/Filter/index.ts +5 -0
- package/src/internal/Filter/match.ts +284 -0
- package/src/internal/Format/format.ts +0 -2
- package/src/internal/Format/index.ts +2 -2
- package/src/internal/Format/string.ts +0 -12
- package/src/internal/Format/types.ts +4 -2
- package/src/internal/JsonSchema/json-schema.test.ts +82 -54
- package/src/internal/Obj/atoms.ts +31 -18
- package/src/internal/Obj/clone.ts +61 -20
- package/src/internal/Obj/create-object.test.ts +3 -3
- package/src/internal/Obj/create-object.ts +3 -4
- package/src/internal/Obj/inspect.ts +1 -1
- package/src/internal/Obj/json-serializer.test.ts +7 -5
- package/src/internal/Obj/json-serializer.ts +1 -1
- package/src/internal/Obj/schema-validator.test.ts +53 -0
- package/src/internal/Obj/set-value.test.ts +29 -19
- package/src/internal/Query/index.ts +1 -0
- package/src/internal/Query/query-result-effect.ts +35 -0
- package/src/internal/Ref/atoms.ts +23 -3
- package/src/internal/Ref/ref.test.ts +8 -8
- package/src/internal/Ref/ref.ts +26 -20
- package/src/internal/common/atom-snapshot.ts +19 -0
- package/src/internal/common/proxy/make-object.ts +1 -1
- package/src/internal/common/proxy/proxy-types.ts +20 -0
- package/src/internal/common/proxy/proxy-utils.ts +37 -1
- package/src/internal/common/proxy/reactive-array.ts +3 -3
- package/src/internal/common/proxy/reactive.test.ts +1 -1
- package/src/internal/common/proxy/schema-validator.ts +181 -8
- package/src/internal/common/proxy/typed-handler.ts +254 -76
- package/src/internal/common/types/entity.ts +15 -7
- package/src/internal/index.ts +1 -0
- package/src/testing/test-schema.ts +75 -90
- package/dist/lib/neutral/chunk-35INCYOE.mjs.map +0 -7
- package/dist/lib/neutral/chunk-3JXQUMUI.mjs.map +0 -7
- package/dist/lib/neutral/chunk-4TPQZPLY.mjs.map +0 -7
- package/dist/lib/neutral/chunk-5GAIWRQB.mjs.map +0 -7
- package/dist/lib/neutral/chunk-6CEISA3V.mjs.map +0 -7
- package/dist/lib/neutral/chunk-AFANXSGV.mjs.map +0 -7
- package/dist/lib/neutral/chunk-BBFJWWAV.mjs.map +0 -7
- package/dist/lib/neutral/chunk-E7IOTOZD.mjs.map +0 -7
- package/dist/lib/neutral/chunk-EVK6XBXO.mjs.map +0 -7
- package/dist/lib/neutral/chunk-HGWQR5KH.mjs.map +0 -7
- package/dist/lib/neutral/chunk-JZ6LFQU5.mjs.map +0 -7
- package/dist/lib/neutral/chunk-NOL7O3BL.mjs.map +0 -7
- package/dist/lib/neutral/chunk-O6BH7EPN.mjs.map +0 -7
- package/dist/lib/neutral/chunk-TF5BSLF6.mjs.map +0 -7
- package/dist/lib/neutral/chunk-TFEWTY5A.mjs.map +0 -7
- package/dist/lib/neutral/chunk-VQYL2OQF.mjs +0 -2353
- package/dist/lib/neutral/chunk-VQYL2OQF.mjs.map +0 -7
- package/dist/lib/neutral/chunk-WU3GIANS.mjs.map +0 -7
- package/dist/lib/neutral/chunk-WZ32BF53.mjs.map +0 -7
- package/dist/lib/neutral/chunk-X3NUUON4.mjs +0 -184
- package/dist/lib/neutral/chunk-X3NUUON4.mjs.map +0 -7
- package/dist/types/src/exemplars.test.d.ts +0 -2
- package/dist/types/src/exemplars.test.d.ts.map +0 -1
- package/dist/types/src/hierarchy.test.d.ts +0 -2
- package/dist/types/src/hierarchy.test.d.ts.map +0 -1
- package/src/exemplars.test.ts +0 -21
- package/src/hierarchy.test.ts +0 -33
- /package/dist/lib/neutral/{chunk-K3S7D5PR.mjs.map → chunk-4A2NWKRJ.mjs.map} +0 -0
- /package/dist/lib/neutral/{chunk-PLDMJJJC.mjs.map → chunk-UGFFV2FR.mjs.map} +0 -0
- /package/dist/lib/neutral/{chunk-L3OBWBV2.mjs.map → chunk-WKIT2YY5.mjs.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/internal/common/types/well-known-types.ts", "../../../src/internal/common/types/meta.ts", "../../../src/internal/common/api/meta.ts", "../../../src/internal/Entity/guard.ts", "../../../src/internal/Annotation/entity-dictionary.ts", "../../../src/internal/common/proxy/define-hidden-property.ts", "../../../src/internal/common/proxy/json-serializer.ts", "../../../src/internal/common/proxy/event-batch.ts", "../../../src/internal/common/proxy/change-context.ts", "../../../src/internal/common/proxy/errors.ts", "../../../src/internal/common/proxy/ownership.ts", "../../../src/internal/common/proxy/proxy-types.ts", "../../../src/internal/common/proxy/reactive-array.ts", "../../../src/internal/common/proxy/schema-validator.ts", "../../../src/internal/common/proxy/typed-handler.ts", "../../../src/internal/common/proxy/make-object.ts", "../../../src/internal/Entity/entity.ts", "../../../src/internal/common/atom-snapshot.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\nimport { DXN } from '@dxos/keys';\n\n/**\n * DXN identity of the system {@link Tag} type.\n *\n * Defined in this low-level leaf so it can be shared by the public `Tag` type (which brands the\n * schema with this DXN) and by `EntityMetaSchema.tags` (which builds a `Ref<Tag>` schema from it)\n * without either importing the other — `Tag` is top-level and `meta` is deep-internal, so a direct\n * dependency between them would form an eval-order cycle.\n */\nexport const TagTypeDXN = DXN.make('org.dxos.type.tag', '0.1.0');\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { type EncodedReference, ForeignKey } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { DXN } from '@dxos/keys';\nimport { type Comparator, intersection } from '@dxos/util';\n\nimport type * as Tag from '../../../Tag';\nimport { Dictionary } from '../../Annotation/dictionary';\n// `meta` is no longer re-exported from the `common/types` barrel (see ./index.ts), so importing the\n// Ref schema builder here no longer forms an eval-order cycle with `Annotation`/`Database`.\nimport { type Ref, createEchoReferenceSchema } from '../../Ref/ref';\nimport { type AnyProperties } from './base';\nimport { MetaId } from './model-symbols';\nimport { TagTypeDXN } from './well-known-types';\n\n/**\n * Property name for meta when object is serialized to JSON.\n */\nexport const ATTR_META = '@meta';\n\n//\n// EntityMeta\n//\n\n/**\n * Schema for references to {@link Tag} objects stored in {@link EntityMetaSchema.tags}.\n *\n * Built from the shared {@link createEchoReferenceSchema} (the same builder `Ref.Ref` uses) via\n * `Schema.suspend`, so it reuses the canonical ref codec rather than duplicating it. The Tag type\n * identity comes from the shared {@link TagTypeDXN} constant; `suspend` defers construction until\n * first use, and `Tag` is referenced type-only, so no `Tag` value import is needed.\n */\nconst TagRefSchema = Schema.suspend(\n (): Schema.Schema<Ref<Tag.Tag>, EncodedReference> =>\n // The factory yields a loosely-typed `Ref<any>` schema; narrow it to the Tag-typed ref.\n createEchoReferenceSchema(undefined, DXN.getName(TagTypeDXN), DXN.getVersion(TagTypeDXN)) as Schema.Schema<\n Ref<Tag.Tag>,\n EncodedReference\n >,\n);\n\nexport const EntityMetaSchema = Schema.Struct({\n keys: Schema.Array(ForeignKey),\n\n /**\n * Tags applied to this entity, as references to {@link Tag} objects.\n */\n tags: Schema.Array(TagRefSchema),\n\n /**\n * Fully-qualified registry key for the object (FQN format, e.g. `org.example.type.foo`).\n * Identifies the canonical registry entry the object instance was created from.\n */\n key: Schema.optional(Schema.String),\n\n /**\n * Semantic version of the registry entry the object was created from.\n * Must be a valid semver string (e.g. `1.2.3`).\n */\n version: Schema.optional(Schema.String),\n\n /**\n * Dictionary of annotations to this entity.\n */\n annotations: Dictionary,\n\n /**\n * Unix ms timestamp when this entity was created.\n * Read-only; sourced from the system section of the automerge document — not stored in meta.\n */\n createdAt: Schema.optional(Schema.Number),\n\n /**\n * Unix ms timestamp of the last automerge change on this entity's document.\n * Read-only; derived from the automerge change graph — not stored in meta.\n */\n updatedAt: Schema.optional(Schema.Number),\n});\n\nexport type EntityMeta = Schema.Schema.Type<typeof EntityMetaSchema>;\n\n/*\n * Get metadata from object.\n * Only callable on the object root.\n *\n * @internal (use Obj.getMeta or Relation.getMeta)\n */\n// TODO(burdon): Refine type to BaseObj.\nexport const getMeta = (obj: AnyProperties): EntityMeta => {\n const metadata = (obj as any)[MetaId];\n invariant(metadata, 'EntityMeta not found.');\n return metadata;\n};\n\n//\n// Foreign keys\n//\n\nexport const foreignKey = (source: string, id: string): ForeignKey => ({ source, id });\nexport const foreignKeyEquals = (a: ForeignKey, b: ForeignKey) => a.source === b.source && a.id === b.id;\n\n// TODO(dmaretskyi): Move to echo-schema.\nexport const compareForeignKeys: Comparator<AnyProperties> = (a: AnyProperties, b: AnyProperties) =>\n intersection(getMeta(a).keys, getMeta(b).keys, foreignKeyEquals).length > 0;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport type { ForeignKey } from '@dxos/echo-protocol';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport type { DeepReadonly } from '@dxos/util';\n\nimport type * as Tag from '../../../Tag';\nimport type { Ref } from '../../Ref/ref';\nimport { type Mutable } from '../proxy';\nimport { type AnyProperties } from '../types';\nimport { type EntityMeta, getMeta as getMeta$ } from '../types/meta';\n\n/**\n * Deeply read-only version of EntityMeta.\n */\nexport type ReadonlyMeta = DeepReadonly<EntityMeta>;\n\n/**\n * Mutable meta type received in meta mutation callbacks.\n */\nexport type Meta = Mutable<EntityMeta>;\n\n/**\n * Get the metadata for an entity with validation.\n * Returns mutable meta when passed a mutable entity (inside change callback).\n * Returns read-only meta when passed a regular entity or snapshot.\n *\n * TODO(burdon): When passed a Snapshot, should return a snapshot of meta, not the live meta proxy.\n */\nexport function getMetaChecked(entity: Mutable<AnyProperties>): Meta;\nexport function getMetaChecked(entity: AnyProperties): ReadonlyMeta;\nexport function getMetaChecked(entity: AnyProperties): Meta | ReadonlyMeta {\n assertArgument(entity, 'entity', 'Should be an entity.');\n const meta = getMeta$(entity);\n invariant(meta != null, 'Invalid entity.');\n return meta;\n}\n\n/**\n * @returns Foreign keys for the entity from the specified source.\n * Accepts both reactive entities and snapshots.\n */\nexport const getKeys = (entity: AnyProperties, source: string): ForeignKey[] => {\n assertArgument(entity, 'entity', 'Should be an entity.');\n const meta = getMetaChecked(entity);\n invariant(meta != null, 'Invalid entity.');\n return meta.keys.filter((key) => key.source === source);\n};\n\n/**\n * Delete all keys from the entity for the specified source.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const deleteKeys = (entity: Mutable<AnyProperties>, source: string) => {\n const meta = getMetaChecked(entity);\n for (let i = 0; i < meta.keys.length; i++) {\n if (meta.keys[i].source === source) {\n meta.keys.splice(i, 1);\n i--;\n }\n }\n};\n\n/**\n * Add a tag (a reference to a {@link Tag} object) to the entity. Idempotent.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const addTag = (entity: Mutable<AnyProperties>, tag: Ref<Tag.Tag>) => {\n const meta = getMetaChecked(entity);\n // Two refs to the same target are not `===`; dedupe by URI.\n if (!meta.tags.some((existing) => existing.uri === tag.uri)) {\n meta.tags.push(tag);\n }\n};\n\n/**\n * Remove a tag (a reference to a {@link Tag} object) from the entity. No-op when not present.\n * Must be called within an Obj.update or Relation.update callback.\n */\nexport const removeTag = (entity: Mutable<AnyProperties>, tag: Ref<Tag.Tag>) => {\n const meta = getMetaChecked(entity);\n for (let i = 0; i < meta.tags.length; i++) {\n if (meta.tags[i].uri === tag.uri) {\n meta.tags.splice(i, 1);\n i--;\n }\n }\n};\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Entity from '../../Entity';\nimport { KindId, SnapshotKindId } from '../common/types';\n\n/**\n * Returns true if the value is an ECHO entity instance (object or relation).\n */\nexport const isEntity = (value: unknown): value is Entity.Unknown => {\n // (some) type entities are functions since they are class declarations.\n if (value == null || (typeof value !== 'object' && typeof value !== 'function')) {\n return false;\n }\n return (value as any)[KindId] !== undefined;\n};\n\n/**\n * Returns true if the value is an ECHO entity snapshot.\n */\nexport const isSnapshot = (value: unknown): value is Entity.Snapshot => {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n return (value as any)[SnapshotKindId] !== undefined;\n};\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\n\nimport type * as Annotation from '../../Annotation';\nimport type * as Entity from '../../Entity';\nimport { getMetaChecked } from '../common/api/meta';\nimport { type Mutable, change } from '../common/proxy/reactive';\nimport { isEntity, isSnapshot } from '../Entity/guard';\nimport { getDictionary } from './dictionary';\n\n/**\n * Get the value of an annotation from an entity instance or snapshot.\n *\n * The value is read-only (schema types are readonly by default). To mutate it, use {@link update}\n * (which reads it as mutable inside a change transaction); the reactive proxy rejects mutation of the\n * live value outside an `Obj.update`. Snapshots return a decoded detached copy.\n */\nexport const get = <T>(\n target: Entity.Unknown | Entity.Snapshot,\n annotation: Annotation.Annotation<T>,\n): Option.Option<T> => {\n if (isSnapshot(target)) {\n return getDictionary(getMetaChecked(target).annotations, annotation);\n }\n if (isEntity(target)) {\n const annotations = getMetaChecked(target).annotations;\n // The dictionary slot is typed `unknown`; at runtime it holds the annotation's live value\n // (the proxy codecs nested refs in both directions), so the read coerces to the declared type.\n return annotation.key in annotations ? Option.some(annotations[annotation.key] as T) : Option.none();\n }\n throw new TypeError('Target is not an annotation target.');\n};\n\n/**\n * Set the value of an annotation on an entity instance.\n * Must be called with a mutable entity — i.e. inside an `Obj.update` callback.\n *\n * The value is assigned directly to the reactive meta dictionary; the proxy encodes nested Refs and\n * links their unsaved targets on write (matching ordinary property assignment), so no manual\n * encode/persist step is needed.\n */\nexport const set = <T>(target: Mutable<Entity.Unknown>, annotation: Annotation.Annotation<T>, value: T): void => {\n if (isEntity(target)) {\n // The dictionary slot is untyped, so the proxy can't validate against the annotation schema;\n // validate here (without encoding — the proxy encodes nested refs and links targets on assignment).\n Schema.validateSync(annotation.schema)(value);\n getMetaChecked(target).annotations[annotation.key] = value;\n } else {\n throw new TypeError('Target is not an annotation target.');\n }\n};\n\n/**\n * Mutate an existing annotation value in place via a callback, wrapping the mutation in a change\n * transaction (like `Obj.update`). Use when only an annotation needs to change. No-op when absent.\n */\nexport const update = <T>(\n target: Entity.Unknown,\n annotation: Annotation.Annotation<T>,\n mutator: (value: Mutable<T>) => void,\n): void => {\n change(target, (mutable) => {\n const current = get(mutable, annotation);\n if (Option.isSome(current)) {\n // `get` returns the value read-only; inside this change transaction the live value is mutable.\n const value = current.value as Mutable<T>;\n mutator(value);\n // Validate against the annotation's own schema — the dictionary slot is untyped, so the proxy\n // can't. Schema validation checks ref structure only (not targets), so it is cycle-safe.\n Schema.validateSync(annotation.schema)(value);\n }\n });\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Define a non-enumerable property on an object.\n */\nexport const defineHiddenProperty = (object: any, key: string | symbol, value: any) => {\n Object.defineProperty(object, key, {\n enumerable: false,\n configurable: true,\n value,\n });\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\nimport { EID } from '@dxos/keys';\nimport { deepMapValues, encodeUint8ArrayToJson } from '@dxos/util';\n\nimport { Ref } from '../../Ref';\nimport {\n ATTR_RELATION_SOURCE,\n ATTR_RELATION_TARGET,\n ATTR_SELF_URI,\n ATTR_TYPE,\n RelationSourceDXNId,\n RelationTargetDXNId,\n SelfURIId,\n TypeId,\n} from '../types';\nimport { ATTR_META, type EntityMeta } from '../types/meta';\nimport { MetaId } from '../types/model-symbols';\n\n/**\n * Attaches a toJSON method to the object for typed serialization.\n */\nexport const attachTypedJsonSerializer = (obj: any) => {\n const descriptor = Object.getOwnPropertyDescriptor(obj, 'toJSON');\n if (descriptor) {\n return;\n }\n\n Object.defineProperty(obj, 'toJSON', {\n value: typedJsonSerializer,\n writable: false,\n enumerable: false,\n // Setting `configurable` to false breaks proxy invariants, should be fixable.\n configurable: true,\n });\n};\n\n// NOTE: KEEP as function.\n// Exported for use in objectToJSON.\nexport const typedJsonSerializer = function (this: any) {\n const { id, ...rest } = this;\n const result: any = {\n id,\n };\n\n if (this[TypeId]) {\n result[ATTR_TYPE] = this[TypeId];\n }\n\n if (this[MetaId]) {\n result[ATTR_META] = serializeMeta(this[MetaId]);\n }\n\n if (this[SelfURIId]) {\n result[ATTR_SELF_URI] = this[SelfURIId];\n }\n\n if (this[RelationSourceDXNId]) {\n const sourceDXN = this[RelationSourceDXNId];\n invariant(EID.isEID(sourceDXN));\n result[ATTR_RELATION_SOURCE] = sourceDXN;\n }\n if (this[RelationTargetDXNId]) {\n const targetDXN = this[RelationTargetDXNId];\n invariant(EID.isEID(targetDXN));\n result[ATTR_RELATION_TARGET] = targetDXN;\n }\n\n Object.assign(result, serializeData(rest));\n return result;\n};\n\nconst serializeData = (data: unknown) => {\n return deepMapValues(data, (value, recurse) => {\n if (Ref.isRef(value)) {\n // TODO(dmaretskyi): Should this be configurable?\n return value.noInline().encode();\n }\n if (value instanceof Uint8Array) {\n return encodeUint8ArrayToJson(value);\n }\n\n return recurse(value);\n });\n};\n\nconst serializeMeta = (meta: EntityMeta) => {\n // Omit empty `tags`/`annotations` to keep serialized output minimal; `objectFromJSON` backfills\n // the required defaults on read.\n const { tags, annotations, ...rest } = meta;\n const compact = {\n ...rest,\n ...(tags != null && tags.length > 0 ? { tags } : {}),\n ...(annotations != null && Object.keys(annotations).length > 0 ? { annotations } : {}),\n };\n // Use `serializeData` so `meta.tags` `Ref<Tag>` values encode to the on-wire reference form.\n return serializeData(compact);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { EventId } from './symbols';\n\n/**\n * Simple batching mechanism for EventId emissions.\n * When batch depth > 0, events are collected instead of emitted immediately.\n * When batch depth returns to 0, pending events are emitted.\n */\nlet eventBatchDepth = 0;\nconst pendingEventTargets = new Set<object>();\n\n/**\n * Run a callback in a batched context for EventId emissions.\n * Multiple mutations within the batch will only emit one event per target.\n */\nexport const batchEvents = (callback: () => void): void => {\n eventBatchDepth++;\n try {\n callback();\n } finally {\n eventBatchDepth--;\n if (eventBatchDepth === 0) {\n // Emit pending events.\n for (const target of pendingEventTargets) {\n (target as any)[EventId]?.emit();\n }\n pendingEventTargets.clear();\n }\n }\n};\n\n/**\n * Emit an event on a target, respecting batching.\n */\nexport const emitEvent = (target: object): void => {\n if (eventBatchDepth > 0) {\n pendingEventTargets.add(target);\n } else {\n (target as any)[EventId]?.emit();\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { batchEvents } from './event-batch';\nimport { EventId } from './symbols';\n\n/**\n * Generic change context tracking.\n * Only one object can be in a change context at a time (synchronous changes).\n *\n * This module provides a unified change context mechanism used by both:\n * - TypedReactiveHandler (for non-database objects, using target as key)\n * - EchoReactiveHandler (for database objects, using ObjectCore as key)\n */\n\n/**\n * The object currently in a change context.\n * Can be a target object (for typed reactive) or ObjectCore (for database objects).\n */\nlet currentChangeContext: object | null = null;\n\n/**\n * The primary object that has pending notifications, if any.\n * This uses the contextKey (target or ObjectCore).\n */\nlet pendingNotificationKey: object | null = null;\n\n/**\n * Additional objects (owner chain) that need notifications.\n * These are separate from the primary notification because they use EventId directly.\n */\nconst pendingOwnerNotifications = new Set<object>();\n\n/**\n * Enter a change context for the given key.\n * While in a change context, mutations are allowed on the associated object.\n * Nested Obj.update calls are not supported.\n *\n * @param key - The key to enter the change context for (target object or ObjectCore).\n * @returns A cleanup function that exits the change context.\n */\nexport const enterChangeContext = (key: object): (() => void) => {\n currentChangeContext = key;\n return () => {\n currentChangeContext = null;\n };\n};\n\n/**\n * Check if the given key is currently in a change context.\n *\n * @param key - The key to check (target object or ObjectCore).\n * @returns True if the key is in a change context, false otherwise.\n */\nexport const isInChangeContext = (key: object): boolean => {\n return currentChangeContext === key;\n};\n\n/**\n * Queue a notification for the given key to be fired when the change context exits.\n *\n * @param key - The key to queue a notification for.\n */\nexport const queueNotification = (key: object): void => {\n if (currentChangeContext === key) {\n pendingNotificationKey = key;\n }\n};\n\n/**\n * Queue an owner notification. Owner notifications are for objects in the ownership\n * chain that should be notified when a nested object changes.\n * These objects have EventId and emit directly.\n * Skip if the target is already the current change context (to avoid duplicate notifications).\n *\n * @param target - The owner target that has EventId.\n */\nexport const queueOwnerNotification = (target: object): void => {\n // Skip if this is the object already being changed (primary notification handles it).\n if (currentChangeContext !== null && target !== currentChangeContext) {\n pendingOwnerNotifications.add(target);\n }\n};\n\n/**\n * Check if there are any pending notifications for the given key.\n *\n * @param key - The key to check.\n * @returns True if there are pending notifications, false otherwise.\n */\nexport const hasPendingNotifications = (key: object): boolean => {\n return pendingNotificationKey === key;\n};\n\n/**\n * Clear any pending notifications for the given key.\n *\n * @param key - The key to clear notifications for.\n */\nexport const clearPendingNotifications = (key: object): void => {\n if (pendingNotificationKey === key) {\n pendingNotificationKey = null;\n }\n};\n\n/**\n * Execute a callback within a change context.\n * This is the shared implementation used by both TypedReactiveHandler and EchoReactiveHandler.\n *\n * @param contextKey - The key for the change context (target for typed, ObjectCore for db).\n * @param eventTarget - The object that has the EventId for notifications.\n * @param proxy - The proxy object to pass to the callback.\n * @param callback - The callback to execute with mutations allowed.\n */\nexport const executeChange = (\n contextKey: object,\n eventTarget: object,\n proxy: any,\n callback: (proxy: any) => void,\n): void => {\n const exitContext = enterChangeContext(contextKey);\n try {\n batchEvents(() => callback(proxy));\n } finally {\n exitContext();\n // Fire primary notification.\n if (hasPendingNotifications(contextKey)) {\n clearPendingNotifications(contextKey);\n (eventTarget as any)[EventId]?.emit();\n }\n // Fire owner chain notifications.\n for (const ownerTarget of pendingOwnerNotifications) {\n (ownerTarget as any)[EventId]?.emit();\n }\n pendingOwnerNotifications.clear();\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Error thrown when attempting to mutate an object outside of an Obj.update() context.\n */\nexport class MutationOutsideChangeContextError extends Error {\n constructor(operation: string, suggestion: string) {\n super(\n `Cannot ${operation} outside of Obj.update(). Use Obj.update(obj, (mutableObj) => { ${suggestion} }) instead.`,\n );\n this.name = 'MutationOutsideChangeContextError';\n }\n}\n\n/**\n * Create an error for attempting to set a property outside of a change context.\n */\nexport const createPropertySetError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `modify object property \"${String(prop)}\"`,\n `mutableObj.${String(prop)} = value;`,\n );\n};\n\n/**\n * Create an error for attempting to delete a property outside of a change context.\n */\nexport const createPropertyDeleteError = (prop: string | symbol): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(\n `delete object property \"${String(prop)}\"`,\n `delete mutableObj.${String(prop)};`,\n );\n};\n\n/**\n * Create an error for attempting to call an array method outside of a change context.\n */\nexport const createArrayMethodError = (method: string): MutationOutsideChangeContextError => {\n return new MutationOutsideChangeContextError(`call array.${method}()`, `mutableObj.array.${method}(...);`);\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\nimport { KindId } from '../types';\nimport { queueOwnerNotification } from './change-context';\nimport { defineHiddenProperty } from './define-hidden-property';\nimport { getProxyTarget, isProxy, isValidProxyTarget } from './proxy-utils';\nimport { EventId } from './symbols';\n\n/**\n * Symbol to store the owning ECHO object reference on nested JS objects (records).\n * Every nested record is attributed to exactly one ECHO object.\n * This achieves:\n * - No cycles in the object graph (cyclical Refs are still allowed).\n * - No multiple inbound pointers to one record.\n * - Centralized reactivity for entire ECHO object.\n */\nconst EchoOwner = Symbol.for('@dxos/echo/Owner');\n\n/**\n * Get the raw target from a value, unwrapping proxy if needed.\n */\nexport const getRawTarget = (value: any): any => {\n return isProxy(value) ? getProxyTarget(value) : value;\n};\n\n/**\n * Get the ECHO object that owns this nested record.\n *\n * The owner is always the raw target object (not a proxy) of the root ECHO object.\n * For example, if you have `echoObject.nested.deep`, both `nested` and `deep`\n * will have their owner set to the raw target of `echoObject`.\n *\n * @param value - The nested record to check (can be a proxy or raw target).\n * @returns The raw target of the owning root ECHO object, or undefined if not owned.\n */\nexport const getOwner = (value: object | null | undefined): object | undefined => {\n return (value as any)?.[EchoOwner];\n};\n\n/**\n * Set the owner of a meta object to its parent.\n * This allows meta mutations to respect the parent's change context.\n * @internal\n */\nexport const setMetaOwner = (metaTarget: object, parent: object): void => {\n defineHiddenProperty(metaTarget, EchoOwner, parent);\n};\n\n/**\n * Set the ECHO object owner on a value and all its nested records.\n * All nested JS objects point directly to the root ECHO object.\n *\n * @param value - The value to set ownership on (can be a proxy or raw target).\n * @param owner - The raw target of the root ECHO object that will own this value.\n * @param options.visited - Set of already-visited objects to avoid infinite loops.\n * @param options.depth - Current recursion depth (unused, kept for debugging).\n * @param options.allowedPreviousOwner - When reassigning a root ECHO object, its nested structures\n * are allowed to have this as their previous owner without triggering the invariant.\n */\nexport const setOwnerRecursive = (\n value: any,\n owner: object,\n options: {\n visited?: Set<object>;\n depth?: number;\n allowedPreviousOwner?: object;\n } = {},\n): void => {\n const { visited = new Set<object>(), depth = 0, allowedPreviousOwner } = options;\n if (value == null || typeof value !== 'object') {\n return;\n }\n\n const actualValue = getRawTarget(value);\n if (visited.has(actualValue)) {\n return;\n }\n visited.add(actualValue);\n\n // Check that we're not stealing a nested record owned by a different ECHO object.\n // Root ECHO objects (those with EventId) can be reassigned - they maintain their own\n // identity and choosing to embed them in another object is a valid operation.\n // When reassigning a root, its nested records (owned by that root) are also allowed.\n const existingOwner = getOwner(actualValue);\n const isRootEchoObject = EventId in actualValue;\n\n // Track if this is a root being assigned - its nested structures are allowed to transfer.\n let newAllowedPreviousOwner = allowedPreviousOwner;\n if (isRootEchoObject && depth === 0) {\n // This is the top-level root being assigned; allow its nested structures to transfer.\n newAllowedPreviousOwner = actualValue;\n }\n\n if (!isRootEchoObject) {\n const ownershipAllowed =\n existingOwner == null || existingOwner === owner || existingOwner === newAllowedPreviousOwner;\n invariant(\n ownershipAllowed,\n 'Cannot reassign ownership of a nested record to a different ECHO object. Use deep copy first.',\n );\n }\n\n // Set owner directly to the root ECHO object.\n defineHiddenProperty(actualValue, EchoOwner, owner);\n\n // Recursively set owner on nested objects and array elements.\n const recursiveOptions = {\n visited,\n depth: depth + 1,\n allowedPreviousOwner: newAllowedPreviousOwner,\n };\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (isValidProxyTarget(item) || isProxy(item)) {\n setOwnerRecursive(item, owner, recursiveOptions);\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n const nested = actualValue[key];\n if (isValidProxyTarget(nested) || isProxy(nested)) {\n setOwnerRecursive(nested, owner, recursiveOptions);\n }\n }\n }\n }\n};\n\n/**\n * Traverse an object graph, calling the visitor on each object.\n * Handles proxy unwrapping and cycle detection.\n *\n * @param value - The value to traverse (can be a proxy or raw target).\n * @param visitor - Called for each object. Return true to stop traversal (early exit).\n * @returns true if the visitor returns true for any object.\n */\nexport const traverseObjectGraph = (\n value: any,\n visitor: (actualValue: any) => boolean,\n visited = new Set<object>(),\n): boolean => {\n if (value == null || typeof value !== 'object') {\n return false;\n }\n\n const actualValue = getRawTarget(value);\n\n if (visited.has(actualValue)) {\n return false;\n }\n visited.add(actualValue);\n\n if (visitor(actualValue)) {\n return true;\n }\n\n if (Array.isArray(actualValue)) {\n for (const item of actualValue) {\n if (traverseObjectGraph(item, visitor, visited)) {\n return true;\n }\n }\n } else {\n for (const key in actualValue) {\n if (Object.prototype.hasOwnProperty.call(actualValue, key)) {\n if (traverseObjectGraph(actualValue[key], visitor, visited)) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Check if a value would create a cycle when assigned to a target ECHO object.\n * Returns true if the value (or any nested object) IS the target root.\n */\nexport const wouldCreateCycle = (targetRoot: object, value: any): boolean =>\n traverseObjectGraph(value, (v) => v === targetRoot);\n\n/**\n * Check if a value or any of its nested objects has an owner different from the target.\n * Used to determine if deep copy is needed during init.\n */\nexport const hasForeignOwner = (value: any, target: object): boolean =>\n traverseObjectGraph(value, (v) => {\n const owner = getOwner(v);\n if (owner != null && owner !== target) {\n return true;\n }\n // Root ECHO objects (with EventId) have their nested structures owned by them.\n if (EventId in v && v !== target) {\n return true;\n }\n return false;\n });\n\n/**\n * Maximum depth for owner chain traversal.\n * This is a defensive measure against malformed circular ownership.\n * Primary cycle detection is handled by wouldCreateCycle() before assignment.\n */\nconst MAX_OWNER_DEPTH = 100;\n\n/**\n * Get the root ECHO object for a target.\n * Follows the owner chain to find the ultimate root.\n * An object may have EventId (from being created standalone) but if it now\n * has an owner, it's nested and we should use its owner's root instead.\n * @internal\n */\nexport const getEchoRoot = (target: object, depth = 0): object => {\n invariant(depth < MAX_OWNER_DEPTH, 'Owner chain too deep - possible circular ownership');\n\n // Root ECHO objects (those created with Obj.make or Relation.make) have KindId set.\n // They maintain their own change context identity even when nested inside another object.\n // Nested helper objects like EntityMeta don't have KindId and should follow their owner.\n if (KindId in target) {\n return target;\n }\n\n // For non-root objects (nested records, EntityMeta, etc.), follow the owner chain.\n const owner = getOwner(target);\n if (owner) {\n return getEchoRoot(owner, depth + 1);\n }\n\n // No owner means this is an unowned object (e.g., during initialization).\n return target;\n};\n\n/**\n * Notify all owners in the ownership chain.\n * When a nested object changes, its parent should also be notified.\n * This handles the case where a root ECHO object is nested inside another object.\n */\nexport const notifyOwnerChain = (target: object): void => {\n const owner = getOwner(target);\n if (owner) {\n // Queue notification for the owner's root (which has EventId).\n queueOwnerNotification(getEchoRoot(owner));\n // Continue up the chain (owner might also be nested).\n notifyOwnerChain(owner);\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\n/**\n * Reactive object proxy.\n */\nexport interface ReactiveHandler<T extends object> extends ProxyHandler<T> {\n /**\n * Target to Proxy mapping.\n */\n readonly _proxyMap: WeakMap<object, any>;\n\n /**\n * Called when a proxy is created for this target.\n */\n init(target: T): void;\n\n /**\n * Replace the string CRDT value at `path` with `newText`, applying a minimal diff so cursors and\n * concurrent edits are preserved. Implemented by handlers that back string fields; `Text.update`\n * dispatches here. Must run inside a change context (`Obj.update`).\n */\n textUpdate?(target: T, path: readonly (string | number)[], newText: string): void;\n\n /**\n * Splice the string CRDT value at `path` (character indices, mirroring `Array.splice`): remove\n * `deleteCount` characters at `start` and insert `insert`. Returns the removed substring. `Text.splice`\n * dispatches here. Must run inside a change context (`Obj.update`).\n */\n textSplice?(\n target: T,\n path: readonly (string | number)[],\n start: number,\n deleteCount: number,\n insert: string,\n ): string;\n}\n\n/**\n * For debug-dumping the data of the object.\n */\nexport const objectData = Symbol.for('@dxos/live-object/objectData');\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { isInChangeContext } from './change-context';\nimport { createArrayMethodError } from './errors';\nimport { batchEvents } from './event-batch';\nimport { getEchoRoot } from './ownership';\nimport { getProxyTarget, isProxy } from './proxy-utils';\nimport { EventId } from './symbols';\n\n/**\n * Check if array mutation is allowed (inside a change context).\n * Throws a descriptive error if not.\n */\nconst checkArrayMutationAllowed = (arr: any, method: string): void => {\n // Get the raw target - if arr is a proxy, get its underlying target.\n const target = isProxy(arr) ? getProxyTarget(arr) : arr;\n\n // Find the root ECHO object.\n const echoRoot = getEchoRoot(target);\n\n // A root object owns an `EventId` once initialized; before that, mutations are allowed.\n const isInitialized = EventId in echoRoot;\n if (!isInitialized) {\n // Array is still being initialized, allow mutations.\n return;\n }\n\n if (!isInChangeContext(echoRoot)) {\n throw createArrayMethodError(method);\n }\n};\n\n/**\n * Extends the native array to make sure that arrays methods are correctly reactive.\n * Enforces that mutations only happen within Obj.update() context.\n */\nexport class ReactiveArray<T> extends Array<T> {\n static override get [Symbol.species]() {\n return Array;\n }\n\n static {\n /**\n * These methods will trigger proxy traps like `set` and `defineProperty` and emit event notifications.\n * We wrap them in a batch to avoid unnecessary event notifications.\n * Change context is checked before allowing mutations.\n *\n * Note: When called on a proxy, `this` will be the proxy, so array mutations\n * go through the proxy's set trap which handles event emission.\n */\n const BATCHED_METHODS = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const;\n\n for (const method of BATCHED_METHODS) {\n Object.defineProperty(this.prototype, method, {\n enumerable: false,\n value: function (this: ReactiveArray<any>, ...args: any[]) {\n // Check change context before allowing mutation.\n checkArrayMutationAllowed(this, method);\n\n let result!: any;\n batchEvents(() => {\n result = Array.prototype[method].apply(this, args);\n });\n return result;\n },\n });\n }\n }\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { SchemaId } from '../types';\n\n// TODO(burdon): Reconcile with @dxos/effect visit().\n\nexport class SchemaValidator {\n /**\n * Recursively check that schema specifies constructions we can handle.\n * Validates there are no ambiguous discriminated union types.\n */\n public static validateSchema(schema: Schema.Schema.AnyNoContext): void {\n const visitAll = (nodes: SchemaAST.AST[]) => nodes.forEach((node) => this.validateSchema(Schema.make(node)));\n if (SchemaAST.isUnion(schema.ast)) {\n const typeAstList = schema.ast.types.filter((type) => SchemaAST.isTypeLiteral(type)) as SchemaAST.TypeLiteral[];\n // Check we can handle a discriminated union.\n if (typeAstList.length > 1) {\n getTypeDiscriminators(typeAstList);\n }\n visitAll(typeAstList);\n } else if (SchemaAST.isTupleType(schema.ast)) {\n const positionalTypes = schema.ast.elements.map((t) => t.type);\n const allTypes = positionalTypes.concat(schema.ast.rest.map((t) => t.type));\n visitAll(allTypes);\n } else if (SchemaAST.isTypeLiteral(schema.ast)) {\n visitAll(SchemaAST.getPropertySignatures(schema.ast).map((p) => p.type));\n }\n }\n\n public static hasTypeAnnotation(\n rootObjectSchema: Schema.Schema.AnyNoContext,\n property: string,\n annotation: symbol,\n ): boolean {\n try {\n let type = this.getPropertySchema(rootObjectSchema, [property]);\n if (SchemaAST.isTupleType(type.ast)) {\n type = this.getPropertySchema(rootObjectSchema, [property, '0']);\n }\n\n return type.ast.annotations[annotation] != null;\n } catch {\n return false;\n }\n }\n\n public static getPropertySchema(\n rootObjectSchema: Schema.Schema.AnyNoContext,\n propertyPath: KeyPath,\n getProperty: (path: KeyPath) => any = () => null,\n ): Schema.Schema.AnyNoContext {\n let schema: Schema.Schema.AnyNoContext = rootObjectSchema;\n for (let i = 0; i < propertyPath.length; i++) {\n const propertyName = propertyPath[i];\n const tupleAst = unwrapArray(schema.ast);\n if (tupleAst != null) {\n schema = getArrayElementSchema(tupleAst, propertyName);\n } else {\n const propertyType = getPropertyType(schema.ast, propertyName.toString(), (propertyName) =>\n getProperty([...propertyPath.slice(0, i), propertyName]),\n );\n if (propertyType == null) {\n const indexSignatureType = getIndexSignatureValueType(schema.ast);\n if (indexSignatureType != null) {\n schema = Schema.make(indexSignatureType).annotations(indexSignatureType.annotations);\n continue;\n }\n\n throw new TypeError(`Unknown property: ${formatPropertyPath([...propertyPath.slice(0, i), propertyName])}`);\n }\n\n schema = Schema.make(propertyType).annotations(propertyType.annotations);\n }\n }\n\n return schema;\n }\n\n /**\n * Rejects properties not declared on the schema. Types with index signatures allow extra keys.\n */\n public static assertExactProperties(\n schema: Schema.Schema.AnyNoContext,\n value: unknown,\n getProperty: (path: KeyPath) => unknown = () => undefined,\n path: KeyPath = [],\n ): void {\n if (!isPlainRecord(value)) {\n return;\n }\n\n const typeLiteral = resolveTypeLiteral(schema.ast, (propertyName) => getProperty([...path, propertyName]));\n if (typeLiteral == null) {\n return;\n }\n\n const propertySignatures = SchemaAST.getPropertySignatures(typeLiteral);\n const allowedKeys = new Set(propertySignatures.map((property) => String(property.name)));\n const indexSignatureType = typeLiteral.indexSignatures[0]?.type;\n\n for (const key of Object.keys(value)) {\n const propertyPath = [...path, key];\n if (!allowedKeys.has(key)) {\n if (indexSignatureType == null) {\n throw new TypeError(`Unknown property: ${formatPropertyPath(propertyPath)}`);\n }\n\n const indexSchema = Schema.make(indexSignatureType).annotations(indexSignatureType.annotations);\n this.assertExactProperties(indexSchema, value[key], getProperty, propertyPath);\n continue;\n }\n\n const propertySignature = propertySignatures.find((property) => String(property.name) === key);\n invariant(propertySignature, 'Property signature must exist.');\n const propertySchema = Schema.make(propertySignature.type).annotations(propertySignature.type.annotations);\n this.assertExactProperties(propertySchema, value[key], getProperty, propertyPath);\n }\n }\n\n public static getIndexedElementSchema(\n schema: Schema.Schema.AnyNoContext,\n index: number | string,\n ): Schema.Schema.AnyNoContext | null {\n const arrayAst = unwrapArray(schema.ast);\n if (arrayAst != null) {\n return getArrayElementSchema(arrayAst, index);\n }\n\n const unionAst = unwrapAst(\n schema.ast,\n (candidate) => SchemaAST.isUnion(candidate) && candidate.types.some((member) => unwrapArray(member) != null),\n );\n if (unionAst != null && SchemaAST.isUnion(unionAst)) {\n for (const member of unionAst.types) {\n const memberArrayAst = unwrapArray(member);\n if (memberArrayAst != null) {\n return getArrayElementSchema(memberArrayAst, index);\n }\n }\n }\n\n return null;\n }\n\n public static getTargetPropertySchema(target: any, prop: string | symbol): Schema.Schema.AnyNoContext {\n const schema: Schema.Schema.AnyNoContext | undefined = (target as any)[SchemaId];\n invariant(schema, 'target has no schema');\n\n if (Array.isArray(target)) {\n if (prop === 'length') {\n return Schema.Number;\n }\n\n if (typeof prop !== 'symbol') {\n const indexedSchema = this.getIndexedElementSchema(schema, prop);\n if (indexedSchema != null) {\n return indexedSchema;\n }\n }\n\n // Arrays sometimes carry the element struct as their stamped schema.\n if (SchemaAST.isTypeLiteral(schema.ast)) {\n return schema;\n }\n }\n\n if (typeof prop === 'number' || (typeof prop === 'string' && /^\\d+$/.test(prop))) {\n const indexedSchema = this.getIndexedElementSchema(schema, prop);\n if (indexedSchema != null) {\n return indexedSchema;\n }\n }\n\n const arrayAst = unwrapArray(schema.ast);\n if (arrayAst != null) {\n return getArrayElementSchema(arrayAst, prop);\n }\n\n const propertyType = getPropertyType(schema.ast, prop.toString(), (prop) => target[prop]);\n if (propertyType == null) {\n const indexSignatureType = getIndexSignatureValueType(schema.ast);\n if (indexSignatureType != null) {\n return Schema.make(indexSignatureType).annotations(indexSignatureType.annotations);\n }\n\n throw new TypeError(`Unknown property: ${String(prop)}`);\n }\n\n return Schema.make(propertyType).annotations(propertyType.annotations);\n }\n}\n\n/**\n * Tuple AST is used both for:\n * fixed-length tuples ([string, number]) in which case AST will be { elements: [Schema.String, Schema.Number] }\n * variable-length arrays (Array<string | number>) in which case AST will be { rest: [Schema.Union(Schema.String, Schema.Number)] }\n */\nconst getArrayElementSchema = (\n tupleAst: SchemaAST.TupleType,\n property: string | symbol | number,\n): Schema.Schema.AnyNoContext => {\n const elementIndex =\n typeof property === 'number' ? property : typeof property === 'string' ? parseInt(property, 10) : Number.NaN;\n if (Number.isNaN(elementIndex)) {\n invariant(property === 'length', `invalid array property: ${String(property)}`);\n return Schema.Number;\n }\n if (elementIndex < tupleAst.elements.length) {\n const elementType = tupleAst.elements[elementIndex].type;\n return Schema.make(elementType).annotations(elementType.annotations);\n }\n\n const restType = tupleAst.rest;\n return Schema.make(restType[0].type).annotations(restType[0].annotations);\n};\n\nconst flattenUnion = (typeAst: SchemaAST.AST): SchemaAST.AST[] =>\n SchemaAST.isUnion(typeAst) ? typeAst.types.flatMap(flattenUnion) : [typeAst];\n\nconst getProperties = (\n typeAst: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => any,\n): SchemaAST.PropertySignature[] => {\n const astCandidates = flattenUnion(typeAst);\n const typeAstList = astCandidates.filter((type) => SchemaAST.isTypeLiteral(type)) as SchemaAST.TypeLiteral[];\n if (typeAstList.length === 0) {\n return [];\n }\n if (typeAstList.length === 1) {\n return SchemaAST.getPropertySignatures(typeAstList[0]);\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = typeDiscriminators.findIndex((p) => targetPropertyValue === (p.type as SchemaAST.Literal).literal);\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return SchemaAST.getPropertySignatures(typeAstList[typeIndex]);\n};\n\nconst getPropertyType = (\n ast: SchemaAST.AST,\n propertyName: string,\n getTargetPropertyFn: (propertyName: string) => any,\n): SchemaAST.AST | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return ast;\n }\n\n const typeOrDiscriminatedUnion = unwrapAst(ast, (t) => {\n return SchemaAST.isTypeLiteral(t) || (SchemaAST.isUnion(t) && t.types.some((t) => SchemaAST.isTypeLiteral(t)));\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n const targetProperty = getProperties(typeOrDiscriminatedUnion, getTargetPropertyFn).find(\n (p) => p.name === propertyName,\n );\n if (targetProperty != null) {\n return unwrapAst(targetProperty.type);\n }\n\n const indexSignatureType = unwrapAst(ast, SchemaAST.isTypeLiteral);\n if (\n indexSignatureType &&\n SchemaAST.isTypeLiteral(indexSignatureType) &&\n indexSignatureType.indexSignatures.length > 0\n ) {\n return unwrapAst(indexSignatureType.indexSignatures[0].type);\n }\n\n return null;\n};\n\nconst getTypeDiscriminators = (typeAstList: SchemaAST.TypeLiteral[]): SchemaAST.PropertySignature[] => {\n const discriminatorPropCandidates = typeAstList\n .flatMap(SchemaAST.getPropertySignatures)\n .filter((p) => SchemaAST.isLiteral(p.type));\n const propertyName = discriminatorPropCandidates[0].name;\n const isValidDiscriminator = discriminatorPropCandidates.every((p) => p.name === propertyName && !p.isOptional);\n const everyTypeHasDiscriminator = discriminatorPropCandidates.length === typeAstList.length;\n const isDiscriminatedUnion = isValidDiscriminator && everyTypeHasDiscriminator;\n invariant(isDiscriminatedUnion, 'type ambiguity: every type in a union must have a single unique-literal field');\n return discriminatorPropCandidates;\n};\n\n/**\n * Used to check that rootAst is for a type matching the provided predicate.\n * That's not always straightforward because types of optionality and recursive types.\n * const Task = Schema.Struct({\n * ...,\n * previous?: Schema.optional(Schema.suspend(() => Task)),\n * });\n * Here the AST for `previous` field is going to be Union(Suspend(Type), Undefined).\n * SchemaAST.isTypeLiteral(field) will return false, but unwrapAst(field, (ast) => SchemaAST.isTypeLiteral(ast))\n * will return true.\n */\nconst unwrapAst = (rootAst: SchemaAST.AST, predicate?: (ast: SchemaAST.AST) => boolean): SchemaAST.AST | null => {\n let ast: SchemaAST.AST | undefined = rootAst;\n while (ast != null) {\n if (predicate?.(ast)) {\n return ast;\n }\n\n if (SchemaAST.isUnion(ast)) {\n const next: any = ast.types.find((t) => (predicate != null && predicate(t)) || SchemaAST.isSuspend(t));\n if (next != null) {\n ast = next;\n continue;\n }\n }\n\n if (SchemaAST.isSuspend(ast)) {\n ast = ast.f();\n } else {\n return predicate == null ? ast : null;\n }\n }\n\n return null;\n};\n\nconst unwrapArray = (ast: SchemaAST.AST) => unwrapAst(ast, SchemaAST.isTupleType) as SchemaAST.TupleType | null;\n\nconst getIndexSignatureValueType = (ast: SchemaAST.AST): SchemaAST.AST | null => {\n const typeLiteral = unwrapAst(ast, SchemaAST.isTypeLiteral);\n if (typeLiteral == null || !SchemaAST.isTypeLiteral(typeLiteral) || typeLiteral.indexSignatures.length === 0) {\n return null;\n }\n\n return unwrapAst(typeLiteral.indexSignatures[0].type);\n};\n\nconst resolveTypeLiteral = (\n ast: SchemaAST.AST,\n getTargetPropertyFn: (propertyName: string) => unknown,\n): SchemaAST.TypeLiteral | null => {\n const anyOrObject = unwrapAst(\n ast,\n (candidate) =>\n SchemaAST.isAnyKeyword(candidate) ||\n SchemaAST.isUnknownKeyword(candidate) ||\n SchemaAST.isObjectKeyword(candidate),\n );\n if (anyOrObject != null) {\n return null;\n }\n\n const typeOrDiscriminatedUnion = unwrapAst(ast, (type) => {\n return (\n SchemaAST.isTypeLiteral(type) ||\n (SchemaAST.isUnion(type) && type.types.some((member) => SchemaAST.isTypeLiteral(member)))\n );\n });\n if (typeOrDiscriminatedUnion == null) {\n return null;\n }\n\n if (SchemaAST.isTypeLiteral(typeOrDiscriminatedUnion)) {\n return typeOrDiscriminatedUnion;\n }\n\n if (!SchemaAST.isUnion(typeOrDiscriminatedUnion)) {\n return null;\n }\n\n const typeAstList = typeOrDiscriminatedUnion.types.filter((type) =>\n SchemaAST.isTypeLiteral(type),\n ) as SchemaAST.TypeLiteral[];\n if (typeAstList.length === 1) {\n return typeAstList[0];\n }\n\n const typeDiscriminators = getTypeDiscriminators(typeAstList);\n const targetPropertyValue = getTargetPropertyFn(String(typeDiscriminators[0].name));\n const typeIndex = typeDiscriminators.findIndex(\n (property) => targetPropertyValue === (property.type as SchemaAST.Literal).literal,\n );\n invariant(typeIndex !== -1, 'discriminator field not set on target');\n return typeAstList[typeIndex];\n};\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== 'object' || value === null || Array.isArray(value) || value instanceof Uint8Array) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\nconst formatPropertyPath = (path: KeyPath): string => path.map(String).join('.');\n\nexport const checkIdNotPresentOnSchema = (schema: Schema.Schema<any, any, any>) => {\n invariant(SchemaAST.isTypeLiteral(schema.ast));\n const idProperty = SchemaAST.getPropertySignatures(schema.ast).find((prop) => prop.name === 'id');\n if (idProperty != null) {\n throw new Error('\"id\" property name is reserved');\n }\n};\n\n// TODO(burdon): Reconcile with JsonPath.\ntype KeyPath = readonly (string | number)[];\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\nimport { type InspectOptionsStylized } from 'node:util';\n\nimport { Event } from '@dxos/async';\nimport { inspectCustom } from '@dxos/debug';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { getDeep, setDeep } from '@dxos/util';\n\nimport { getSchemaURI } from '../../Annotation/annotations';\nimport { toEffectSchema } from '../../JsonSchema/json-schema';\nimport { ObjectDeletedId, ParentId, SchemaId, StaticTypeSchemaSlot, TypeEntityId, TypeId } from '../types';\nimport { executeChange, isInChangeContext, queueNotification } from './change-context';\nimport { defineHiddenProperty } from './define-hidden-property';\nimport { createPropertyDeleteError } from './errors';\nimport { batchEvents } from './event-batch';\nimport {\n getEchoRoot,\n getOwner,\n getRawTarget,\n hasForeignOwner,\n notifyOwnerChain,\n setOwnerRecursive,\n wouldCreateCycle,\n} from './ownership';\nimport { type ReactiveHandler, objectData } from './proxy-types';\nimport {\n createProxy,\n isProxy,\n isReactiveRecord,\n isValidProxyTarget,\n normalizeSpliceRange,\n symbolIsProxy,\n symbolReactivePrototype,\n} from './proxy-utils';\nimport { ReactiveArray } from './reactive-array';\nimport { SchemaValidator } from './schema-validator';\nimport { ChangeId, EventId } from './symbols';\n\n// Re-export for external consumers.\nexport { getEchoRoot, setMetaOwner } from './ownership';\n\ntype ProxyTarget = {\n /**\n * Typename or type DXN.\n */\n [TypeId]: string;\n\n /**\n * Schema for the root.\n */\n [SchemaId]: Schema.Schema.AnyNoContext;\n [ParentId]?: any;\n\n /**\n * For modifications.\n */\n [EventId]: Event<void>;\n} & ({ [key: keyof any]: any } | any[]);\n\n/**\n * Deep copy a value, handling arrays and nested objects.\n * Preserves ReactiveArray type and hidden properties (SchemaId, TypeId).\n * Does not copy class instances or functions (except ReactiveArray).\n *\n * Note: Cannot use structuredClone because we need to:\n * - Unwrap proxies\n * - Preserve ReactiveArray instances\n * - Copy Symbol-keyed hidden properties (SchemaId, TypeId)\n * - Convert plain arrays to ReactiveArray\n *\n * Performance: O(n) where n is the total number of nested objects/arrays.\n * For large structures, consider using Refs for frequently reassigned subtrees.\n */\nconst deepCopy = <T>(value: T, visited = new Map<object, object>()): T => {\n if (value == null || typeof value !== 'object') {\n return value;\n }\n\n // Handle proxies - get the underlying target.\n const actualValue = getRawTarget(value);\n\n // Check for circular references in the copy.\n if (visited.has(actualValue)) {\n return visited.get(actualValue) as T;\n }\n\n // Handle ReactiveArray specially to preserve reactivity.\n if (actualValue instanceof ReactiveArray) {\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n // Copy hidden properties.\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n }\n\n // Don't copy other class instances (objects with non-Object prototype). A reactive record\n // (its metadata moved onto a behaviour prototype) still counts as a plain data record here.\n const proto = Object.getPrototypeOf(actualValue);\n if (proto !== Array.prototype && proto !== null && !isReactiveRecord(actualValue)) {\n return value; // Return as-is, don't copy class instances.\n }\n\n if (Array.isArray(actualValue)) {\n // Plain arrays become ReactiveArrays.\n const copy = new ReactiveArray<any>();\n visited.set(actualValue, copy);\n for (const item of actualValue) {\n copy.push(deepCopy(item, visited));\n }\n return copy as T;\n }\n\n const copy: Record<string, any> = {};\n visited.set(actualValue, copy);\n for (const key of Object.keys(actualValue)) {\n copy[key] = deepCopy((actualValue as any)[key], visited);\n }\n // Copy hidden properties (SchemaId, TypeId).\n copyHiddenProperties(actualValue, copy);\n return copy as T;\n};\n\n/**\n * Copy hidden properties (SchemaId, TypeId) from source to target.\n */\nconst copyHiddenProperties = (source: any, target: any): void => {\n if (SchemaId in source) {\n defineHiddenProperty(target, SchemaId, source[SchemaId]);\n }\n if (TypeId in source) {\n defineHiddenProperty(target, TypeId, source[TypeId]);\n }\n};\n\n//\n// Object layering for an in-memory typed reactive object (`TypedReactiveHandler`).\n//\n// Unlike the database-backed handler (echo-client/echo-prototypes.ts), here USER DATA lives as\n// real OWN properties on the target — there is no document behind it. Only the per-object metadata\n// is relocated onto a prototype, so swapping handlers doesn't disturb the data shape:\n//\n// proxy ──Proxy(target, ProxyHandlerSlot → TypedReactiveHandler)\n// │ get/set/has/... traps run here\n// ▼\n// target the user's object. OWN enumerable props = user data ({ name, age, ... });\n// │ [[Prototype]] OWN symbol props are removed by `compactMetadataToInstanceState` after init.\n// ▼\n// instanceState `Object.create(TypedObjectPrototype)`. Holds the relocated symbol-keyed\n// │ [[Prototype]] metadata as hidden props: [EventId] (root only), [ObjectDeletedId], [SchemaId],\n// │ [TypeId], [TypeEntityId], cached [StaticTypeSchemaSlot], ... (Arrays are\n// │ exempt — they keep their ReactiveArray chain and are never compacted.)\n// ▼\n// TypedObjectPrototype shared behaviour. Carries [symbolReactivePrototype]=true (so the\n// │ [[Prototype]] \"plain object\" gates still treat the record as data) plus the system\n// │ accessors [objectData], [ChangeId], [StaticTypeSchemaSlot]; the get trap\n// │ delegates to these via `isBehaviourAccessor` instead of switching.\n// ▼\n// Object.prototype ──▶ null a `getPrototypeOf` trap reports `Object.prototype` so consumers\n// see a plain object; the real instanceState prototype stays hidden.\n//\n// Root vs nested: a root object owns an `[EventId]`; nested records share their root's reactivity\n// and have none. That presence is the \"is this an initialized root\" signal (it replaced an earlier\n// `[ChangeId] === true` marker).\n//\n// `this` in the accessors below: the get trap calls `Reflect.get(target, prop, receiver)`, so\n// `this` is the PROXY (receiver) on the common path, or the raw target when read directly.\n// `getRawTarget(this)` normalizes to the underlying target — needed here because user data and the\n// metadata chain both hang off the raw target, and `executeChange` keys the change context by it.\n//\n/**\n * Behaviour prototype for typed reactive records. A record's per-object metadata is moved onto an\n * intermediate instance-state object whose prototype is this, so that swapping the handler that\n * backs an object (e.g. an in-memory object becoming database-backed) is a prototype re-point that\n * doesn't perturb the target's own-property shape. Marked as a reactive prototype so the \"plain\n * object\" gates (`isValidProxyTarget` / `deepCopy`) still treat such targets as data records.\n */\nconst TypedObjectPrototype: object = Object.create(Object.prototype);\ndefineHiddenProperty(TypedObjectPrototype, symbolReactivePrototype, true);\n\n// The ECHO system surface is exposed as accessors on the behaviour prototype rather than as\n// branches in the `get` trap. `this` is the proxy receiver (or the raw target when read directly);\n// `getRawTarget` resolves either to the underlying target.\nObject.defineProperties(TypedObjectPrototype, {\n // TODO(burdon): Remove?\n [objectData]: {\n get(this: ProxyTarget) {\n return toJSON(getRawTarget(this));\n },\n },\n [ChangeId]: {\n // A function that runs a mutation inside a controlled change context. Only root objects (which\n // own an `EventId`) expose one; nested records share their root's reactivity and return undefined.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n if (!(EventId in target)) {\n return undefined;\n }\n return (callback: (obj: any) => void) => executeChange(target, target, this, callback);\n },\n },\n [StaticTypeSchemaSlot]: {\n // Lazily rebuild the source Effect Schema from `jsonSchema` and cache it as an own (hidden)\n // property so subsequent reads short-circuit this accessor; the set-trap deletes the cache when\n // `jsonSchema` is mutated.\n get(this: ProxyTarget) {\n const target = getRawTarget(this);\n const jsonSchema = (target as any).jsonSchema;\n if (jsonSchema == null) {\n return undefined;\n }\n const rebuilt = toEffectSchema(jsonSchema);\n defineHiddenProperty(target, StaticTypeSchemaSlot, rebuilt);\n return rebuilt;\n },\n },\n});\n\n/** True if `prop` resolves to an accessor on the behaviour-prototype chain (not an own property). */\nconst isBehaviourAccessor = (target: object, prop: symbol): boolean => {\n let proto = Object.getPrototypeOf(target);\n while (proto != null && proto !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, prop);\n if (descriptor != null) {\n return descriptor.get != null;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n};\n\n/**\n * Enforce that user-data mutations only happen inside `Obj.update()`. A root object owns an\n * `EventId` once initialized; before that (and for non-root records or symbol-keyed system\n * properties) mutations pass through. Returns whether the root is initialized so callers can gate\n * change notifications.\n */\nconst assertMutableWithinChange = (echoRoot: object, prop: string | symbol): boolean => {\n const isInitialized = EventId in echoRoot;\n if (isInitialized && typeof prop !== 'symbol' && !isInChangeContext(echoRoot)) {\n throw new Error(\n `Cannot modify object property \"${String(prop)}\" outside of Obj.update(). ` +\n 'Use Obj.update(obj, (mutableObj) => { mutableObj.property = value; }) instead.',\n );\n }\n return isInitialized;\n};\n\n/**\n * Move a record's per-object metadata (symbol-keyed hidden properties) onto a fresh instance-state\n * object inserted between the target and {@link TypedObjectPrototype}. The target keeps only its\n * user data as own properties. Arrays are exempt — they keep their own (ReactiveArray) prototype chain.\n */\nconst compactMetadataToInstanceState = (target: ProxyTarget): void => {\n if (Array.isArray(target) || Object.getPrototypeOf(target) !== Object.prototype) {\n return;\n }\n const state = Object.create(TypedObjectPrototype);\n for (const symbol of Object.getOwnPropertySymbols(target)) {\n Object.defineProperty(state, symbol, Object.getOwnPropertyDescriptor(target, symbol)!);\n // Dynamic delete over arbitrary symbol keys: `ProxyTarget` declares these as required, so the\n // statically-typed view cannot express deleting them; the symbol set is only known at runtime.\n delete (target as any)[symbol];\n }\n Object.setPrototypeOf(target, state);\n};\n\n/**\n * Typed in-memory reactive store (with Schema).\n * Reactivity is based on Event subscriptions, not signals.\n */\nexport class TypedReactiveHandler implements ReactiveHandler<ProxyTarget> {\n public static readonly instance: ReactiveHandler<any> = new TypedReactiveHandler();\n\n readonly _proxyMap = new WeakMap<object, any>();\n private _inSet = false;\n\n private constructor() {}\n\n init(target: ProxyTarget): void {\n assertArgument(typeof target === 'object' && target !== null, 'target');\n invariant(SchemaId in target, 'Schema is not defined for the target');\n\n // Only set EventId on root objects (those without an owner).\n // Nested objects share their root's EventId for centralized reactivity.\n const hasOwner = !!getOwner(target);\n if (!(EventId in target) && !hasOwner) {\n defineHiddenProperty(target, EventId, new Event());\n }\n\n defineHiddenProperty(target, ObjectDeletedId, false);\n\n // Only set owners if this is a root object (no existing owner).\n // Nested objects already have owners set by their root's initialization.\n // If we re-set owners here for nested objects, we'd incorrectly point\n // array elements to the array instead of the true root ECHO object.\n if (!hasOwner) {\n // Set owner on all nested objects to this root ECHO object.\n // All nested records point directly to this root for centralized reactivity.\n for (const key in target) {\n if ((target as any)[symbolIsProxy]) {\n continue;\n }\n let value = (target as any)[key];\n if (isValidProxyTarget(value) || isProxy(value)) {\n // Deep copy values that have foreign owners (owned by a different object,\n // or are root ECHO objects whose nested structures would be owned by them).\n // This recursively checks all nested objects.\n if (hasForeignOwner(value, target)) {\n value = deepCopy(value);\n (target as any)[key] = value;\n }\n setOwnerRecursive(value, target);\n }\n }\n }\n\n // Maybe have been set by `create`.\n Object.defineProperty(target, inspectCustom, {\n enumerable: false,\n configurable: true,\n value: this._inspect.bind(target),\n });\n\n // Relocate per-object metadata onto an instance-state prototype, leaving only user data as own\n // properties on the target. Done last so all metadata set above (and by `prepareTypedTarget`) moves.\n compactMetadataToInstanceState(target);\n }\n\n /**\n * Hide the internal instance-state prototype so consumers see a plain object; arrays keep their\n * real (ReactiveArray) prototype.\n */\n getPrototypeOf(target: ProxyTarget): object | null {\n return Array.isArray(target) ? Reflect.getPrototypeOf(target) : Object.prototype;\n }\n\n get(target: ProxyTarget, prop: string | symbol, receiver: any): any {\n // The ECHO system surface (objectData, ChangeId, StaticTypeSchemaSlot, ...) lives as accessors\n // on the behaviour prototype; resolve them via Reflect.get and return as-is — these are not user\n // data and must never be proxy-wrapped.\n if (typeof prop === 'symbol' && isBehaviourAccessor(target, prop)) {\n return Reflect.get(target, prop, receiver);\n }\n\n // The back-reference to the type entity is own metadata — return the raw value so we don't\n // re-wrap an already-reactive `Type.Type` entity in another proxy (which would fail the\n // SchemaId-in-target invariant).\n if (prop === TypeEntityId) {\n return Reflect.get(target, prop, receiver);\n }\n\n // Own getter properties (e.g. the `SchemaId` slot installed by `setSchemaProperties`).\n if (Object.getOwnPropertyDescriptor(target, prop)?.get) {\n return Reflect.get(target, prop, receiver);\n }\n\n const value = Reflect.get(target, prop, receiver);\n if (isValidProxyTarget(value)) {\n return createProxy(value, this);\n }\n\n return value;\n }\n\n set(target: ProxyTarget, prop: string | symbol, value: any, receiver: any): boolean {\n const echoRoot = getEchoRoot(target);\n const isInitialized = assertMutableWithinChange(echoRoot, prop);\n\n let result: boolean = false;\n this._inSet = true;\n try {\n batchEvents(() => {\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, prop, value);\n result = Reflect.set(target, prop, preparedValue, receiver);\n // Invalidate the cached source Effect Schema when `jsonSchema` changes\n // (e.g. `Type.addFields`) so `Type.getSchema` rebuilds from the new shape.\n if (prop === 'jsonSchema') {\n Reflect.deleteProperty(target, StaticTypeSchemaSlot);\n }\n // Queue notification instead of emitting immediately (batched).\n if (isInitialized) {\n queueNotification(echoRoot);\n // Also notify the owner chain so parent objects are updated when nested objects change.\n notifyOwnerChain(target);\n }\n });\n } finally {\n this._inSet = false;\n }\n return result;\n }\n\n ownKeys(target: ProxyTarget): ArrayLike<string | symbol> {\n return Reflect.ownKeys(target);\n }\n\n deleteProperty(target: ProxyTarget, property: string | symbol): boolean {\n const echoRoot = getEchoRoot(target);\n\n // Check readonly enforcement - mutations only allowed within Obj.update().\n // Skip for symbol properties (internal infrastructure, not user data).\n const isInitialized = EventId in echoRoot;\n const isSymbolProp = typeof property === 'symbol';\n if (isInitialized && !isSymbolProp && !isInChangeContext(echoRoot)) {\n throw createPropertyDeleteError(property);\n }\n\n const result = Reflect.deleteProperty(target, property);\n if (isInitialized) {\n queueNotification(echoRoot);\n }\n return result;\n }\n\n defineProperty(target: ProxyTarget, property: string | symbol, attributes: PropertyDescriptor): boolean {\n const echoRoot = getEchoRoot(target);\n const isInitialized = assertMutableWithinChange(echoRoot, property);\n\n const { echoRoot: _, preparedValue } = this._prepareValueForAssignment(target, property, attributes.value);\n const result = Reflect.defineProperty(target, property, {\n ...attributes,\n value: preparedValue,\n });\n if (!this._inSet && isInitialized) {\n // Queue notification instead of emitting immediately (batched).\n queueNotification(echoRoot);\n }\n return result;\n }\n\n textUpdate(target: ProxyTarget, path: readonly (string | number)[], newText: string): void {\n this._applyTextMutation(target, path, () => newText);\n }\n\n textSplice(\n target: ProxyTarget,\n path: readonly (string | number)[],\n start: number,\n deleteCount: number,\n insert: string,\n ): string {\n let removed = '';\n this._applyTextMutation(target, path, (current) => {\n const range = normalizeSpliceRange(current.length, start, deleteCount);\n removed = current.slice(range.start, range.start + range.deleteCount);\n return current.slice(0, range.start) + insert + current.slice(range.start + range.deleteCount);\n });\n return removed;\n }\n\n /**\n * Shared read-modify-write for the in-memory string CRDT path. Mirrors the `set` trap: enforce the\n * change context, then mutate and notify through the same batched notification path so reactivity fires.\n *\n * Writes via `setDeep` on the raw target, intentionally bypassing `_prepareValueForAssignment` /\n * `_validateValue`: a string CRDT delta produces a string, and per-delta schema checks (pattern,\n * maxLength) would reject valid intermediate states during incremental edits. Such constraints are\n * enforced at the initial assignment or as application-level invariants, mirroring the Automerge path.\n */\n private _applyTextMutation(\n target: ProxyTarget,\n path: readonly (string | number)[],\n compute: (current: string) => string,\n ): void {\n const echoRoot = getEchoRoot(target);\n if (!isInChangeContext(echoRoot)) {\n throw new Error(\n `Cannot modify text at \"${path.join('.')}\" outside of Obj.update(). ` +\n 'Use Obj.update(obj, () => { Text.splice(obj, path, ...); }) instead.',\n );\n }\n\n const keyPath = [...path];\n invariant(keyPath.length > 0, 'Text path must be non-empty');\n const current = getDeep(target, keyPath);\n if (typeof current !== 'string') {\n throw new TypeError(`Text mutation target at \"${keyPath.join('.')}\" is not a string.`);\n }\n\n const next = compute(current);\n batchEvents(() => {\n // Write directly on the raw target (not the proxy) and notify through the same batched path\n // the `set` trap uses, so subscribers fire once per `Obj.update`.\n setDeep(target, keyPath, next);\n queueNotification(echoRoot);\n notifyOwnerChain(target);\n });\n }\n\n /**\n * Prepare a value for assignment to a typed object property.\n * Handles cycle detection, copy-on-assign, array conversion, validation, and ownership.\n */\n private _prepareValueForAssignment(\n target: ProxyTarget,\n prop: string | symbol,\n value: any,\n ): { echoRoot: object; preparedValue: any } {\n const echoRoot = getEchoRoot(target);\n\n if (typeof prop === 'symbol') {\n return { echoRoot, preparedValue: value };\n }\n\n // Check for cycles before assignment.\n if (isValidProxyTarget(value) || isProxy(value)) {\n if (wouldCreateCycle(echoRoot, value)) {\n throw new Error('Cannot create cycles in typed object graph. Consider using Ref for circular references.');\n }\n }\n\n // Prevent direct assignment of root ECHO objects (those created with Obj.make/Relation.make).\n // These must be wrapped with Ref.make for proper reference handling.\n // This matches database object behavior for consistency.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const isRootEchoObject = EventId in actualValue;\n if (isRootEchoObject) {\n throw new Error('Object references must be wrapped with `Ref.make`');\n }\n }\n\n // Copy-on-assign: If the value is a nested record owned by a different ECHO object, deep copy it.\n if (isValidProxyTarget(value) || isProxy(value)) {\n const actualValue = getRawTarget(value);\n const existingOwner = getOwner(actualValue);\n if (existingOwner != null && existingOwner !== echoRoot) {\n value = deepCopy(value);\n }\n }\n\n // Convert arrays to reactive arrays.\n if (Array.isArray(value) && !(value instanceof ReactiveArray)) {\n value = ReactiveArray.from(value);\n }\n\n const validatedValue = this._validateValue(target, prop, value);\n\n // Set owner on new value to the root ECHO object.\n if (isValidProxyTarget(validatedValue) || isProxy(validatedValue)) {\n setOwnerRecursive(validatedValue, echoRoot);\n }\n\n return { echoRoot, preparedValue: validatedValue };\n }\n\n private _validateValue(target: any, prop: string | symbol, value: any) {\n if (prop === ParentId) {\n return value;\n }\n const schema = SchemaValidator.getTargetPropertySchema(target, prop);\n const _ = Schema.asserts(schema)(value);\n SchemaValidator.assertExactProperties(schema, value, (path) => getDeep(value, path));\n if (isValidProxyTarget(value)) {\n setSchemaProperties(value, schema);\n }\n\n return value;\n }\n\n private _inspect(\n _: number,\n options: InspectOptionsStylized,\n inspectFn: (value: any, options?: InspectOptionsStylized) => string,\n ): string {\n const inspected = inspectFn(this, {\n ...options,\n showHidden: false,\n customInspect: false,\n });\n\n return `Typed ${inspected}`;\n }\n}\n\n/**\n * @deprecated Use `Obj.toJSON` instead.\n */\n// TODO(burdon): Remove?\nconst toJSON = (target: ProxyTarget): any => {\n return { '@type': 'TypedReactiveObject', ...target };\n};\n\n/**\n * Pointer to a `Type.Type` entity, stamped as the back-reference (`TypeEntityId`)\n * on instances and read by the `SchemaId` getter installed below.\n *\n * Structural shape (not `Type.AnyEntity`) because `internal/common/proxy/`\n * can't import the top-level `Type` module without a cycle. Every kind of\n * `Type.Type` entity satisfies this shape:\n * - Static (`Type.makeObject(dxn)` pipe) — slot set directly on the object.\n * - Persisted (echo-handler-wrapped) — slot exposed via that handler's\n * `get` trap (rebuilds from `data.jsonSchema`).\n * - In-memory pre-persist (`Type.makeObjectFromJsonSchema`) — slot exposed\n * via the `case StaticTypeSchemaSlot:` arm in this file's `get` trap.\n */\nexport type TypeSource = { readonly [StaticTypeSchemaSlot]?: Schema.Schema.AnyNoContext };\n\n/**\n * Recursively set AST on all potential proxy targets.\n */\nconst setSchemaProperties = (obj: any, schema: Schema.Schema.AnyNoContext, typeSource?: TypeSource) => {\n const schemaType = getSchemaURI(schema);\n if (schemaType != null) {\n defineHiddenProperty(obj, TypeId, schemaType);\n }\n\n if (typeSource != null) {\n // Keep a back-reference to the type entity so `Obj.getType` /\n // `Relation.getType` / `Entity.getType` can return it.\n defineHiddenProperty(obj, TypeEntityId, typeSource);\n\n // Install `SchemaId` as a getter that reads through the entity's static\n // schema slot. The three entity shapes (static / persisted / in-memory\n // pre-persist) each populate the slot via their own get-trap path, so\n // `Type.update` / `Type.addFields` mutations propagate into validation\n // for objects created via `Obj.make(typeEntity, ...)` without this file\n // having to rebuild from `jsonSchema` itself.\n Object.defineProperty(obj, SchemaId, {\n get: () => typeSource[StaticTypeSchemaSlot] ?? schema,\n enumerable: false,\n configurable: true,\n });\n } else {\n defineHiddenProperty(obj, SchemaId, schema);\n }\n\n if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n if (isValidProxyTarget(obj[index])) {\n const elementSchema = SchemaValidator.getIndexedElementSchema(schema, index) ?? Schema.Any;\n setSchemaProperties(obj[index], elementSchema);\n }\n }\n return;\n }\n\n for (const key in obj) {\n if (isValidProxyTarget(obj[key])) {\n let elementSchema: Schema.Schema<any>;\n try {\n elementSchema = SchemaValidator.getTargetPropertySchema(obj, key);\n } catch {\n // Property not in schema — treat as untyped so the proxy can still wrap it.\n elementSchema = Schema.Any;\n }\n setSchemaProperties(obj[key], elementSchema);\n }\n }\n};\n\n// Accepts any encoded type: the typed handler operates on the decoded representation, so schemas\n// whose encoded form differs (e.g. refs encode as `{ '/': uri }`) are valid here.\nexport const prepareTypedTarget = <T>(target: T, schema: Schema.Schema<T, any>, typeSource?: TypeSource) => {\n // log.info('prepareTypedTarget', { target, schema });\n if (!SchemaAST.isTypeLiteral(schema.ast)) {\n throw new Error('schema has to describe an object type');\n }\n\n SchemaValidator.validateSchema(schema);\n const _ = Schema.asserts(schema)(target);\n SchemaValidator.assertExactProperties(schema, target, (path) => getDeep(target, path));\n makeArraysReactive(target);\n setSchemaProperties(target, schema, typeSource);\n};\n\nconst makeArraysReactive = (target: any) => {\n for (const key in target) {\n if (target[symbolIsProxy]) {\n continue;\n }\n if (Array.isArray(target[key])) {\n target[key] = ReactiveArray.from(target[key]);\n }\n if (typeof target[key] === 'object') {\n makeArraysReactive(target[key]);\n }\n }\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport type * as Schema from 'effect/Schema';\n\nimport { EntityId } from '@dxos/keys';\n\nimport { getTypeAnnotation } from '../../Annotation/annotations';\nimport { type AnyProperties, KindId, ParentId, SchemaKindId, StaticTypeSchemaSlot } from '../types';\nimport { type EntityMeta, EntityMetaSchema } from '../types/meta';\nimport { MetaId } from '../types/model-symbols';\nimport { defineHiddenProperty } from './define-hidden-property';\nimport { attachTypedJsonSerializer } from './json-serializer';\nimport { createProxy, getProxyTarget, isValidProxyTarget } from './proxy-utils';\nimport { TypedReactiveHandler, TypeSource, prepareTypedTarget, setMetaOwner } from './typed-handler';\n\n/**\n *\n */\n// TODO(burdon): Make internal\n// Omits the brand slots — those get stamped on the instance by the entity\n// handler (KindId via setKind, SchemaKindId derived in the proxy `get` trap\n// from kind + jsonSchema.entityKind, StaticTypeSchemaSlot lazily via the\n// proxy), not supplied by the caller.\nexport type MakeObjectProps<T extends AnyProperties> = Omit<T, 'id' | KindId | SchemaKindId | StaticTypeSchemaSlot>;\n\n/**\n * Creates a reactive object from a plain Javascript object.\n * Requires a TS-effect schema.\n *\n * Callers that have a `Type.Type` entity (not a raw schema) must unwrap it\n * themselves — `Obj.make` / `Relation.make` do this via `Type.getSchema(...)`\n * and pass the entity through as `typeSource` so the instance carries a\n * back-reference for `Obj.getType` and resolves the live source schema\n * uniformly via the entity's `[StaticTypeSchemaSlot]`.\n */\n// TODO(burdon): Make internal\n// TODO(dmaretskyi): Deep mutability.\n// TODO(dmaretskyi): Invert generics (generic over schema) to have better error messages.\n// TODO(dmaretskyi): Could mutate original object making it unusable.\nexport const makeObject = <T extends AnyProperties>(\n schema: Schema.Schema<T, any, never>,\n obj: NoInfer<MakeObjectProps<T>>,\n meta?: Partial<EntityMeta>,\n typeSource?: TypeSource,\n): T => {\n // Use Object.assign to copy symbol properties (like ParentId) that spread operator doesn't copy.\n return createReactiveObject<T>(Object.assign({}, obj) as T, meta, schema as Schema.Schema<T, any>, typeSource);\n};\n\nconst createReactiveObject = <T extends AnyProperties>(\n obj: T,\n meta?: Partial<EntityMeta>,\n schema?: Schema.Schema<T>,\n typeSource?: TypeSource,\n): T => {\n if (!isValidProxyTarget(obj)) {\n throw new Error('Value cannot be made into a reactive object.');\n }\n\n if (!schema) {\n throw new Error('Schema is required for reactive objects. Use Atom for untyped reactive state.');\n }\n\n // Extract parent from props (can be set via [Obj.Parent]).\n const parent = (obj as any)[ParentId];\n if (parent !== undefined) {\n delete (obj as any)[ParentId];\n }\n\n const annotation = getTypeAnnotation(schema);\n if (annotation) {\n setIdOnTarget(obj);\n defineHiddenProperty(obj, KindId, annotation.kind);\n }\n initMeta(obj, meta);\n if (parent !== undefined) {\n defineHiddenProperty(obj, ParentId, parent);\n }\n prepareTypedTarget(obj, schema, typeSource);\n attachTypedJsonSerializer(obj);\n const proxy = createProxy<T>(obj, TypedReactiveHandler.instance);\n\n // Set meta's owner to the main object so meta mutations respect the parent's change context.\n // For non-database objects using TypedReactiveHandler, this links the meta to the main object's\n // change context. For database objects, meta is handled by EchoReactiveHandler.getMeta().\n const metaProxy = (obj as any)[MetaId];\n if (metaProxy) {\n const metaTarget = getProxyTarget(metaProxy);\n if (metaTarget) {\n setMetaOwner(metaTarget, obj);\n }\n }\n\n return proxy;\n};\n\n/**\n * Set ID on ECHO object targets during creation.\n * Used for objects with schema and the ones explicitly marked as Expando.\n */\nconst setIdOnTarget = (target: any) => {\n // invariant(!('id' in target), 'Object already has an `id` field, which is reserved.');\n if ('id' in target && target.id !== undefined && target.id !== null) {\n if (!EntityId.isValid(target.id)) {\n throw new Error('Invalid object id format.');\n }\n } else {\n target.id = EntityId.random();\n }\n};\n\n/**\n * Set metadata on object.\n */\n// TODO(dmaretskyi): Move to echo-schema.\nconst initMeta = <T>(obj: T, meta?: Partial<EntityMeta>) => {\n // Backfill required fields so callers may pass a partial meta, or one whose `keys`/`tags`/\n // `annotations` are explicitly `undefined` (coalesce, don't let a spread reintroduce undefined).\n const fullMeta: EntityMeta = {\n ...meta,\n keys: meta?.keys ?? [],\n tags: meta?.tags ?? [],\n annotations: meta?.annotations ?? {},\n };\n prepareTypedTarget(fullMeta, EntityMetaSchema);\n defineHiddenProperty(obj, MetaId, createProxy(fullMeta, TypedReactiveHandler.instance as any));\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\nimport type * as Types from 'effect/Types';\n\nimport { DXN, EntityId } from '@dxos/keys';\nimport { type ToMutable } from '@dxos/util';\n\nimport { type TypeAnnotation, TypeAnnotationId } from '../Annotation/annotations';\nimport { makeTypeJsonSchemaAnnotation } from '../Annotation/util';\nimport { defineHiddenProperty } from '../common/proxy/define-hidden-property';\nimport { makeObject } from '../common/proxy/make-object';\nimport { getProxyTarget } from '../common/proxy/proxy-utils';\nimport {\n type AnyEntity,\n EntityKind,\n InstancePhantomId,\n KindId,\n SchemaKindId,\n StaticTypeSchemaSlot,\n} from '../common/types';\nimport { type EntityMeta } from '../common/types/meta';\nimport { JsonSchemaType } from '../JsonSchema/json-schema-type';\n\n// TODO(burdon): Define Schema type for `typename` and use consistently for all DXN-like properties.\n\n// type RequiredKeys<T> = { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T];\nexport type EchoTypeSchemaProps<T, ExtraFields = {}> = Types.Simplify<AnyEntity & ToMutable<T> & ExtraFields>;\n\n/**\n * Options accepted by every `Type.makeObject` / `Type.makeRelation` / type-kind\n * factory. Defaults are derived from `(typename, version)` so callers normally\n * pass nothing.\n */\nexport type EchoTypeOptions = {\n /**\n * Override the entity id stamped on the in-memory `Type.Type` value.\n *\n * Defaults to `EntityId.deterministic(typename, version)` — stable across processes\n * and workerd-safe (no `crypto.getRandomValues()` at module-evaluation time).\n * Pass an explicit id (typically `EntityId.random()`) to opt out of the\n * deterministic default.\n */\n id?: EntityId;\n};\n\n/**\n * In-memory `Type.Type` entity shape produced by `Type.makeObject(dxn)` /\n * `Type.makeRelation({...})`. A live reactive `TypeSchema` instance —\n * identical to a persisted `Type.Type` except for database attachment.\n *\n * NOT a `Schema.Schema`. The underlying Effect Schema is cached on the hidden\n * `StaticTypeSchemaSlot` slot — retrieve it via `Type.getSchema(...)`.\n */\n// TODO(burdon): Rename EchoEntitySchema.\nexport interface EchoTypeSchema<\n Self extends Schema.Schema.Any,\n ExtraFields = {},\n K extends EntityKind = EntityKind,\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n> {\n /**\n * Entity-kind brand. Type entities are their own kind (`Type`) regardless of\n * the kind of instance they describe — `[SchemaKindId]` carries the latter.\n * This lets predicates like `Obj.isObject` / `Relation.isRelation` cleanly\n * reject type entities without also having to inspect `[SchemaKindId]`.\n */\n readonly [KindId]: EntityKind.Type;\n\n /** Schema-kind brand indicating what kind of instance this type describes. */\n readonly [SchemaKindId]: K;\n\n /**\n * Entity id. Always present — stamped at construction — but NOT the type's\n * identity while in-memory: an unattached type resolves its URI to the typename\n * DXN, switching to `echo:/<id>` only once attached to a database (see\n * `getTypeURIFromSpecifier`, which discriminates by database attachment).\n */\n readonly id: EntityId;\n\n /** Source Effect Schema (kept on a hidden slot for `Type.getSchema`). */\n readonly [StaticTypeSchemaSlot]: Schema.Schema.AnyNoContext;\n\n // NOTE: `typename` / `version` are intentionally NOT fields. They live in\n // `EntityMeta` (`key` / `version`); read via `Type.getTypename(self)` /\n // `Type.getVersion(self)`.\n readonly jsonSchema: JsonSchemaType;\n\n /** Struct fields for introspection. */\n readonly fields: Fields;\n\n /** Phantom — instance type produced by `Obj.make(self, ...)`. */\n readonly _instance?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields>;\n\n /**\n * Phantom slot mirroring `Type<A>` so internal helpers (`makeObject`,\n * `createObject`, `Ref.make`) infer the instance type uniformly whether\n * the caller passes an `EchoTypeSchema` or a top-level `Type.Type` entity.\n *\n * Includes the instance-kind brand (`[KindId]`) so the phantom is assignable\n * to the matching public-side interface in `Type.ts` (`Type.Obj` /\n * `Type.Relation` / `Type.Type`). Each kind projects identity: instances of\n * an object-kind schema are object-kind entities, type-kind schemas produce\n * type-kind (persisted Type.Type) entities — the latter additionally carry\n * the `[SchemaKindId]` / `[StaticTypeSchemaSlot]` brands the echo-handler\n * proxy exposes on persisted Type entities.\n */\n readonly [InstancePhantomId]?: EchoTypeSchemaProps<Schema.Schema.Type<Self>, ExtraFields> & {\n readonly [KindId]: K;\n } & (K extends EntityKind.Type\n ? {\n readonly [SchemaKindId]: EntityKind.Type;\n readonly [StaticTypeSchemaSlot]: Schema.Schema.AnyNoContext;\n }\n : {});\n}\n\n// type MakeProps =\n// | boolean\n// | {\n// readonly disableValidation?: boolean;\n// };\n\n// NOTE: Utils copied from Effect `Schema.ts`.\n// const _ownKeys = (o: object): Array<PropertyKey> =>\n// (Object.keys(o) as Array<PropertyKey>).concat(Object.getOwnPropertySymbols(o));\n\n// const _lazilyMergeDefaults = (\n// fields: Schema.Struct.Fields,\n// out: Record<PropertyKey, unknown>,\n// ): { [x: string | symbol]: unknown } => {\n// const ownKeys = _ownKeys(fields);\n// for (const key of ownKeys) {\n// const field = fields[key];\n// if (out[key] === undefined && Schema.isPropertySignature(field)) {\n// const ast = field.ast;\n// const defaultValue = ast._tag === 'PropertySignatureDeclaration' ? ast.defaultValue : ast.to.defaultValue;\n// if (defaultValue !== undefined) {\n// out[key] = defaultValue();\n// }\n// }\n// }\n// return out;\n// };\n\n// const _getDisableValidationMakeOption = (options: MakeProps | undefined): boolean =>\n// Predicate.isBoolean(options) ? options : options?.disableValidation ?? false;\n\n/**\n * Identity (typename + version) of the type meta-schema — the `Type.Type` that\n * every ECHO type entity is itself an instance of. Shared by the materialisation\n * vehicle ({@link persistentEntitySchema}) and `TypeSchema` so the two cannot\n * drift on identity.\n */\nexport const TypeMetaSchemaDXN = DXN.make('org.dxos.type.schema', '0.1.0');\n\n/**\n * Effect Schema that every `Type.Type` entity is an instance of: the meta-schema\n * struct `{ name?, jsonSchema, id }` branded as a type-kind ECHO entity. This is\n * the materialisation vehicle for `makeObject` below — the canonical user-facing\n * entity is `Type/type-schema.ts`'s `TypeSchema`, which carries the same shape\n * plus UI annotations.\n *\n * Kept self-contained (no import of `TypeSchema`) to avoid a bootstrap cycle:\n * `TypeSchema` is itself produced via `makeEchoTypeSchema`, so this builder must\n * not depend on it. `jsonSchema` is declared optional here (only on the\n * materialisation vehicle — the canonical `TypeSchema` keeps it required) so the\n * construction-time `Schema.asserts` does not force the field before it is\n * attached; it is populated immediately after via a lazy accessor (see\n * `makeEchoTypeSchema`).\n */\n// TODO(wittjosiah): Reconcile with `TypeSchema` (`Type/type-schema.ts`).\n// Both describe the same `org.dxos.type.schema` shape.\nconst persistentEntitySchema: Schema.Schema.AnyNoContext = (() => {\n const typename = DXN.getName(TypeMetaSchemaDXN);\n const version = DXN.getVersion(TypeMetaSchemaDXN)!;\n const struct = Schema.Struct({\n name: Schema.optional(Schema.String),\n jsonSchema: JsonSchemaType.pipe(Schema.optional),\n id: EntityId,\n });\n const ast = SchemaAST.annotations(struct.ast, {\n [TypeAnnotationId]: { kind: EntityKind.Type, typename, version } satisfies TypeAnnotation,\n [SchemaAST.JSONSchemaAnnotationId]: makeTypeJsonSchemaAnnotation({ kind: EntityKind.Type, typename, version }),\n });\n return Schema.make(ast);\n})();\n\n/**\n * @internal\n *\n * Build an in-memory `Type.Type` entity (the value returned by `Type.makeObject`\n * / `Type.makeRelation`). The result is a LIVE reactive `TypeSchema`\n * instance — identical in every respect to a persisted `Type.Type` except that\n * it is not yet attached to a database. It is mutable via `Type.update`, can be\n * passed to `db.add(...)` (which keeps the same proxy and swaps the handler),\n * and round-trips through `jsonSchema`.\n *\n * The source Effect Schema describing the user's type is cached on\n * `[StaticTypeSchemaSlot]` so `Type.getSchema(...)` returns it without a\n * jsonSchema round-trip; the cache is invalidated by the proxy set-trap when\n * `jsonSchema` is mutated (see `typed-handler.ts`).\n */\nexport const makeEchoTypeSchema = <\n Self extends Schema.Schema.Any,\n K extends EntityKind = EntityKind,\n // TODO(wittjosiah): Can this be inferred from the schema?\n Fields extends Schema.Struct.Fields = Schema.Struct.Fields,\n>(\n fields: Fields,\n ast: SchemaAST.AST,\n typename: string,\n version: string,\n kind: K,\n computeJsonSchema: () => JsonSchemaType,\n explicitId?: EntityId,\n): EchoTypeSchema<Self, {}, K, Fields> => {\n // Source Effect Schema describing the user's type — cached for `Type.getSchema`.\n const sourceSchema = Schema.make<\n EchoTypeSchemaProps<Schema.Schema.Type<Self>>,\n EchoTypeSchemaProps<Schema.Schema.Encoded<Self>>,\n Schema.Schema.Context<Self>\n >(ast);\n\n // `typename` / `version` route through `EntityMeta` (`key` / `version`) — the\n // canonical registry-provenance pair — not data fields. `keys` is empty for\n // in-memory declarations until persisted.\n const meta: Partial<EntityMeta> = { keys: [], key: typename, version };\n\n // Default to a deterministic id derived from `(typename, version)` so that\n // constructing a `Type.Type` entity never reaches `crypto.getRandomValues()`.\n // Cloudflare workerd forbids RNG calls in global scope, and the ~hundreds of\n // `Type.makeObject(...)` call sites across the monorepo execute at module top.\n // `setIdOnTarget` (see `proxy/make-object.ts`) short-circuits on a pre-supplied\n // valid id, so this also bypasses the `EntityId.random()` path inside `makeObject`.\n // Callers can override via `Type.makeObject(dxn, { id })` when they want a fresh\n // random id (e.g. inside a request handler where workerd does allow RNG).\n const id = explicitId ?? EntityId.deterministic(typename, version);\n\n // Materialise as a live reactive meta-schema instance. `jsonSchema` is attached\n // below as a getter (not passed here as data) for two reasons; see that accessor.\n const entity = makeObject(persistentEntitySchema, { id } as any, meta);\n\n const target = getProxyTarget(entity)!;\n // `jsonSchema` is always available, but computed once on first read rather than at\n // construction: serializing the AST walks `Schema.suspend(...)` thunks, and for a\n // self-referential type (`Schema.suspend(() => Self)`) that thunk hits `Self`'s TDZ\n // while we're still inside its `const` initializer. A getter also lets reads return\n // the raw object instead of a child reactive proxy.\n let memoizedJsonSchema: JsonSchemaType | undefined;\n Object.defineProperty(target, 'jsonSchema', {\n configurable: true,\n enumerable: true,\n get() {\n return (memoizedJsonSchema ??= computeJsonSchema());\n },\n set(value: JsonSchemaType) {\n memoizedJsonSchema = value;\n },\n });\n // Cache the source Effect Schema (read by `Type.getSchema` via the proxy's\n // `[StaticTypeSchemaSlot]` get-trap; invalidated on `jsonSchema` mutation).\n defineHiddenProperty(target, StaticTypeSchemaSlot, sourceSchema);\n // Schema-kind brand: what kind of instance this type describes. There is no\n // database handler to derive it for in-memory entities, so stamp it directly.\n defineHiddenProperty(target, SchemaKindId, kind);\n // Struct fields for introspection. A getter (not a data property) so reads return\n // the raw fields object rather than a child reactive proxy.\n Object.defineProperty(target, 'fields', { configurable: true, enumerable: false, get: () => fields });\n\n return entity as unknown as EchoTypeSchema<Self, {}, K, Fields>;\n};\n\nexport { isEntity } from './guard';\n", "//\n// Copyright 2026 DXOS.org\n//\n\n/**\n * Snapshot a value to create a new reference for atom change-detection and React dependency tracking.\n * Objects and arrays are shallow-copied (a fresh reference each read, so an in-place mutation is\n * observed); primitives are returned as-is (so they dedupe via `!==`). Shared by the object-property\n * and annotation atom families.\n */\nexport const snapshotForComparison = <V>(value: V): V => {\n if (Array.isArray(value)) {\n return [...value] as V;\n }\n if (value !== null && typeof value === 'object') {\n return { ...value } as V;\n }\n return value;\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAASA,WAAW;AAUb,IAAMC,aAAaD,IAAIE,KAAK,qBAAqB,OAAA;;;ACVxD,YAAYC,YAAY;AAExB,SAAgCC,kBAAkB;AAClD,SAASC,iBAAiB;AAC1B,SAASC,OAAAA,YAAW;AACpB,SAA0BC,oBAAoB;AAW9C,IAAA,eAAA;AAMA,IAAa,YAAA;AAoBb,IAAO,eAAyBC,eAAOC;;EACrCC,0BAAmBC,QAAAA,KAAAA,QAAAA,UAAAA,GAAAA,KAAAA,WAAAA,UAAAA,CAAAA;CAAAA;AAEnB,IAAA,mBAAA,cAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAqCF,WAAA,gBAAA,aAAA;;AASEC,IAAAA,UAAUC,CAAU,QAAA;AACpB,QAAA,WAAOA,IAAAA,MAAAA;AACP,YAAA,UAAA,yBAAA,EAAA,YAAA,YAAA,GAAA,cAAA,GAAA,IAAA,GAAA,QAAA,GAAA,CAAA,YAAA,yBAAA,EAAA,CAAA;AAEA,SAAA;AACF;IAGiFC,aAAAA,CAAAA,QAAAA,QAAAA;EAAM;EAChF;AAEP;AACO,IAAMC,mBAAAA,CAAAA,GAAiDC,MAAkBC,EAC9EC,WAAAA,EAAaC,UAAQH,EAAGN,OAAMS,EAAAA;;;;ACvGhC,SAASC,g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SAAOA;AACT;",
|
|
6
|
+
"names": ["DXN", "TagTypeDXN", "make", "Schema", "ForeignKey", "invariant", "DXN", "intersection", "Schema", "Struct", "keys", "ForeignKey", "invariant", "metadata", "id", "compareForeignKeys", "a", "b", "intersection", "getMeta", "assertArgument", "invariant", "__dxlog_file", "getMetaChecked", "meta", "entity", "invariant", "keys", "key", "source", "splice", "i", "tags", "existing", "length", "uri", "isEntity", "value", "KindId", "undefined", "isSnapshot", "SnapshotKindId", "Option", "Schema", "get", "target", "annotation", "isSnapshot", "getDictionary", "getMetaChecked", "annotations", "isEntity", "key", "some", "none", "TypeError", "set", "value", "Schema", "validateSync", "schema", "update", "mutator", "change", "mutable", "current", "isSome", "defineHiddenProperty", "object", "key", "value", "Object", "defineProperty", "enumerable", "configurable", "invariant", "EID", "deepMapValues", "encodeUint8ArrayToJson", "__dxlog_file", "descriptor", "Object", "writable", "enumerable", "configurable", "result", "id", "MetaId", "SelfURIId", "RelationSourceDXNId", "invariant", "sourceDXN", "ATTR_RELATION_SOURCE", "RelationTargetDXNId", "targetDXN", "ATTR_RELATION_TARGET", "assign", "serializeData", "value", "noInline", "Uint8Array", "recurse", "rest", "annotations", "eventBatchDepth", "pendingEventTargets", "Set", "batchEvents", "callback", "target", "EventId", "emit", "clear", "emitEvent", "add", "currentChangeContext", "pendingNotificationKey", "pendingOwnerNotifications", "Set", "enterChangeContext", "key", "isInChangeContext", "queueNotification", "queueOwnerNotification", "target", "add", "hasPendingNotifications", "clearPendingNotifications", "executeChange", "contextKey", "eventTarget", "proxy", "callback", "exitContext", "batchEvents", "EventId", "emit", "ownerTarget", "clear", "MutationOutsideChangeContextError", "Error", "operation", "suggestion", "name", "createPropertySetError", "prop", "String", "createPropertyDeleteError", "createArrayMethodError", "method", "invariant", "__dxlog_file", "value", "visited", "newAllowedPreviousOwner", "allowedPreviousOwner", "actualValue", "invariant", "ownershipAllowed", "defineHiddenProperty", "recursiveOptions", "depth", "Array", "isValidProxyTarget", "item", "setOwnerRecursive", "nested", "isProxy", "owner", "isArray", "traverseObjectGraph", "target", "getEchoRoot", "queueOwnerNotification", "notifyOwnerChain", "objectData", "Symbol", "for", "checkArrayMutationAllowed", "arr", "method", "target", "isProxy", "getProxyTarget", "echoRoot", "getEchoRoot", "isInitialized", "EventId", "isInChangeContext", "createArrayMethodError", "ReactiveArray", "Array", "Symbol", "species", "BATCHED_METHODS", "Object", "defineProperty", "prototype", "enumerable", "value", "args", "result", "batchEvents", "apply", "Schema", "SchemaAST", "invariant", "__dxlog_file", "SchemaAST", "isUnion", "schema", "typeAstList", "ast", "filter", "type", "isTypeLiteral", "length", "visitAll", "positionalTypes", "concat", "allTypes", "getPropertySchema", "rootObjectSchema", "property", "propertyPath", "propertyName", "tupleAst", "unwrapArray", "getArrayElementSchema", "propertyType", "getPropertyType", "indexSignatureType", "annotations", "typeLiteral", "Object", "keys", "path", "key", "TypeError", "indexSchema", "Schema", "invariant", "propertySchema", "propertySignature", "assertExactProperties", "getProperty", "arrayAst", "unionAst", "candidate", "member", "types", "memberArrayAst", "getTargetPropertySchema", "Array", "isArray", "target", "prop", "Number", "indexedSchema", "getIndexSignatureValueType", "String", "make", "elementIndex", "elementType", "flattenUnion", "typeAst", "flatMap", "getProperties", "astCandidates", "typeDiscriminators", "getTypeDiscriminators", "typeIndex", "p", "targetPropertyValue", "getPropertySignatures", "getTargetPropertyFn", "typeOrDiscriminatedUnion", "t", "targetProperty", "unwrapAst", "indexSignatures", "discriminatorPropCandidates", "isValidDiscriminator", "everyTypeHasDiscriminator", "isDiscriminatedUnion", "predicate", "next", "resolveTypeLiteral", "isPlainRecord", "value", "proto", "formatPropertyPath", "map", "idProperty", "Schema", "SchemaAST", "Event", "inspectCustom", "assertArgument", "invariant", "getDeep", "setDeep", "__dxlog_file", "value", "visited", "actualValue", "copy", "item", "push", "copyHiddenProperties", "Array", "isArray", "ReactiveArray", "key", "defineHiddenProperty", "target", "SchemaId", "source", "TypeId", "objectData", "ChangeId", "undefined", "callback", "StaticTypeSchemaSlot", "jsonSchema", "rebuilt", "descriptor", "getOwnPropertyDescriptor", "proto", "Object", "getPrototypeOf", "isInitialized", "prop", "isInChangeContext", "defineProperty", "state", "setPrototypeOf", "_proxyMap", "_inSet", "init", "assertArgument", "invariant", "EventId", "ObjectDeletedId", "setOwnerRecursive", "configurable", "_inspect", "receiver", "Reflect", "get", "createProxy", "assertMutableWithinChange", "result", "batchEvents", "notifyOwnerChain", "ownKeys", "deleteProperty", "property", "isSymbolProp", "createPropertyDeleteError", "queueNotification", "echoRoot", "preparedValue", "attributes", "textUpdate", "textSplice", "start", "deleteCount", "insert", "_applyTextMutation", "current", "range", "removed", "slice", "Error", "keyPath", "TypeError", "next", "compute", "isRootEchoObject", "existingOwner", "getOwner", "validatedValue", "_validateValue", "isValidProxyTarget", "isProxy", "schema", "SchemaValidator", "assertExactProperties", "path", "getDeep", "setSchemaProperties", "options", "showHidden", "customInspect", "inspected", "schemaType", "typeSource", "enumerable", "elementSchema", "getIndexedElementSchema", "index", "SchemaAST", "validateSchema", "makeArraysReactive", "symbolIsProxy", "EntityId", "makeObject", "schema", "obj", "meta", "typeSource", "createReactiveObject", "Object", "assign", "isValidProxyTarget", "Error", "parent", "ParentId", "undefined", "annotation", "getTypeAnnotation", "setIdOnTarget", "defineHiddenProperty", "KindId", "kind", "initMeta", "prepareTypedTarget", "attachTypedJsonSerializer", "proxy", "createProxy", "TypedReactiveHandler", "instance", "metaProxy", "MetaId", "metaTarget", "getProxyTarget", "setMetaOwner", "target", "id", "EntityId", "isValid", "random", "fullMeta", "keys", "tags", "annotations", "EntityMetaSchema", "Schema", "SchemaAST", "DXN", "EntityId", "TypeMetaSchemaDXN", "DXN", "make", "persistentEntitySchema", "typename", "getName", "version", "getVersion", "struct", "Struct", "name", "optional", "String", "jsonSchema", "JsonSchemaType", "pipe", "id", "EntityId", "ast", "annotations", "TypeAnnotationId", "kind", "EntityKind", "Type", "JSONSchemaAnnotationId", "makeTypeJsonSchemaAnnotation", "makeEchoTypeSchema", "fields", "computeJsonSchema", "explicitId", "sourceSchema", "meta", "keys", "key", "deterministic", "entity", "makeObject", "target", "getProxyTarget", "memoizedJsonSchema", "Object", "defineProperty", "configurable", "enumerable", "get", "set", "value", "defineHiddenProperty", "StaticTypeSchemaSlot", "SchemaKindId", "snapshotForComparison", "value", "Array", "isArray"]
|
|
7
|
+
}
|
|
@@ -4,20 +4,21 @@ var KindId = "~@dxos/echo/Kind";
|
|
|
4
4
|
var SchemaKindId = "~@dxos/echo/SchemaKind";
|
|
5
5
|
var SnapshotKindId = "~@dxos/echo/SnapshotKind";
|
|
6
6
|
var StaticTypeSchemaSlot = "~@dxos/echo/Type.StaticSchema";
|
|
7
|
+
var isBrandCarrier = (value) => value != null && (typeof value === "object" || typeof value === "function");
|
|
7
8
|
var getStaticTypeSchema = (value) => {
|
|
8
|
-
if (value
|
|
9
|
+
if (!isBrandCarrier(value)) {
|
|
9
10
|
return void 0;
|
|
10
11
|
}
|
|
11
12
|
return value[StaticTypeSchemaSlot];
|
|
12
13
|
};
|
|
13
14
|
var getSchemaKind = (value) => {
|
|
14
|
-
if (value
|
|
15
|
+
if (!isBrandCarrier(value)) {
|
|
15
16
|
return void 0;
|
|
16
17
|
}
|
|
17
18
|
return value[SchemaKindId];
|
|
18
19
|
};
|
|
19
20
|
var getEntityKindBrand = (value) => {
|
|
20
|
-
if (value
|
|
21
|
+
if (!isBrandCarrier(value)) {
|
|
21
22
|
return void 0;
|
|
22
23
|
}
|
|
23
24
|
return value[KindId];
|
|
@@ -91,4 +92,4 @@ export {
|
|
|
91
92
|
unwrapOptional,
|
|
92
93
|
makeTypeJsonSchemaAnnotation
|
|
93
94
|
};
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
+
//# sourceMappingURL=chunk-2ZHECXUR.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/internal/common/types/entity.ts", "../../../src/internal/Annotation/util.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\n// NOTE: String literals are used instead of unique symbols for both KindId and SchemaKindId.\n// Unique symbols cause TS4023 \"cannot be named\" errors when external packages\n// try to export types that reference this key (e.g., `export const Graph = ...`).\n// TypeScript cannot emit declaration files that reference unique symbols from\n// external modules. Using a string literal allows the type to be inlined in\n// declaration files, making the API portable across package boundaries.\n\n/**\n * String key used to identify the kind of an entity instance (object or relation).\n */\nexport const KindId = '~@dxos/echo/Kind' as const;\nexport type KindId = typeof KindId;\n\n/**\n * String key used to identify the kind of a schema (object schema or relation schema).\n * Parallels KindId which identifies instance kinds.\n */\nexport const SchemaKindId = '~@dxos/echo/SchemaKind' as const;\nexport type SchemaKindId = typeof SchemaKindId;\n\n/**\n * String key used to brand snapshot types.\n * Snapshots have SnapshotKindId instead of KindId, making them\n * distinguishable from reactive objects at the type level.\n */\nexport const SnapshotKindId = '~@dxos/echo/SnapshotKind' as const;\nexport type SnapshotKindId = typeof SnapshotKindId;\n\n/**\n * Hidden slot on a static `Type.Type` entity that holds the source Effect\n * Schema. `Type.getSchema(...)` reads this for static types; persisted types\n * rebuild from `jsonSchema` instead. Stored as a string key for declaration\n * portability (see KindId comment above).\n */\nexport const StaticTypeSchemaSlot = '~@dxos/echo/Type.StaticSchema' as const;\nexport type StaticTypeSchemaSlot = typeof StaticTypeSchemaSlot;\n\n/**\n * Whether a value can carry an entity brand/slot. Class-declared types\n * Class-declared types (`Type.makeObject`) are functions whose prototype chain reaches the entity,\n * so brand/slot lookups must accept functions as well as plain objects.\n */\nconst isBrandCarrier = (value: unknown): boolean =>\n value != null && (typeof value === 'object' || typeof value === 'function');\n\n/**\n * Read the hidden `StaticTypeSchemaSlot` off any value that may carry one.\n * Returns `undefined` for raw schemas (no slot) and inputs that cannot carry a brand.\n * Single point-of-cast for the slot lookup.\n */\nexport const getStaticTypeSchema = (value: unknown): Schema.Schema.AnyNoContext | undefined => {\n if (!isBrandCarrier(value)) {\n return undefined;\n }\n return (value as { [StaticTypeSchemaSlot]?: Schema.Schema.AnyNoContext })[StaticTypeSchemaSlot];\n};\n\n/**\n * Read the `[SchemaKindId]` brand off a value. Returns `undefined` for raw\n * schemas (which don't carry the brand on their static type) and inputs that\n * cannot carry a brand. Single point-of-cast for the brand lookup.\n */\nexport const getSchemaKind = (value: unknown): EntityKind | undefined => {\n if (!isBrandCarrier(value)) {\n return undefined;\n }\n return (value as { [SchemaKindId]?: EntityKind })[SchemaKindId];\n};\n\n/**\n * Read the `[KindId]` brand off a value. Returns `undefined` for raw schemas\n * and inputs that cannot carry a brand. Companion to {@link getSchemaKind}.\n */\nexport const getEntityKindBrand = (value: unknown): EntityKind | undefined => {\n if (!isBrandCarrier(value)) {\n return undefined;\n }\n return (value as { [KindId]?: EntityKind })[KindId];\n};\n\n/**\n * Phantom string key on `Type<A>` entities that carries the instance type `A`.\n * Lets internal helpers (`makeObject`, `createObject`, etc.) pattern-match the\n * instance type from an entity input without importing from the top-level\n * `Type` module. Mirrors `Type.InstancePhantomId` (declared in `Type.ts`).\n *\n * Stored as a string key so declarations remain portable across packages\n * (see KindId comment above).\n */\nexport const InstancePhantomId = '~@dxos/echo/Type.Instance' as const;\nexport type InstancePhantomId = typeof InstancePhantomId;\n\n/**\n * Nominal brand carried by the well-known \"any object\" / \"any relation\"\n * schemas (`Obj.Unknown`, `Relation.Unknown`). The brand lets `Ref.Ref`,\n * `Filter.type`, and `Query.type` accept these schemas in addition to\n * `Type.Type` entities, without opening the door to arbitrary raw schemas.\n *\n * Stored as a string key so declarations remain portable across packages\n * (see KindId comment above).\n */\nexport const UnknownTypeSchemaBrandId = '~@dxos/echo/UnknownTypeSchemaBrand' as const;\nexport type UnknownTypeSchemaBrandId = typeof UnknownTypeSchemaBrandId;\n\n/**\n * Schema-side companion to `Type.Type` entities for the \"any object\" /\n * \"any relation\" cases. Branded so `Ref.Ref` / `Filter.type` / `Query.type`\n * can pattern-match on it; arbitrary `Schema.Schema` values do not satisfy\n * this shape.\n */\nexport interface UnknownTypeSchema<A, K extends EntityKind> extends Schema.Schema<A, any, never> {\n readonly [UnknownTypeSchemaBrandId]: K;\n}\n\n/**\n * Kinds of entities stored in ECHO: objects, relations, and types.\n */\nexport enum EntityKind {\n Object = 'object',\n Relation = 'relation',\n Type = 'type',\n}\n\nexport const EntityKindSchema = Schema.Enums(EntityKind);\n\n/**\n * Typename for generic object references (Type.Obj / Ref.Ref(Obj.Unknown)).\n * Used when referencing any object without a specific schema.\n */\nexport const ANY_OBJECT_TYPENAME = 'org.dxos.schema.anyObject';\n\n/**\n * Version for generic object references.\n */\nexport const ANY_OBJECT_VERSION = '0.0.0';\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Option from 'effect/Option';\nimport type * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { assertArgument } from '@dxos/invariant';\nimport { DXN } from '@dxos/keys';\n\nimport { EntityKind } from '../common/types';\n\nexport interface AnnotationHelper<T> {\n /**\n * Get the annotation value from an Effect schema.\n *\n * Only accepts `Schema.Schema.Any` — to read an annotation off a `Type.Type`\n * entity, unwrap it first with `Type.getSchema(entity)`. This keeps the\n * annotation pipeline single-shaped and forces annotations to live on the\n * source schema, not on the post-construction Type entity.\n */\n get: (schema: Schema.Schema.Any) => Option.Option<T>;\n /**\n * Get the annotation value from the AST.\n */\n getFromAst: (ast: SchemaAST.AST) => Option.Option<T>;\n /**\n * Set the annotation on an Effect schema.\n *\n * Only accepts `Schema.Schema.Any` — annotations must be applied to the\n * source schema BEFORE wrapping it with `Type.makeObject` / `Type.makeRelation`.\n * In a pipe, place every `Annotation.X.set(...)` before the `Type.make...` step.\n */\n set: (value: T) => <S extends Schema.Schema.Any>(schema: S) => S;\n}\n\n/**\n * Note: only for system annotations.\n */\n// TODO(dmaretskyi): Rename to createSystemAnnotationHelper.\n// TODO(dmaretskyi): REconcile with Annotation.make.\nexport const createAnnotationHelper = <T>(id: symbol): AnnotationHelper<T> => {\n return {\n get: (schema) => SchemaAST.getAnnotation(schema.ast, id),\n getFromAst: (ast) => SchemaAST.getAnnotation(ast, id),\n set:\n (value) =>\n <S extends Schema.Schema.Any>(schema: S): S =>\n schema.annotations({ [id]: value }) as S,\n };\n};\n\n/**\n * If property is optional returns the nested property, otherwise returns the property.\n */\n// TODO(wittjosiah): Is there a way to do this as a generic?\nexport const unwrapOptional = (property: SchemaAST.PropertySignature) => {\n if (!property.isOptional || !SchemaAST.isUnion(property.type)) {\n return property;\n }\n\n return property.type.types[0];\n};\n\n/**\n * @see JSONSchemaAnnotationId\n * @returns JSON-schema annotation so that the schema can be serialized with correct parameters.\n */\n// TODO(burdon): Required type.\nexport const makeTypeJsonSchemaAnnotation = (options: {\n identifier?: string;\n kind: EntityKind;\n typename: string;\n version: string;\n relationSource?: string;\n relationTarget?: string;\n}) => {\n assertArgument(!!options.relationSource === (options.kind === EntityKind.Relation), 'relationSource');\n assertArgument(!!options.relationTarget === (options.kind === EntityKind.Relation), 'relationTarget');\n\n const obj: Record<string, unknown> = {\n $id: options.identifier ?? DXN.make(options.typename, options.version),\n entityKind: options.kind,\n version: options.version,\n typename: options.typename,\n };\n if (options.kind === EntityKind.Relation) {\n obj.relationSource = { $ref: options.relationSource };\n obj.relationTarget = { $ref: options.relationTarget };\n }\n\n return obj;\n};\n"],
|
|
5
|
+
"mappings": ";AAIA,YAAYA,YAAY;AAYjB,IAAMC,SAAS;AAOf,IAAMC,eAAe;AAQrB,IAAMC,iBAAiB;AASvB,IAAMC,uBAAuB;AAQpC,IAAMC,iBAAiB,CAACC,UACtBA,SAAS,SAAS,OAAOA,UAAU,YAAY,OAAOA,UAAU;AAO3D,IAAMC,sBAAsB,CAACD,UAAAA;AAClC,MAAI,CAACD,eAAeC,KAAAA,GAAQ;AAC1B,WAAOE;EACT;AACA,SAAQF,MAAkEF,oBAAAA;AAC5E;AAOO,IAAMK,gBAAgB,CAACH,UAAAA;AA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,QAAQY;EACpB;AACA,MAAIZ,QAAQG,SAASC,WAAWC,UAAU;AACxCE,QAAIL,iBAAiB;MAAEa,MAAMf,QAAQE;IAAe;AACpDK,QAAID,iBAAiB;MAAES,MAAMf,QAAQM;IAAe;EACtD;AAEA,SAAOC;AACT;",
|
|
6
|
+
"names": ["Schema", "KindId", "SchemaKindId", "SnapshotKindId", "StaticTypeSchemaSlot", "isBrandCarrier", "value", "getStaticTypeSchema", "undefined", "getSchemaKind", "getEntityKindBrand", "InstancePhantomId", "UnknownTypeSchemaBrandId", "EntityKind", "EntityKindSchema", "Enums", "ANY_OBJECT_TYPENAME", "ANY_OBJECT_VERSION", "SchemaAST", "assertArgument", "DXN", "createAnnotationHelper", "id", "get", "schema", "getAnnotation", "ast", "getFromAst", "set", "value", "annotations", "unwrapOptional", "property", "isOptional", "isUnion", "type", "types", "makeTypeJsonSchemaAnnotation", "options", "assertArgument", "relationSource", "kind", "EntityKind", "Relation", "relationTarget", "obj", "$id", "identifier", "DXN", "make", "typename", "version", "entityKind", "$ref"]
|
|
7
|
+
}
|
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Feed,
|
|
3
3
|
getQueueUri
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-XXWK4J53.mjs";
|
|
5
5
|
import {
|
|
6
6
|
everything,
|
|
7
7
|
is,
|
|
8
8
|
props,
|
|
9
9
|
type
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-SCT6FFCR.mjs";
|
|
11
11
|
import {
|
|
12
12
|
getTypename,
|
|
13
13
|
getURI,
|
|
14
14
|
instanceOf
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-HBXT3GSB.mjs";
|
|
16
16
|
import {
|
|
17
17
|
prettyQuery
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-ACFAOTKJ.mjs";
|
|
19
19
|
import {
|
|
20
20
|
getTypeURIFromSpecifier,
|
|
21
21
|
isDatabase
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-3TN2VMI4.mjs";
|
|
23
23
|
import {
|
|
24
24
|
__export
|
|
25
25
|
} from "./chunk-J5LGTIGS.mjs";
|
|
@@ -43,7 +43,7 @@ var QueryClass = class _QueryClass {
|
|
|
43
43
|
this.ast = ast;
|
|
44
44
|
}
|
|
45
45
|
"~Query" = _QueryClass.variance;
|
|
46
|
-
select(filter) {
|
|
46
|
+
"select"(filter) {
|
|
47
47
|
if (is(filter)) {
|
|
48
48
|
return new _QueryClass({
|
|
49
49
|
type: "filter",
|
|
@@ -58,14 +58,14 @@ var QueryClass = class _QueryClass {
|
|
|
58
58
|
});
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
|
-
reference(key) {
|
|
61
|
+
"reference"(key) {
|
|
62
62
|
return new _QueryClass({
|
|
63
63
|
type: "reference-traversal",
|
|
64
64
|
anchor: this.ast,
|
|
65
65
|
property: key
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
|
-
referencedBy(target, key) {
|
|
68
|
+
"referencedBy"(target, key) {
|
|
69
69
|
const uri = target !== void 0 ? getTypeURIFromSpecifier(target) : null;
|
|
70
70
|
return new _QueryClass({
|
|
71
71
|
type: "incoming-references",
|
|
@@ -74,7 +74,7 @@ var QueryClass = class _QueryClass {
|
|
|
74
74
|
typename: uri ?? null
|
|
75
75
|
});
|
|
76
76
|
}
|
|
77
|
-
sourceOf(relation, predicates) {
|
|
77
|
+
"sourceOf"(relation, predicates) {
|
|
78
78
|
return new _QueryClass({
|
|
79
79
|
type: "relation",
|
|
80
80
|
anchor: this.ast,
|
|
@@ -82,7 +82,7 @@ var QueryClass = class _QueryClass {
|
|
|
82
82
|
filter: relation !== void 0 ? type(relation, predicates).ast : void 0
|
|
83
83
|
});
|
|
84
84
|
}
|
|
85
|
-
targetOf(relation, predicates) {
|
|
85
|
+
"targetOf"(relation, predicates) {
|
|
86
86
|
return new _QueryClass({
|
|
87
87
|
type: "relation",
|
|
88
88
|
anchor: this.ast,
|
|
@@ -90,49 +90,49 @@ var QueryClass = class _QueryClass {
|
|
|
90
90
|
filter: relation !== void 0 ? type(relation, predicates).ast : void 0
|
|
91
91
|
});
|
|
92
92
|
}
|
|
93
|
-
source() {
|
|
93
|
+
"source"() {
|
|
94
94
|
return new _QueryClass({
|
|
95
95
|
type: "relation-traversal",
|
|
96
96
|
anchor: this.ast,
|
|
97
97
|
direction: "source"
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
|
-
target() {
|
|
100
|
+
"target"() {
|
|
101
101
|
return new _QueryClass({
|
|
102
102
|
type: "relation-traversal",
|
|
103
103
|
anchor: this.ast,
|
|
104
104
|
direction: "target"
|
|
105
105
|
});
|
|
106
106
|
}
|
|
107
|
-
parent() {
|
|
107
|
+
"parent"() {
|
|
108
108
|
return new _QueryClass({
|
|
109
109
|
type: "hierarchy-traversal",
|
|
110
110
|
anchor: this.ast,
|
|
111
111
|
direction: "to-parent"
|
|
112
112
|
});
|
|
113
113
|
}
|
|
114
|
-
children() {
|
|
114
|
+
"children"() {
|
|
115
115
|
return new _QueryClass({
|
|
116
116
|
type: "hierarchy-traversal",
|
|
117
117
|
anchor: this.ast,
|
|
118
118
|
direction: "to-children"
|
|
119
119
|
});
|
|
120
120
|
}
|
|
121
|
-
orderBy(...order) {
|
|
121
|
+
"orderBy"(...order) {
|
|
122
122
|
return new _QueryClass({
|
|
123
123
|
type: "order",
|
|
124
124
|
query: this.ast,
|
|
125
125
|
order: order.map((o) => o.ast)
|
|
126
126
|
});
|
|
127
127
|
}
|
|
128
|
-
limit(limit) {
|
|
128
|
+
"limit"(limit) {
|
|
129
129
|
return new _QueryClass({
|
|
130
130
|
type: "limit",
|
|
131
131
|
query: this.ast,
|
|
132
132
|
limit
|
|
133
133
|
});
|
|
134
134
|
}
|
|
135
|
-
from(...args) {
|
|
135
|
+
"from"(...args) {
|
|
136
136
|
if (args.length > 1 && args.every(_isRawScope)) {
|
|
137
137
|
return new _QueryClass({
|
|
138
138
|
type: "from",
|
|
@@ -243,14 +243,14 @@ var QueryClass = class _QueryClass {
|
|
|
243
243
|
}
|
|
244
244
|
});
|
|
245
245
|
}
|
|
246
|
-
options(options) {
|
|
246
|
+
"options"(options) {
|
|
247
247
|
return new _QueryClass({
|
|
248
248
|
type: "options",
|
|
249
249
|
query: this.ast,
|
|
250
250
|
options
|
|
251
251
|
});
|
|
252
252
|
}
|
|
253
|
-
debugLabel(label) {
|
|
253
|
+
"debugLabel"(label) {
|
|
254
254
|
if (this.ast.type === "options") {
|
|
255
255
|
return new _QueryClass({
|
|
256
256
|
type: "options",
|
|
@@ -333,4 +333,4 @@ export {
|
|
|
333
333
|
pretty,
|
|
334
334
|
Query_exports
|
|
335
335
|
};
|
|
336
|
-
//# sourceMappingURL=chunk-
|
|
336
|
+
//# sourceMappingURL=chunk-3KTE2Y7Q.mjs.map
|