@dxos/echo 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/lib/Annotation.mjs +2 -2
  2. package/dist/lib/Database.mjs +1 -1
  3. package/dist/lib/Error.mjs +1 -1
  4. package/dist/lib/Feed.mjs +1 -1
  5. package/dist/lib/Format.mjs +2 -2
  6. package/dist/lib/Migration.mjs +1 -1
  7. package/dist/lib/chunk-Annotation.mjs +14 -11
  8. package/dist/lib/chunk-Annotation.mjs.map +1 -1
  9. package/dist/lib/chunk-Blob.mjs +1 -1
  10. package/dist/lib/chunk-Collection.mjs +1 -1
  11. package/dist/lib/chunk-Database.mjs +93 -7
  12. package/dist/lib/chunk-Database.mjs.map +1 -1
  13. package/dist/lib/chunk-Dataset.mjs +1 -1
  14. package/dist/lib/chunk-Entity.mjs +2 -2
  15. package/dist/lib/chunk-Entity.mjs.map +1 -1
  16. package/dist/lib/chunk-Error.mjs +13 -1
  17. package/dist/lib/chunk-Error.mjs.map +1 -1
  18. package/dist/lib/chunk-Feed.mjs +311 -17
  19. package/dist/lib/chunk-Feed.mjs.map +1 -1
  20. package/dist/lib/chunk-Filter.mjs +4 -3
  21. package/dist/lib/chunk-Filter.mjs.map +1 -1
  22. package/dist/lib/chunk-Format.mjs +2 -1
  23. package/dist/lib/chunk-Hypergraph.mjs +1 -1
  24. package/dist/lib/chunk-Hypergraph.mjs.map +1 -1
  25. package/dist/lib/chunk-Migration.mjs +155 -5
  26. package/dist/lib/chunk-Migration.mjs.map +1 -1
  27. package/dist/lib/chunk-Obj.mjs +12 -5
  28. package/dist/lib/chunk-Obj.mjs.map +1 -1
  29. package/dist/lib/chunk-Query.mjs +2 -2
  30. package/dist/lib/chunk-QueryResult.mjs.map +1 -1
  31. package/dist/lib/chunk-Ref2.mjs +2 -2
  32. package/dist/lib/chunk-Registry.mjs +1 -1
  33. package/dist/lib/chunk-Registry.mjs.map +1 -1
  34. package/dist/lib/chunk-Relation.mjs +5 -5
  35. package/dist/lib/chunk-Relation.mjs.map +1 -1
  36. package/dist/lib/chunk-Scope.mjs +16 -2
  37. package/dist/lib/chunk-Scope.mjs.map +1 -1
  38. package/dist/lib/chunk-Tag.mjs +4 -4
  39. package/dist/lib/chunk-Tag.mjs.map +1 -1
  40. package/dist/lib/chunk-Text.mjs +2 -2
  41. package/dist/lib/chunk-Type.mjs +26 -7
  42. package/dist/lib/chunk-Type.mjs.map +1 -1
  43. package/dist/lib/chunk-View.mjs +1 -1
  44. package/dist/lib/chunk-atom-snapshot.mjs +29 -1
  45. package/dist/lib/chunk-atom-snapshot.mjs.map +1 -1
  46. package/dist/lib/chunk-entity-dictionary.mjs +28 -19
  47. package/dist/lib/chunk-entity-dictionary.mjs.map +1 -1
  48. package/dist/lib/chunk-internal.mjs +231 -79
  49. package/dist/lib/chunk-internal.mjs.map +1 -1
  50. package/dist/lib/chunk-json-schema.mjs +1 -1
  51. package/dist/lib/chunk-ref.mjs +38 -34
  52. package/dist/lib/chunk-ref.mjs.map +1 -1
  53. package/dist/lib/chunk-select.mjs +7 -3
  54. package/dist/lib/chunk-select.mjs.map +1 -1
  55. package/dist/lib/index.mjs +2 -2
  56. package/dist/lib/internal.mjs +6 -6
  57. package/dist/lib/testing.mjs +2 -2
  58. package/dist/lib/testing.mjs.map +1 -1
  59. package/dist/types/src/Annotation.d.ts +1 -1
  60. package/dist/types/src/Annotation.d.ts.map +1 -1
  61. package/dist/types/src/Database.d.ts +30 -13
  62. package/dist/types/src/Database.d.ts.map +1 -1
  63. package/dist/types/src/Entity.d.ts +3 -4
  64. package/dist/types/src/Entity.d.ts.map +1 -1
  65. package/dist/types/src/Error.d.ts +36 -0
  66. package/dist/types/src/Error.d.ts.map +1 -1
  67. package/dist/types/src/Feed.d.ts +261 -18
  68. package/dist/types/src/Feed.d.ts.map +1 -1
  69. package/dist/types/src/Filter.d.ts +7 -1
  70. package/dist/types/src/Filter.d.ts.map +1 -1
  71. package/dist/types/src/Hypergraph.d.ts +1 -1
  72. package/dist/types/src/Migration.d.ts +213 -2
  73. package/dist/types/src/Migration.d.ts.map +1 -1
  74. package/dist/types/src/Migration.test.d.ts +2 -0
  75. package/dist/types/src/Migration.test.d.ts.map +1 -0
  76. package/dist/types/src/Obj.d.ts +4 -4
  77. package/dist/types/src/Obj.d.ts.map +1 -1
  78. package/dist/types/src/QueryResult.d.ts +16 -0
  79. package/dist/types/src/QueryResult.d.ts.map +1 -1
  80. package/dist/types/src/Relation.d.ts +3 -4
  81. package/dist/types/src/Relation.d.ts.map +1 -1
  82. package/dist/types/src/Scope.d.ts +32 -1
  83. package/dist/types/src/Scope.d.ts.map +1 -1
  84. package/dist/types/src/Tag.d.ts.map +1 -1
  85. package/dist/types/src/Type.d.ts +27 -2
  86. package/dist/types/src/Type.d.ts.map +1 -1
  87. package/dist/types/src/internal/Annotation/annotations.d.ts +35 -1
  88. package/dist/types/src/internal/Annotation/annotations.d.ts.map +1 -1
  89. package/dist/types/src/internal/Annotation/atoms.d.ts +2 -2
  90. package/dist/types/src/internal/Annotation/atoms.d.ts.map +1 -1
  91. package/dist/types/src/internal/Entity/api.d.ts +11 -0
  92. package/dist/types/src/internal/Entity/api.d.ts.map +1 -1
  93. package/dist/types/src/internal/Entity/model.d.ts +3 -2
  94. package/dist/types/src/internal/Entity/model.d.ts.map +1 -1
  95. package/dist/types/src/internal/Format/string.d.ts +5 -1
  96. package/dist/types/src/internal/Format/string.d.ts.map +1 -1
  97. package/dist/types/src/internal/Obj/atoms.d.ts +1 -1
  98. package/dist/types/src/internal/Obj/atoms.d.ts.map +1 -1
  99. package/dist/types/src/internal/Obj/json-serializer.d.ts.map +1 -1
  100. package/dist/types/src/internal/Query/pretty.d.ts.map +1 -1
  101. package/dist/types/src/internal/Ref/ref.d.ts +5 -1
  102. package/dist/types/src/internal/Ref/ref.d.ts.map +1 -1
  103. package/dist/types/src/internal/Ref/strong-deps.d.ts +3 -1
  104. package/dist/types/src/internal/Ref/strong-deps.d.ts.map +1 -1
  105. package/dist/types/src/internal/common/api/meta.d.ts +4 -5
  106. package/dist/types/src/internal/common/api/meta.d.ts.map +1 -1
  107. package/dist/types/src/internal/common/atom-snapshot.d.ts +10 -0
  108. package/dist/types/src/internal/common/atom-snapshot.d.ts.map +1 -1
  109. package/dist/types/src/internal/common/proxy/change-context.d.ts +4 -0
  110. package/dist/types/src/internal/common/proxy/change-context.d.ts.map +1 -1
  111. package/dist/types/src/internal/common/proxy/ownership.d.ts +5 -0
  112. package/dist/types/src/internal/common/proxy/ownership.d.ts.map +1 -1
  113. package/dist/types/src/internal/common/proxy/proxy-utils.d.ts.map +1 -1
  114. package/dist/types/src/internal/common/proxy/schema-validator.d.ts +17 -2
  115. package/dist/types/src/internal/common/proxy/schema-validator.d.ts.map +1 -1
  116. package/dist/types/src/internal/common/proxy/symbols.d.ts +10 -0
  117. package/dist/types/src/internal/common/proxy/symbols.d.ts.map +1 -1
  118. package/dist/types/src/internal/common/proxy/typed-handler.d.ts +0 -1
  119. package/dist/types/src/internal/common/proxy/typed-handler.d.ts.map +1 -1
  120. package/dist/types/src/internal/common/types/meta.d.ts +8 -4
  121. package/dist/types/src/internal/common/types/meta.d.ts.map +1 -1
  122. package/dist/types/src/internal/common/types/model-symbols.d.ts +6 -0
  123. package/dist/types/src/internal/common/types/model-symbols.d.ts.map +1 -1
  124. package/dist/types/src/internal/index.d.ts.map +1 -1
  125. package/dist/types/tsconfig.tsbuildinfo +1 -1
  126. package/package.json +19 -15
  127. package/src/Annotation.test.ts +34 -0
  128. package/src/Annotation.ts +3 -0
  129. package/src/Database.ts +46 -15
  130. package/src/Entity.ts +3 -4
  131. package/src/Error.ts +9 -0
  132. package/src/Feed.test.ts +160 -0
  133. package/src/Feed.ts +412 -29
  134. package/src/Filter.ts +8 -1
  135. package/src/Hypergraph.ts +1 -1
  136. package/src/Migration.test.ts +137 -0
  137. package/src/Migration.ts +376 -4
  138. package/src/Obj.test.ts +44 -4
  139. package/src/Obj.ts +19 -5
  140. package/src/QueryResult.ts +14 -0
  141. package/src/Relation.ts +3 -4
  142. package/src/Scope.ts +43 -1
  143. package/src/Tag.md +5 -6
  144. package/src/Tag.ts +3 -2
  145. package/src/Type.test.ts +52 -0
  146. package/src/Type.ts +75 -22
  147. package/src/Type.tst.ts +155 -0
  148. package/src/internal/Annotation/annotations.test.ts +19 -0
  149. package/src/internal/Annotation/annotations.ts +67 -1
  150. package/src/internal/Annotation/atoms.ts +10 -9
  151. package/src/internal/Entity/api.ts +20 -1
  152. package/src/internal/Entity/model.ts +3 -0
  153. package/src/internal/Filter/match.ts +2 -2
  154. package/src/internal/Format/string.ts +7 -2
  155. package/src/internal/JsonSchema/json-schema.test.ts +2 -2
  156. package/src/internal/Obj/atoms.ts +9 -5
  157. package/src/internal/Obj/json-serializer.test.ts +34 -7
  158. package/src/internal/Obj/json-serializer.ts +18 -3
  159. package/src/internal/Query/pretty.ts +3 -2
  160. package/src/internal/Ref/ref.test.ts +27 -2
  161. package/src/internal/Ref/ref.ts +18 -2
  162. package/src/internal/Ref/strong-deps.ts +21 -2
  163. package/src/internal/common/api/meta.ts +7 -8
  164. package/src/internal/common/atom-snapshot.ts +61 -0
  165. package/src/internal/common/proxy/change-context.ts +5 -0
  166. package/src/internal/common/proxy/change.test.ts +62 -31
  167. package/src/internal/common/proxy/json-serializer.ts +3 -2
  168. package/src/internal/common/proxy/ownership.ts +14 -1
  169. package/src/internal/common/proxy/proxy-utils.ts +7 -1
  170. package/src/internal/common/proxy/schema-validator.ts +116 -27
  171. package/src/internal/common/proxy/symbols.ts +12 -0
  172. package/src/internal/common/proxy/typed-handler.test.ts +43 -0
  173. package/src/internal/common/proxy/typed-handler.ts +105 -33
  174. package/src/internal/common/types/meta.ts +25 -20
  175. package/src/internal/common/types/model-symbols.ts +7 -0
  176. package/src/internal/index.ts +1 -2
@@ -0,0 +1,137 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import * as Schema from 'effect/Schema';
6
+ import { describe, test } from 'vitest';
7
+
8
+ import { DXN } from '@dxos/keys';
9
+
10
+ import * as Annotation from './Annotation.ts';
11
+ import * as JsonSchema from './JsonSchema.ts';
12
+ import * as Migration from './Migration.ts';
13
+ import * as Type from './Type.ts';
14
+
15
+ const Document = Type.makeObject(DXN.make('com.example.type.document', '0.1.0'))(
16
+ Schema.Struct({
17
+ format: Schema.String.pipe(
18
+ Annotation.ContentVersionAnnotation.set({ fields: ['content', 'title'] }),
19
+ Schema.optional,
20
+ ),
21
+ content: Schema.Record(Schema.String, Schema.Any),
22
+ title: Schema.String.pipe(Schema.optional),
23
+ }),
24
+ );
25
+
26
+ const Plain = Type.makeObject(DXN.make('com.example.type.plain', '0.1.0'))(
27
+ Schema.Struct({ content: Schema.Record(Schema.String, Schema.Any) }),
28
+ );
29
+
30
+ const v1ToV2 = Migration.defineContent({
31
+ type: Document,
32
+ from: 'example.com/doc/1',
33
+ to: 'example.com/doc/2',
34
+ since: '0.1.0',
35
+ transform: ({ content, title }) => ({ content, title: String(title).toUpperCase() }),
36
+ });
37
+
38
+ const v2ToV3 = Migration.defineContent({
39
+ type: Document,
40
+ from: 'example.com/doc/2',
41
+ to: 'example.com/doc/3',
42
+ since: '0.2.0',
43
+ transform: ({ content, title }) => ({ content: { ...Object(content), added: true }, title }),
44
+ });
45
+
46
+ describe('Migration', () => {
47
+ describe('defineContent', () => {
48
+ test('reads the version field and record fields from the annotation', ({ expect }) => {
49
+ expect(Migration.isMigration(v1ToV2)).toBe(true);
50
+ expect(Migration.isContentMigration(v1ToV2)).toBe(true);
51
+ expect(v1ToV2.kind).toBe('content');
52
+ expect(v1ToV2.type).toBe(DXN.make('com.example.type.document', '0.1.0'));
53
+ expect(v1ToV2.versionField).toBe('format');
54
+ expect(v1ToV2.fields).toEqual(['content', 'title']);
55
+ expect(v1ToV2.recordFields).toEqual(['content']);
56
+ });
57
+
58
+ test('rejects a type without a ContentVersionAnnotation', ({ expect }) => {
59
+ expect(() =>
60
+ Migration.defineContent({
61
+ type: Plain,
62
+ from: 'a/1',
63
+ to: 'a/2',
64
+ since: '0.1.0',
65
+ transform: (content) => content,
66
+ }),
67
+ ).toThrow(/ContentVersionAnnotation/);
68
+ });
69
+
70
+ test('rejects a step that does not change the version', ({ expect }) => {
71
+ expect(() =>
72
+ Migration.defineContent({ type: Document, from: 'a/1', to: 'a/1', since: '0.1.0', transform: (c) => c }),
73
+ ).toThrow(/Invalid content versions/);
74
+ });
75
+
76
+ test('the annotation survives JSON schema serialization', ({ expect }) => {
77
+ const jsonSchema = JsonSchema.toJsonSchema(Type.getSchema(Document));
78
+ expect(JSON.stringify(jsonSchema)).toContain('org.dxos.annotation.contentVersion');
79
+ });
80
+ });
81
+
82
+ describe('upgradeContent', () => {
83
+ test('applies the chain in order from any version on it', ({ expect }) => {
84
+ const migrations = [v2ToV3, v1ToV2];
85
+ expect(Migration.upgradeContent(migrations, Document, 'example.com/doc/1', { content: {}, title: 'a' })).toEqual({
86
+ version: 'example.com/doc/3',
87
+ content: { content: { added: true }, title: 'A' },
88
+ });
89
+ expect(Migration.upgradeContent(migrations, Document, 'example.com/doc/2', { content: {}, title: 'a' })).toEqual({
90
+ version: 'example.com/doc/3',
91
+ content: { content: { added: true }, title: 'a' },
92
+ });
93
+ });
94
+
95
+ test('returns content at an unknown or current version unchanged', ({ expect }) => {
96
+ const content = { content: {} };
97
+ for (const version of ['example.com/doc/3', 'other.com/1', undefined]) {
98
+ const result = Migration.upgradeContent([v1ToV2, v2ToV3], Document, version, content);
99
+ expect(result.content).toBe(content);
100
+ expect(result.version).toBe(version);
101
+ }
102
+ });
103
+
104
+ test('ignores steps of other types', ({ expect }) => {
105
+ const content = { content: {} };
106
+ const result = Migration.upgradeContent(
107
+ [v1ToV2],
108
+ DXN.make('com.example.type.other', '0.1.0'),
109
+ 'example.com/doc/1',
110
+ content,
111
+ );
112
+ expect(result.content).toBe(content);
113
+ });
114
+
115
+ test('rejects two steps from the same version', ({ expect }) => {
116
+ const fork = Migration.defineContent({
117
+ type: Document,
118
+ from: 'example.com/doc/1',
119
+ to: 'example.com/doc/9',
120
+ since: '0.1.0',
121
+ transform: (content) => content,
122
+ });
123
+ expect(() => Migration.upgradeContent([v1ToV2, fork], Document, 'example.com/doc/1', {})).toThrow(/Ambiguous/);
124
+ });
125
+
126
+ test('rejects a loop', ({ expect }) => {
127
+ const back = Migration.defineContent({
128
+ type: Document,
129
+ from: 'example.com/doc/2',
130
+ to: 'example.com/doc/1',
131
+ since: '0.1.0',
132
+ transform: (content) => content,
133
+ });
134
+ expect(() => Migration.upgradeContent([v1ToV2, back], Document, 'example.com/doc/1', {})).toThrow(/loop/);
135
+ });
136
+ });
137
+ });
package/src/Migration.ts CHANGED
@@ -4,13 +4,19 @@
4
4
 
5
5
  // @import-as-namespace
6
6
 
7
+ import type * as Effect from 'effect/Effect';
8
+ import * as Option from 'effect/Option';
7
9
  import type * as Schema from 'effect/Schema';
8
10
 
11
+ import * as SchemaAST from '@dxos/effect/SchemaAST';
12
+ import * as SchemaEx from '@dxos/effect/SchemaEx';
9
13
  import { DXN, type URI } from '@dxos/keys';
10
14
 
11
15
  import type * as Database from './Database.ts';
12
16
  import type * as Entity from './Entity.ts';
13
- import { type EntityMeta, MetaId, getSchemaURI } from './internal/index.ts';
17
+ import type * as EchoError from './Error.ts';
18
+ import { ContentVersionAnnotation, type EntityMeta, MetaId, getSchemaURI } from './internal/index.ts';
19
+ import type * as Obj from './Obj.ts';
14
20
  import * as Type from './Type.ts';
15
21
 
16
22
  export const TypeId = '~@dxos/echo/Migration' as const;
@@ -21,11 +27,11 @@ export type TypeId = typeof TypeId;
21
27
  */
22
28
  export interface Migration {
23
29
  readonly [TypeId]: TypeId;
24
- readonly kind: 'object' | 'rename';
30
+ readonly kind: 'object' | 'rename' | 'content' | 'transaction';
25
31
  }
26
32
 
27
33
  /**
28
- * Type guard for values produced by {@link define} / {@link defineRename}.
34
+ * Type guard for values produced by {@link define} / {@link defineRename} / {@link defineContent}.
29
35
  *
30
36
  * @performance O(1) brand check; no allocation.
31
37
  */
@@ -36,7 +42,13 @@ export const isMigration = (value: unknown): value is Migration => {
36
42
  const candidate = value as { [TypeId]?: unknown; kind?: unknown };
37
43
  // `kind` is checked too: a branded value carrying an unknown kind is not a migration any
38
44
  // consumer can dispatch on.
39
- return candidate[TypeId] === TypeId && (candidate.kind === 'object' || candidate.kind === 'rename');
45
+ return (
46
+ candidate[TypeId] === TypeId &&
47
+ (candidate.kind === 'object' ||
48
+ candidate.kind === 'rename' ||
49
+ candidate.kind === 'content' ||
50
+ candidate.kind === 'transaction')
51
+ );
40
52
  };
41
53
 
42
54
  /**
@@ -199,3 +211,363 @@ export const defineRename = <const From extends string, const To extends string>
199
211
  from: DXN.make<string>(options.from),
200
212
  to: DXN.make<string>(options.to),
201
213
  });
214
+
215
+ /**
216
+ * Values of the content fields a {@link ContentVersionAnnotation} names, keyed by field name.
217
+ * A field absent from the object is absent here.
218
+ */
219
+ export type Content = Readonly<Record<string, unknown>>;
220
+
221
+ /**
222
+ * Definition of one step of a content format: upgrades the fields a type's
223
+ * {@link ContentVersionAnnotation} names from content version `from` to `to`.
224
+ */
225
+ export interface ContentMigration extends Migration {
226
+ readonly kind: 'content';
227
+
228
+ /** URI of the object type whose content this step upgrades. */
229
+ readonly type: URI.URI;
230
+
231
+ /** The string field holding the content version. */
232
+ readonly versionField: string;
233
+
234
+ /** The content fields the version describes. */
235
+ readonly fields: readonly string[];
236
+
237
+ /** Content fields declared as records, which the runner writes key by key. */
238
+ readonly recordFields: readonly string[];
239
+
240
+ /** Content version this step reads. */
241
+ readonly from: string;
242
+
243
+ /** Content version this step writes. */
244
+ readonly to: string;
245
+
246
+ /** Release that first ships this step, which decides when it can be deleted. */
247
+ readonly since: string;
248
+
249
+ /** Pure, deterministic upgrade of the content fields. */
250
+ readonly transform: (content: Content) => Content;
251
+ }
252
+
253
+ type DefineContentMigrationOptions<S extends MigrationSchemaInput> = {
254
+ /** Object type whose schema carries a {@link ContentVersionAnnotation}. */
255
+ type: S;
256
+ from: string;
257
+ to: string;
258
+ since: string;
259
+ /**
260
+ * Returns the new values of the content fields. Must be pure and deterministic: peers migrating
261
+ * the same object concurrently must write identical values for their changes to merge.
262
+ */
263
+ transform: (content: Content) => Content;
264
+ };
265
+
266
+ /**
267
+ * Narrows a migration to a {@link ContentMigration}.
268
+ *
269
+ * @performance O(1).
270
+ */
271
+ export const isContentMigration = (migration: Migration): migration is ContentMigration => migration.kind === 'content';
272
+
273
+ type ContentVersionField = { readonly field: string; readonly fields: readonly string[] };
274
+
275
+ /** The field a schema's {@link ContentVersionAnnotation} marks, with the fields it versions. */
276
+ const getContentVersionField = (ast: SchemaAST.AST): ContentVersionField | undefined => {
277
+ for (const property of SchemaAST.getPropertySignatures(ast)) {
278
+ if (typeof property.name !== 'string') {
279
+ continue;
280
+ }
281
+ // Optionality wraps the annotated schema in a union.
282
+ const value = Option.getOrUndefined(
283
+ Option.orElse(ContentVersionAnnotation.getFromAst(property.type), () =>
284
+ ContentVersionAnnotation.getFromAst(SchemaEx.unwrapOptional(property.type)),
285
+ ),
286
+ );
287
+ if (value) {
288
+ return { field: property.name, fields: value.fields };
289
+ }
290
+ }
291
+ return undefined;
292
+ };
293
+
294
+ const isRecordAst = (ast: SchemaAST.AST): boolean =>
295
+ SchemaAST.isObjects(ast) && ast.propertySignatures.length === 0 && ast.indexSignatures.length > 0;
296
+
297
+ /**
298
+ * Define one step of a content format carried by an object type.
299
+ *
300
+ * The type's schema must mark its version field with {@link ContentVersionAnnotation}. Steps chain
301
+ * by version: an object at `from` is upgraded through every step reachable from it.
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * const sceneParams = Migration.defineContent({
306
+ * type: Drawing.Canvas,
307
+ * from: 'dxos.org/scene/1',
308
+ * to: 'dxos.org/scene/2',
309
+ * since: '0.11.0',
310
+ * transform: ({ content }) => ({ content: upgradeRecords(content) }),
311
+ * });
312
+ * ```
313
+ *
314
+ * @performance O(fields) at definition time; walks the schema's top-level properties.
315
+ */
316
+ export const defineContent = <S extends MigrationSchemaInput>(
317
+ options: DefineContentMigrationOptions<S>,
318
+ ): ContentMigration => {
319
+ const schema = Type.getSchema(options.type);
320
+ const type = getSchemaURI(schema);
321
+ if (!type) {
322
+ throw new Error('Invalid type schema');
323
+ }
324
+ const version = getContentVersionField(schema.ast);
325
+ if (!version) {
326
+ throw new Error(`Type has no ContentVersionAnnotation: ${type}`);
327
+ }
328
+ if (options.from.length === 0 || options.to.length === 0 || options.from === options.to) {
329
+ throw new Error(`Invalid content versions: ${options.from} -> ${options.to}`);
330
+ }
331
+
332
+ const properties = new Map(
333
+ SchemaAST.getPropertySignatures(schema.ast).map((property) => [String(property.name), property]),
334
+ );
335
+ const recordFields = version.fields.filter((field) => {
336
+ const property = properties.get(field);
337
+ if (!property) {
338
+ throw new Error(`ContentVersionAnnotation names an unknown field: ${field}`);
339
+ }
340
+ return isRecordAst(SchemaEx.unwrapOptional(property.type));
341
+ });
342
+
343
+ return {
344
+ [TypeId]: TypeId,
345
+ kind: 'content',
346
+ type,
347
+ versionField: version.field,
348
+ fields: version.fields,
349
+ recordFields,
350
+ from: options.from,
351
+ to: options.to,
352
+ since: options.since,
353
+ transform: options.transform,
354
+ };
355
+ };
356
+
357
+ /**
358
+ * The content steps of `type` keyed by `from`.
359
+ *
360
+ * @throws When two steps start at the same version, since the chain would be ambiguous.
361
+ */
362
+ export const getContentSteps = (
363
+ migrations: readonly Migration[],
364
+ type: URI.URI,
365
+ ): ReadonlyMap<string, ContentMigration> => {
366
+ const steps = new Map<string, ContentMigration>();
367
+ for (const migration of migrations) {
368
+ if (!isContentMigration(migration) || migration.type !== type) {
369
+ continue;
370
+ }
371
+ const existing = steps.get(migration.from);
372
+ if (existing && existing !== migration) {
373
+ throw new Error(`Ambiguous content migrations from ${migration.from}: ${existing.to}, ${migration.to}`);
374
+ }
375
+ steps.set(migration.from, migration);
376
+ }
377
+ return steps;
378
+ };
379
+
380
+ /** Result of {@link upgradeContent}. */
381
+ export type UpgradedContent = {
382
+ readonly version: string | undefined;
383
+ readonly content: Content;
384
+ };
385
+
386
+ /**
387
+ * Upgrades content in memory through the chain of content steps declared for `type`, from `version`
388
+ * to the newest version reachable. Readers use it for data that synced in before the migration pass
389
+ * ran; the pass itself applies the same chain. Content at a version no step starts from is
390
+ * returned as it is (same reference).
391
+ *
392
+ * @performance O(steps) transforms; each costs what its `transform` does.
393
+ */
394
+ export const upgradeContent = (
395
+ migrations: readonly Migration[],
396
+ type: MigrationSchemaInput | URI.URI,
397
+ version: string | undefined,
398
+ content: Content,
399
+ ): UpgradedContent => {
400
+ const uri = typeof type === 'string' ? type : getSchemaURI(Type.getSchema(type));
401
+ if (!uri || version === undefined) {
402
+ return { version, content };
403
+ }
404
+ return applyContentSteps(getContentSteps(migrations, uri), version, content);
405
+ };
406
+
407
+ /**
408
+ * Applies the chain of `steps` starting at `version`.
409
+ *
410
+ * @throws When the chain loops back to a version it already passed.
411
+ */
412
+ export const applyContentSteps = (
413
+ steps: ReadonlyMap<string, ContentMigration>,
414
+ version: string,
415
+ content: Content,
416
+ ): UpgradedContent => {
417
+ const visited = new Set<string>([version]);
418
+ let current = version;
419
+ let result = content;
420
+ for (let step = steps.get(current); step; step = steps.get(current)) {
421
+ result = step.transform(result);
422
+ current = step.to;
423
+ if (visited.has(current)) {
424
+ throw new Error(`Content migrations loop at ${current}`);
425
+ }
426
+ visited.add(current);
427
+ }
428
+ return { version: current, content: result };
429
+ };
430
+
431
+ //
432
+ // Transaction
433
+ //
434
+
435
+ /**
436
+ * Result of {@link Transaction.compact}.
437
+ */
438
+ export type CompactResult = {
439
+ /** Objects whose documents will be rewritten without history. */
440
+ readonly compacted: readonly Obj.ID[];
441
+ /** Requested objects not stored in a document of their own. */
442
+ readonly skipped: readonly Obj.ID[];
443
+ };
444
+
445
+ /**
446
+ * Options for {@link Transaction}.
447
+ */
448
+ export type TransactionOptions = {
449
+ /**
450
+ * How {@link Transaction.commit} publishes the staged changes.
451
+ * - `replace` (default): builds a new space root and starts a new epoch with it. Peers adopt the new
452
+ * root, so writes made to the old root after the transaction began are lost.
453
+ * - `update`: writes the changed links and inline objects into the current root in one atomic change.
454
+ * No epoch is started, and concurrent writes to the root merge.
455
+ */
456
+ root?: 'replace' | 'update';
457
+ };
458
+
459
+ /**
460
+ * Structural changes to a database, staged and then committed atomically.
461
+ *
462
+ * Staged changes are not visible to queries until {@link Transaction.commit}. Use it for changes that
463
+ * an ordinary write cannot express: changing an object's type in place, removing objects without a
464
+ * tombstone, or dropping document history. For schema changes that a write can express, prefer
465
+ * {@link define}. Run it with `db.runMigrations` through {@link defineTransaction}, or directly:
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * const migration = await space.db.beginMigration();
470
+ * yield* migration.migrate(contact.id, (json) => Obj.make(ContactV2, { id: json.id, name: String(json.name) }));
471
+ * migration.add(Obj.make(Note, { title: 'Imported' }));
472
+ * migration.delete(legacy.id);
473
+ * yield* migration.commit();
474
+ * ```
475
+ */
476
+ export interface Transaction {
477
+ /**
478
+ * The staged state of an object: what earlier calls in this transaction left, else what is stored.
479
+ * None for an object that is not stored or that this transaction deletes.
480
+ */
481
+ get(id: Obj.ID): Effect.Effect<Option.Option<Obj.JSON>, EchoError.MigrationError>;
482
+
483
+ /**
484
+ * Stages a new object, with every object it references that is not stored yet.
485
+ * The object is not bound to the database: query it after {@link commit}.
486
+ */
487
+ add(object: Obj.Unknown): void;
488
+
489
+ /**
490
+ * Stages `object` in place of the stored object with the same id, replacing its type, data and meta.
491
+ * The object's document keeps its history, so concurrent edits from peers still merge.
492
+ *
493
+ * @throws When no object with that id is stored.
494
+ */
495
+ replace(object: Obj.Unknown): void;
496
+
497
+ /**
498
+ * Reads the staged state of an object and stages the object `transform` returns in its place.
499
+ * The returned object must keep the id. Does nothing for an object that is not stored.
500
+ *
501
+ * @returns Whether the object was found.
502
+ */
503
+ migrate<E = never, R = never>(
504
+ id: Obj.ID,
505
+ transform: (current: Obj.JSON) => Obj.Unknown | Effect.Effect<Obj.Unknown, E, R>,
506
+ ): Effect.Effect<boolean, E | EchoError.MigrationError, R>;
507
+
508
+ /**
509
+ * Stages removing an object from the space. The object leaves no tombstone.
510
+ */
511
+ delete(id: Obj.ID): void;
512
+
513
+ /**
514
+ * Stages rewriting the documents of the given objects (default: every object stored in a document
515
+ * of its own) without their history.
516
+ */
517
+ compact(ids?: readonly Obj.ID[]): CompactResult;
518
+
519
+ /**
520
+ * Writes the staged changes as {@link TransactionOptions.root} selects.
521
+ * The transaction cannot be used afterwards.
522
+ */
523
+ commit(): Effect.Effect<void, EchoError.MigrationError>;
524
+ }
525
+
526
+ /**
527
+ * Context passed to a {@link TransactionMigration}.
528
+ */
529
+ export type TransactionMigrationContext = {
530
+ /** The database being migrated, for queries; writes go through the transaction. */
531
+ db: Database.Database;
532
+ };
533
+
534
+ /**
535
+ * A migration that stages its changes in a {@link Transaction}, which the runner commits once `run` succeeds.
536
+ */
537
+ export interface TransactionMigration extends Migration {
538
+ readonly kind: 'transaction';
539
+ readonly options: TransactionOptions;
540
+ readonly run: (transaction: Transaction, context: TransactionMigrationContext) => Effect.Effect<void, unknown>;
541
+ }
542
+
543
+ /**
544
+ * Narrows a migration to a {@link TransactionMigration}.
545
+ *
546
+ * @performance O(1).
547
+ */
548
+ export const isTransactionMigration = (migration: Migration): migration is TransactionMigration =>
549
+ migration.kind === 'transaction';
550
+
551
+ /**
552
+ * Define a migration that stages structural changes in a {@link Transaction}.
553
+ * A failure of `run` rejects `db.runMigrations` and commits nothing.
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * const migration = Migration.defineTransaction((transaction) =>
558
+ * Effect.sync(() => transaction.delete(legacyId)),
559
+ * );
560
+ * await db.runMigrations([migration]);
561
+ * ```
562
+ *
563
+ * @performance O(1) at definition time.
564
+ */
565
+ export const defineTransaction = <E>(
566
+ run: (transaction: Transaction, context: TransactionMigrationContext) => Effect.Effect<void, E>,
567
+ options: TransactionOptions = {},
568
+ ): TransactionMigration => ({
569
+ [TypeId]: TypeId,
570
+ kind: 'transaction',
571
+ options,
572
+ run,
573
+ });
package/src/Obj.test.ts CHANGED
@@ -558,6 +558,46 @@ describe('Obj', () => {
558
558
  });
559
559
  });
560
560
 
561
+ describe('setParent', () => {
562
+ test("notifies the child when set inside another object's update", ({ expect }) => {
563
+ const child = Obj.make(TestSchema.Task, { title: 'Child' });
564
+ const person = Obj.make(TestSchema.Person, {
565
+ name: 'Alice',
566
+ email: 'alice@example.com',
567
+ username: 'alice',
568
+ tasks: [Ref.make(child)],
569
+ });
570
+ let notified = 0;
571
+ const unsubscribe = Obj.subscribe(child, () => notified++);
572
+ Obj.update(person, (person) => {
573
+ person.name = 'Alice B';
574
+ Obj.setParent(child, person);
575
+ });
576
+ unsubscribe();
577
+ expect(Obj.getParent(child)?.id).toBe(person.id);
578
+ expect(notified).toBe(1);
579
+ });
580
+
581
+ test('notifies the child once when set inside its own update', ({ expect }) => {
582
+ const child = Obj.make(TestSchema.Task, { title: 'Child' });
583
+ const person = Obj.make(TestSchema.Person, {
584
+ name: 'Alice',
585
+ email: 'alice@example.com',
586
+ username: 'alice',
587
+ tasks: [Ref.make(child)],
588
+ });
589
+ let notified = 0;
590
+ const unsubscribe = Obj.subscribe(child, () => notified++);
591
+ Obj.update(child, (child) => {
592
+ child.title = 'Renamed';
593
+ Obj.setParent(child, person);
594
+ });
595
+ unsubscribe();
596
+ expect(Obj.getParent(child)?.id).toBe(person.id);
597
+ expect(notified).toBe(1);
598
+ });
599
+ });
600
+
561
601
  describe('type-level tests', () => {
562
602
  test('Obj.Unknown does not allow arbitrary property access', () => {
563
603
  // Obj.Unknown only exposes `id` - no arbitrary properties.
@@ -741,18 +781,18 @@ describe('Obj', () => {
741
781
  expect(fires).toBe(baseline);
742
782
 
743
783
  Obj.update(obj, (obj) => {
744
- Obj.getMeta(obj).tags.push(Ref.make(urgent));
784
+ Obj.getMeta(obj).tags.push(urgent);
745
785
  });
746
786
  expect(fires).toBe(baseline + 1);
747
- expect(registry.get(tagsAtom).map((ref) => ref.uri.toString())).toEqual([Ref.make(urgent).uri.toString()]);
787
+ expect(registry.get(tagsAtom)).toEqual([urgent]);
748
788
 
749
789
  Obj.update(obj, (obj) => {
750
- Obj.getMeta(obj).tags.splice(0, 1, Ref.make(urgent));
790
+ Obj.getMeta(obj).tags.splice(0, 1, urgent);
751
791
  });
752
792
  expect(fires).toBe(baseline + 1);
753
793
 
754
794
  Obj.update(obj, (obj) => {
755
- Obj.getMeta(obj).tags.push(Ref.make(later));
795
+ Obj.getMeta(obj).tags.push(later);
756
796
  });
757
797
  expect(fires).toBe(baseline + 2);
758
798
  expect(registry.get(tagsAtom)).toHaveLength(2);
package/src/Obj.ts CHANGED
@@ -760,7 +760,7 @@ export type Meta = internal.Meta;
760
760
  * // Mutable access inside change callback
761
761
  * Obj.update(person, (obj) => {
762
762
  * const meta = Obj.getMeta(obj); // EntityMeta (mutable)
763
- * meta.tags.push(Ref.make(tag)); // tags are refs to Tag objects
763
+ * meta.tags.push(tag); // tags are Tag objects
764
764
  * });
765
765
  * ```
766
766
  *
@@ -802,9 +802,9 @@ export const deleteKeys = (entity: Mutable<Unknown>, source: string): void => in
802
802
  * NOTE: TypeScript's structural typing allows readonly objects to be passed to `Mutable<T>`
803
803
  * parameters, so there is no compile-time error. Enforcement is runtime-only.
804
804
  *
805
- * @performance O(t) in the tag count; dedupes by ref URI before appending.
805
+ * @performance O(t) in the tag count; dedupes by tag id before appending.
806
806
  */
807
- export const addTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.addTag(entity, tag);
807
+ export const addTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.addTag(entity, tag);
808
808
 
809
809
  /**
810
810
  * Remove a tag from the object.
@@ -815,7 +815,7 @@ export const addTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void =>
815
815
  *
816
816
  * @performance O(t) in the tag count.
817
817
  */
818
- export const removeTag = (entity: Mutable<Unknown>, tag: Ref.Ref<Tag.Tag>): void => internal.removeTag(entity, tag);
818
+ export const removeTag = (entity: Mutable<Unknown>, tag: Tag.Tag): void => internal.removeTag(entity, tag);
819
819
 
820
820
  /**
821
821
  * Check if the object is deleted.
@@ -961,7 +961,21 @@ export const setParent = (entity: Unknown, parent: Any | undefined) => {
961
961
  }
962
962
  assumeType<internal.InternalObjectProps>(entity);
963
963
  assumeType<internal.InternalObjectProps | undefined>(parent);
964
- entity[internal.ParentId] = parent;
964
+ // The parent is part of the object's state, so setting it notifies subscribers like any edit, in a change
965
+ // of its own; inside any `Obj.update` it is set directly, since a nested change would end the caller's.
966
+ if (internal.isAnyChangeContextActive()) {
967
+ entity[internal.ParentId] = parent;
968
+ // The context's exit notifies only its own object, so another object's update must queue this one.
969
+ const changeKey: object | undefined = Reflect.get(entity, internal.ChangeKeyId);
970
+ if (changeKey === undefined || !internal.isInChangeContext(changeKey)) {
971
+ internal.queueOwnerNotification(entity);
972
+ }
973
+ } else {
974
+ internal.change(entity, (mutable) => {
975
+ assumeType<internal.InternalObjectProps>(mutable);
976
+ mutable[internal.ParentId] = parent;
977
+ });
978
+ }
965
979
  return entity;
966
980
  };
967
981
 
@@ -42,9 +42,23 @@ export type Entry<T> = {
42
42
  * Query resolution time in milliseconds.
43
43
  */
44
44
  time: number;
45
+
46
+ /** The state a remote source evaluated the entry at; absent for an in-process entry. */
47
+ version?: Version;
48
+
49
+ /**
50
+ * Whether local evidence confirmed a remote entry: its object is loaded here and still matches, or is held
51
+ * at the exact version the remote evaluated. False when the entry is shown on the remote's word alone.
52
+ */
53
+ verified?: boolean;
45
54
  };
46
55
  };
47
56
 
57
+ /** The state a remote source evaluated an entry at: a document's heads, or a feed block's position. */
58
+ export type Version =
59
+ | { kind: 'automerge'; documentId: string; heads: readonly string[] }
60
+ | { kind: 'feed'; insertionId: number };
61
+
48
62
  /**
49
63
  * Where query results come from.
50
64
  */