@dxos/migrations 0.5.9-main.8359215 → 0.5.9-main.89d55b2

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.
@@ -1,35 +1,197 @@
1
- // packages/sdk/migrations/src/migrations.ts
2
- import { SpaceState } from "@dxos/client/echo";
1
+ // packages/sdk/migrations/src/migration-builder.ts
2
+ import { getHeads } from "@dxos/automerge/automerge";
3
+ import { CreateEpochRequest } from "@dxos/client/halo";
4
+ import { ObjectCore } from "@dxos/echo-db";
5
+ import { encodeReference, Reference } from "@dxos/echo-protocol";
6
+ import { requireTypeReference } from "@dxos/echo-schema";
3
7
  import { invariant } from "@dxos/invariant";
4
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
8
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migration-builder.ts";
9
+ var MigrationBuilder = class {
10
+ constructor(_space) {
11
+ this._space = _space;
12
+ this._newLinks = {};
13
+ this._flushStates = [];
14
+ this._deleteObjects = [];
15
+ this._newRoot = void 0;
16
+ this._repo = this._space.db.coreDatabase.automerge.repo;
17
+ this._automergeContext = this._space.db.coreDatabase.automerge;
18
+ this._rootDoc = this._space.db.coreDatabase._automergeDocLoader.getSpaceRootDocHandle().docSync();
19
+ }
20
+ async findObject(id) {
21
+ const documentId = this._rootDoc.links?.[id] || this._newLinks[id];
22
+ const docHandle = documentId && this._repo.find(documentId);
23
+ if (!docHandle) {
24
+ return void 0;
25
+ }
26
+ await docHandle.whenReady();
27
+ const doc = docHandle.docSync();
28
+ return doc.objects?.[id];
29
+ }
30
+ async migrateObject(id, migrate) {
31
+ const objectStructure = await this.findObject(id);
32
+ if (!objectStructure) {
33
+ return;
34
+ }
35
+ const { schema, props } = await migrate(objectStructure);
36
+ this._createObject({
37
+ id,
38
+ schema,
39
+ props
40
+ });
41
+ }
42
+ async addObject(schema, props) {
43
+ const core = this._createObject({
44
+ schema,
45
+ props
46
+ });
47
+ return core.id;
48
+ }
49
+ createReference(id) {
50
+ return encodeReference(new Reference(id));
51
+ }
52
+ deleteObject(id) {
53
+ this._deleteObjects.push(id);
54
+ }
55
+ changeProperties(changeFn) {
56
+ if (!this._newRoot) {
57
+ this._buildNewRoot();
58
+ }
59
+ invariant(this._newRoot, "New root not created", {
60
+ F: __dxlog_file,
61
+ L: 79,
62
+ S: this,
63
+ A: [
64
+ "this._newRoot",
65
+ "'New root not created'"
66
+ ]
67
+ });
68
+ this._newRoot.change((doc) => {
69
+ const propertiesStructure = doc.objects?.[this._space.properties.id];
70
+ propertiesStructure && changeFn(propertiesStructure);
71
+ });
72
+ this._flushStates.push({
73
+ documentId: this._newRoot.documentId,
74
+ heads: getHeads(this._newRoot.docSync())
75
+ });
76
+ }
77
+ /**
78
+ * @internal
79
+ */
80
+ async _commit() {
81
+ if (!this._newRoot) {
82
+ this._buildNewRoot();
83
+ }
84
+ invariant(this._newRoot, "New root not created", {
85
+ F: __dxlog_file,
86
+ L: 98,
87
+ S: this,
88
+ A: [
89
+ "this._newRoot",
90
+ "'New root not created'"
91
+ ]
92
+ });
93
+ await this._automergeContext.flush({
94
+ states: this._flushStates
95
+ });
96
+ await this._space.internal.createEpoch({
97
+ migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,
98
+ automergeRootUrl: this._newRoot.url
99
+ });
100
+ }
101
+ _buildNewRoot() {
102
+ const previousLinks = {
103
+ ...this._rootDoc.links ?? {}
104
+ };
105
+ for (const id of this._deleteObjects) {
106
+ delete previousLinks[id];
107
+ }
108
+ this._newRoot = this._repo.create({
109
+ access: {
110
+ spaceKey: this._space.key.toHex()
111
+ },
112
+ objects: this._rootDoc.objects,
113
+ links: {
114
+ ...previousLinks,
115
+ ...this._newLinks
116
+ }
117
+ });
118
+ this._flushStates.push({
119
+ documentId: this._newRoot.documentId,
120
+ heads: getHeads(this._newRoot.docSync())
121
+ });
122
+ }
123
+ _createObject({ id, schema, props }) {
124
+ const core = new ObjectCore();
125
+ if (id) {
126
+ core.id = id;
127
+ }
128
+ core.initNewObject(props);
129
+ core.setType(requireTypeReference(schema));
130
+ const newHandle = this._repo.create({
131
+ access: {
132
+ spaceKey: this._space.key.toHex()
133
+ },
134
+ objects: {
135
+ [core.id]: core.getDoc()
136
+ }
137
+ });
138
+ this._newLinks[core.id] = newHandle.url;
139
+ this._flushStates.push({
140
+ documentId: newHandle.documentId,
141
+ heads: getHeads(newHandle.docSync())
142
+ });
143
+ return core;
144
+ }
145
+ };
146
+
147
+ // packages/sdk/migrations/src/migrations.ts
148
+ import { create, SpaceState } from "@dxos/client/echo";
149
+ import { invariant as invariant2 } from "@dxos/invariant";
150
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
5
151
  var Migrations = class {
6
152
  static {
7
153
  this.migrations = [];
8
154
  }
155
+ static {
156
+ this._state = create({
157
+ running: []
158
+ });
159
+ }
9
160
  static get versionProperty() {
10
161
  return this.namespace && `${this.namespace}.version`;
11
162
  }
12
163
  static get targetVersion() {
13
164
  return this.migrations[this.migrations.length - 1].version;
14
165
  }
166
+ static running(space) {
167
+ return this._state.running.includes(space.key.toHex());
168
+ }
15
169
  static define(namespace, migrations) {
16
170
  this.namespace = namespace;
17
171
  this.migrations = migrations;
18
172
  }
19
- // TODO(wittjosiah): Multi-space migrations.
20
173
  static async migrate(space, targetVersion) {
21
- invariant(this.versionProperty, "Migrations namespace not set", {
22
- F: __dxlog_file,
23
- L: 40,
174
+ invariant2(!this.running(space), "Migration already running", {
175
+ F: __dxlog_file2,
176
+ L: 44,
177
+ S: this,
178
+ A: [
179
+ "!this.running(space)",
180
+ "'Migration already running'"
181
+ ]
182
+ });
183
+ invariant2(this.versionProperty, "Migrations namespace not set", {
184
+ F: __dxlog_file2,
185
+ L: 45,
24
186
  S: this,
25
187
  A: [
26
188
  "this.versionProperty",
27
189
  "'Migrations namespace not set'"
28
190
  ]
29
191
  });
30
- invariant(space.state.get() === SpaceState.READY, "Space not ready", {
31
- F: __dxlog_file,
32
- L: 41,
192
+ invariant2(space.state.get() === SpaceState.READY, "Space not ready", {
193
+ F: __dxlog_file2,
194
+ L: 46,
33
195
  S: this,
34
196
  A: [
35
197
  "space.state.get() === SpaceState.READY",
@@ -43,29 +205,36 @@ var Migrations = class {
43
205
  if (currentIndex === targetIndex) {
44
206
  return false;
45
207
  }
208
+ this._state.running.push(space.key.toHex());
46
209
  if (targetIndex > currentIndex) {
47
210
  const migrations = this.migrations.slice(currentIndex, targetIndex);
48
211
  for (const migration of migrations) {
49
- await migration.up({
50
- space
212
+ const builder = new MigrationBuilder(space);
213
+ await migration.next({
214
+ space,
215
+ builder
51
216
  });
52
- space.properties[this.versionProperty] = migration.version;
53
- }
54
- } else {
55
- const migrations = this.migrations.slice(targetIndex, currentIndex);
56
- migrations.reverse();
57
- for (const migration of migrations) {
58
- await migration.down({
59
- space
217
+ builder.changeProperties((propertiesStructure) => {
218
+ invariant2(this.versionProperty, "Migrations namespace not set", {
219
+ F: __dxlog_file2,
220
+ L: 62,
221
+ S: this,
222
+ A: [
223
+ "this.versionProperty",
224
+ "'Migrations namespace not set'"
225
+ ]
226
+ });
227
+ propertiesStructure.data[this.versionProperty] = migration.version;
60
228
  });
61
- const index = this.migrations.indexOf(migration);
62
- space.properties[this.versionProperty] = this.migrations[index - 1]?.version;
229
+ await builder._commit();
63
230
  }
64
231
  }
232
+ this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);
65
233
  return true;
66
234
  }
67
235
  };
68
236
  export {
237
+ MigrationBuilder,
69
238
  Migrations
70
239
  };
71
240
  //# sourceMappingURL=index.mjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/migrations.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Space, SpaceState } from '@dxos/client/echo';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\n// TODO(burdon): Merge with successor to serialization mechanism in braneframe/types.\n\nexport type MigrationContext = {\n space: Space;\n};\n\nexport type Migration = {\n version: string | number;\n up: (context: MigrationContext) => MaybePromise<void>;\n down: (context: MigrationContext) => MaybePromise<void>;\n};\n\nexport class Migrations {\n static namespace?: string;\n static migrations: Migration[] = [];\n\n static get versionProperty() {\n return this.namespace && `${this.namespace}.version`;\n }\n\n static get targetVersion() {\n return this.migrations[this.migrations.length - 1].version;\n }\n\n static define(namespace: string, migrations: Migration[]) {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n // TODO(wittjosiah): Multi-space migrations.\n static async migrate(space: Space, targetVersion?: string | number) {\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.READY, 'Space not ready');\n const currentVersion = space.properties[this.versionProperty];\n const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;\n const i = this.migrations.findIndex((m) => m.version === targetVersion);\n const targetIndex = i === -1 ? this.migrations.length : i + 1;\n if (currentIndex === targetIndex) {\n return false;\n }\n\n if (targetIndex > currentIndex) {\n const migrations = this.migrations.slice(currentIndex, targetIndex);\n for (const migration of migrations) {\n await migration.up({ space });\n space.properties[this.versionProperty] = migration.version;\n }\n } else {\n const migrations = this.migrations.slice(targetIndex, currentIndex);\n migrations.reverse();\n for (const migration of migrations) {\n await migration.down({ space });\n const index = this.migrations.indexOf(migration);\n space.properties[this.versionProperty] = this.migrations[index - 1]?.version;\n }\n }\n\n return true;\n }\n}\n"],
5
- "mappings": ";AAIA,SAAqBA,kBAAkB;AACvC,SAASC,iBAAiB;;AAenB,IAAMC,aAAN,MAAMA;EAEX;SAAOC,aAA0B,CAAA;;EAEjC,WAAWC,kBAAkB;AAC3B,WAAO,KAAKC,aAAa,GAAG,KAAKA,SAAS;EAC5C;EAEA,WAAWC,gBAAgB;AACzB,WAAO,KAAKH,WAAW,KAAKA,WAAWI,SAAS,CAAA,EAAGC;EACrD;EAEA,OAAOC,OAAOJ,WAAmBF,YAAyB;AACxD,SAAKE,YAAYA;AACjB,SAAKF,aAAaA;EACpB;;EAGA,aAAaO,QAAQC,OAAcL,eAAiC;AAClEL,cAAU,KAAKG,iBAAiB,gCAAA;;;;;;;;;AAChCH,cAAUU,MAAMC,MAAMC,IAAG,MAAOb,WAAWc,OAAO,mBAAA;;;;;;;;;AAClD,UAAMC,iBAAiBJ,MAAMK,WAAW,KAAKZ,eAAe;AAC5D,UAAMa,eAAe,KAAKd,WAAWe,UAAU,CAACC,MAAMA,EAAEX,YAAYO,cAAAA,IAAkB;AACtF,UAAMK,IAAI,KAAKjB,WAAWe,UAAU,CAACC,MAAMA,EAAEX,YAAYF,aAAAA;AACzD,UAAMe,cAAcD,MAAM,KAAK,KAAKjB,WAAWI,SAASa,IAAI;AAC5D,QAAIH,iBAAiBI,aAAa;AAChC,aAAO;IACT;AAEA,QAAIA,cAAcJ,cAAc;AAC9B,YAAMd,aAAa,KAAKA,WAAWmB,MAAML,cAAcI,WAAAA;AACvD,iBAAWE,aAAapB,YAAY;AAClC,cAAMoB,UAAUC,GAAG;UAAEb;QAAM,CAAA;AAC3BA,cAAMK,WAAW,KAAKZ,eAAe,IAAImB,UAAUf;MACrD;IACF,OAAO;AACL,YAAML,aAAa,KAAKA,WAAWmB,MAAMD,aAAaJ,YAAAA;AACtDd,iBAAWsB,QAAO;AAClB,iBAAWF,aAAapB,YAAY;AAClC,cAAMoB,UAAUG,KAAK;UAAEf;QAAM,CAAA;AAC7B,cAAMgB,QAAQ,KAAKxB,WAAWyB,QAAQL,SAAAA;AACtCZ,cAAMK,WAAW,KAAKZ,eAAe,IAAI,KAAKD,WAAWwB,QAAQ,CAAA,GAAInB;MACvE;IACF;AAEA,WAAO;EACT;AACF;",
6
- "names": ["SpaceState", "invariant", "Migrations", "migrations", "versionProperty", "namespace", "targetVersion", "length", "version", "define", "migrate", "space", "state", "get", "READY", "currentVersion", "properties", "currentIndex", "findIndex", "m", "i", "targetIndex", "slice", "migration", "up", "reverse", "down", "index", "indexOf"]
3
+ "sources": ["../../../src/migration-builder.ts", "../../../src/migrations.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Doc, getHeads } from '@dxos/automerge/automerge';\nimport { type AnyDocumentId, type DocHandle, type Repo } from '@dxos/automerge/automerge-repo';\nimport { type Space } from '@dxos/client/echo';\nimport { CreateEpochRequest } from '@dxos/client/halo';\nimport { type AutomergeContext, ObjectCore } from '@dxos/echo-db';\nimport { encodeReference, type ObjectStructure, Reference, type SpaceDoc } from '@dxos/echo-protocol';\nimport { requireTypeReference, type S } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { type FlushRequest } from '@dxos/protocols/proto/dxos/echo/service';\nimport { type MaybePromise } from '@dxos/util';\n\nexport class MigrationBuilder {\n private readonly _repo: Repo;\n private readonly _automergeContext: AutomergeContext;\n private readonly _rootDoc: Doc<SpaceDoc>;\n\n // echoId -> automergeUrl\n private readonly _newLinks: Record<string, string> = {};\n private readonly _flushStates: FlushRequest.DocState[] = [];\n private readonly _deleteObjects: string[] = [];\n\n private _newRoot?: DocHandle<SpaceDoc> = undefined;\n\n constructor(private readonly _space: Space) {\n this._repo = this._space.db.coreDatabase.automerge.repo;\n this._automergeContext = this._space.db.coreDatabase.automerge;\n // TODO(wittjosiah): Accessing private API.\n this._rootDoc = (this._space.db.coreDatabase as any)._automergeDocLoader\n .getSpaceRootDocHandle()\n .docSync() as Doc<SpaceDoc>;\n }\n\n async findObject(id: string): Promise<ObjectStructure | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id]) as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n const doc = docHandle.docSync() as Doc<SpaceDoc>;\n return doc.objects?.[id];\n }\n\n async migrateObject(\n id: string,\n migrate: (objectStructure: ObjectStructure) => MaybePromise<{ schema: S.Schema<any>; props: any }>,\n ) {\n const objectStructure = await this.findObject(id);\n if (!objectStructure) {\n return;\n }\n\n const { schema, props } = await migrate(objectStructure);\n this._createObject({ id, schema, props });\n }\n\n async addObject(schema: S.Schema<any>, props: any) {\n const core = this._createObject({ schema, props });\n return core.id;\n }\n\n createReference(id: string) {\n return encodeReference(new Reference(id));\n }\n\n deleteObject(id: string) {\n this._deleteObjects.push(id);\n }\n\n changeProperties(changeFn: (properties: ObjectStructure) => void) {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n this._newRoot.change((doc: SpaceDoc) => {\n const propertiesStructure = doc.objects?.[this._space.properties.id];\n propertiesStructure && changeFn(propertiesStructure);\n });\n this._flushStates.push({\n documentId: this._newRoot.documentId,\n heads: getHeads(this._newRoot.docSync()),\n });\n }\n\n /**\n * @internal\n */\n async _commit() {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n await this._automergeContext.flush({\n states: this._flushStates,\n });\n\n // Create new epoch.\n await this._space.internal.createEpoch({\n migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,\n automergeRootUrl: this._newRoot.url,\n });\n }\n\n private _buildNewRoot() {\n const previousLinks = { ...(this._rootDoc.links ?? {}) };\n for (const id of this._deleteObjects) {\n delete previousLinks[id];\n }\n\n this._newRoot = this._repo.create<SpaceDoc>({\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: this._rootDoc.objects,\n links: {\n ...previousLinks,\n ...this._newLinks,\n },\n });\n this._flushStates.push({\n documentId: this._newRoot.documentId,\n heads: getHeads(this._newRoot.docSync()),\n });\n }\n\n private _createObject({ id, schema, props }: { id?: string; schema: S.Schema<any>; props: any }) {\n const core = new ObjectCore();\n if (id) {\n core.id = id;\n }\n\n core.initNewObject(props);\n core.setType(requireTypeReference(schema));\n const newHandle = this._repo.create<SpaceDoc>({\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [core.id]: core.getDoc(),\n },\n });\n this._newLinks[core.id] = newHandle.url;\n this._flushStates.push({\n documentId: newHandle.documentId,\n heads: getHeads(newHandle.docSync()),\n });\n\n return core;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Space, create, SpaceState } from '@dxos/client/echo';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { MigrationBuilder } from './migration-builder';\n\nexport type MigrationContext = {\n space: Space;\n builder: MigrationBuilder;\n};\n\nexport type Migration = {\n version: string;\n next: (context: MigrationContext) => MaybePromise<void>;\n};\n\nexport class Migrations {\n static namespace?: string;\n static migrations: Migration[] = [];\n private static _state = create<{ running: string[] }>({ running: [] });\n\n static get versionProperty() {\n return this.namespace && `${this.namespace}.version`;\n }\n\n static get targetVersion() {\n return this.migrations[this.migrations.length - 1].version;\n }\n\n static running(space: Space) {\n return this._state.running.includes(space.key.toHex());\n }\n\n static define(namespace: string, migrations: Migration[]) {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n static async migrate(space: Space, targetVersion?: string | number) {\n invariant(!this.running(space), 'Migration already running');\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.READY, 'Space not ready');\n const currentVersion = space.properties[this.versionProperty];\n const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;\n const i = this.migrations.findIndex((m) => m.version === targetVersion);\n const targetIndex = i === -1 ? this.migrations.length : i + 1;\n if (currentIndex === targetIndex) {\n return false;\n }\n\n this._state.running.push(space.key.toHex());\n if (targetIndex > currentIndex) {\n const migrations = this.migrations.slice(currentIndex, targetIndex);\n for (const migration of migrations) {\n const builder = new MigrationBuilder(space);\n await migration.next({ space, builder });\n builder.changeProperties((propertiesStructure) => {\n invariant(this.versionProperty, 'Migrations namespace not set');\n propertiesStructure.data[this.versionProperty] = migration.version;\n });\n await builder._commit();\n }\n }\n this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);\n\n return true;\n }\n}\n"],
5
+ "mappings": ";AAIA,SAAmBA,gBAAg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iBAAiB,gCAAA;;;;;;;;;AAChCW,IAAAA,WAAUN,MAAMO,MAAMC,IAAG,MAAOC,WAAWC,OAAO,mBAAA;;;;;;;;;AAClD,UAAMC,iBAAiBX,MAAMY,WAAW,KAAKjB,eAAe;AAC5D,UAAMkB,eAAe,KAAKtB,WAAWuB,UAAU,CAACC,MAAMA,EAAEhB,YAAYY,cAAAA,IAAkB;AACtF,UAAMK,IAAI,KAAKzB,WAAWuB,UAAU,CAACC,MAAMA,EAAEhB,YAAYF,aAAAA;AACzD,UAAMoB,cAAcD,MAAM,KAAK,KAAKzB,WAAWO,SAASkB,IAAI;AAC5D,QAAIH,iBAAiBI,aAAa;AAChC,aAAO;IACT;AAEA,SAAKzB,OAAOE,QAAQwB,KAAKlB,MAAME,IAAIC,MAAK,CAAA;AACxC,QAAIc,cAAcJ,cAAc;AAC9B,YAAMtB,aAAa,KAAKA,WAAW4B,MAAMN,cAAcI,WAAAA;AACvD,iBAAWG,aAAa7B,YAAY;AAClC,cAAM8B,UAAU,IAAIC,iBAAiBtB,KAAAA;AACrC,cAAMoB,UAAUG,KAAK;UAAEvB;UAAOqB;QAAQ,CAAA;AACtCA,gBAAQG,iBAAiB,CAACC,wBAAAA;AACxBnB,UAAAA,WAAU,KAAKX,iBAAiB,gCAAA;;;;;;;;;AAChC8B,8BAAoBC,KAAK,KAAK/B,eAAe,IAAIyB,UAAUrB;QAC7D,CAAA;AACA,cAAMsB,QAAQM,QAAO;MACvB;IACF;AACA,SAAKnC,OAAOE,QAAQkC,OAAO,KAAKpC,OAAOE,QAAQmC,QAAQ7B,MAAME,IAAIC,MAAK,CAAA,GAAK,CAAA;AAE3E,WAAO;EACT;AACF;",
6
+ "names": ["getHeads", "CreateEpochRequest", "ObjectCore", "encodeReference", "Reference", "requireTypeReference", "invariant", "MigrationBuilder", "constructor", "_space", "_newLinks", "_flushStates", "_deleteObjects", "_newRoot", "undefined", "_repo", "db", "coreDatabase", "automerge", "repo", "_automergeContext", "_rootDoc", "_automergeDocLoader", "getSpaceRootDocHandle", "docSync", "findObject", "id", "documentId", "links", "docHandle", "find", "whenReady", "doc", "objects", "migrateObject", "migrate", "objectStructure", "schema", "props", "_createObject", "addObject", "core", "createReference", "deleteObject", "push", "changeProperties", "changeFn", "_buildNewRoot", "change", "propertiesStructure", "properties", "heads", "_commit", "flush", "states", "internal", "createEpoch", "migration", "Migration", "REPLACE_AUTOMERGE_ROOT", "automergeRootUrl", "url", "previousLinks", "create", "access", "spaceKey", "key", "toHex", "initNewObject", "setType", "newHandle", "getDoc", "create", "SpaceState", "invariant", "Migrations", "migrations", "_state", "create", "running", "versionProperty", "namespace", "targetVersion", "length", "version", "space", "includes", "key", "toHex", "define", "migrate", "invariant", "state", "get", "SpaceState", "READY", "currentVersion", "properties", "currentIndex", "findIndex", "m", "i", "targetIndex", "push", "slice", "migration", "builder", "MigrationBuilder", "next", "changeProperties", "propertiesStructure", "data", "_commit", "splice", "indexOf"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/sdk/migrations/src/migrations.ts":{"bytes":8236,"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/sdk/migrations/src/index.ts":{"bytes":501,"imports":[{"path":"packages/sdk/migrations/src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"packages/sdk/migrations/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":3895},"packages/sdk/migrations/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["Migrations"],"entryPoint":"packages/sdk/migrations/src/index.ts","inputs":{"packages/sdk/migrations/src/migrations.ts":{"bytesInOutput":2163},"packages/sdk/migrations/src/index.ts":{"bytesInOutput":0}},"bytes":2268}}}
1
+ {"inputs":{"packages/sdk/migrations/src/migration-builder.ts":{"bytes":17544,"imports":[{"path":"@dxos/automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/sdk/migrations/src/migrations.ts":{"bytes":9817,"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/sdk/migrations/src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"}],"format":"esm"},"packages/sdk/migrations/src/index.ts":{"bytes":698,"imports":[{"path":"packages/sdk/migrations/src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"},{"path":"packages/sdk/migrations/src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"packages/sdk/migrations/dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13051},"packages/sdk/migrations/dist/lib/browser/index.mjs":{"imports":[{"path":"@dxos/automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["MigrationBuilder","Migrations"],"entryPoint":"packages/sdk/migrations/src/index.ts","inputs":{"packages/sdk/migrations/src/migration-builder.ts":{"bytesInOutput":3936},"packages/sdk/migrations/src/index.ts":{"bytesInOutput":0},"packages/sdk/migrations/src/migrations.ts":{"bytesInOutput":2745}},"bytes":6859}}}
@@ -18,40 +18,201 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
+ MigrationBuilder: () => MigrationBuilder,
21
22
  Migrations: () => Migrations
22
23
  });
23
24
  module.exports = __toCommonJS(node_exports);
24
- var import_echo = require("@dxos/client/echo");
25
+ var import_automerge = require("@dxos/automerge/automerge");
26
+ var import_halo = require("@dxos/client/halo");
27
+ var import_echo_db = require("@dxos/echo-db");
28
+ var import_echo_protocol = require("@dxos/echo-protocol");
29
+ var import_echo_schema = require("@dxos/echo-schema");
25
30
  var import_invariant = require("@dxos/invariant");
26
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
31
+ var import_echo = require("@dxos/client/echo");
32
+ var import_invariant2 = require("@dxos/invariant");
33
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migration-builder.ts";
34
+ var MigrationBuilder = class {
35
+ constructor(_space) {
36
+ this._space = _space;
37
+ this._newLinks = {};
38
+ this._flushStates = [];
39
+ this._deleteObjects = [];
40
+ this._newRoot = void 0;
41
+ this._repo = this._space.db.coreDatabase.automerge.repo;
42
+ this._automergeContext = this._space.db.coreDatabase.automerge;
43
+ this._rootDoc = this._space.db.coreDatabase._automergeDocLoader.getSpaceRootDocHandle().docSync();
44
+ }
45
+ async findObject(id) {
46
+ const documentId = this._rootDoc.links?.[id] || this._newLinks[id];
47
+ const docHandle = documentId && this._repo.find(documentId);
48
+ if (!docHandle) {
49
+ return void 0;
50
+ }
51
+ await docHandle.whenReady();
52
+ const doc = docHandle.docSync();
53
+ return doc.objects?.[id];
54
+ }
55
+ async migrateObject(id, migrate) {
56
+ const objectStructure = await this.findObject(id);
57
+ if (!objectStructure) {
58
+ return;
59
+ }
60
+ const { schema, props } = await migrate(objectStructure);
61
+ this._createObject({
62
+ id,
63
+ schema,
64
+ props
65
+ });
66
+ }
67
+ async addObject(schema, props) {
68
+ const core = this._createObject({
69
+ schema,
70
+ props
71
+ });
72
+ return core.id;
73
+ }
74
+ createReference(id) {
75
+ return (0, import_echo_protocol.encodeReference)(new import_echo_protocol.Reference(id));
76
+ }
77
+ deleteObject(id) {
78
+ this._deleteObjects.push(id);
79
+ }
80
+ changeProperties(changeFn) {
81
+ if (!this._newRoot) {
82
+ this._buildNewRoot();
83
+ }
84
+ (0, import_invariant.invariant)(this._newRoot, "New root not created", {
85
+ F: __dxlog_file,
86
+ L: 79,
87
+ S: this,
88
+ A: [
89
+ "this._newRoot",
90
+ "'New root not created'"
91
+ ]
92
+ });
93
+ this._newRoot.change((doc) => {
94
+ const propertiesStructure = doc.objects?.[this._space.properties.id];
95
+ propertiesStructure && changeFn(propertiesStructure);
96
+ });
97
+ this._flushStates.push({
98
+ documentId: this._newRoot.documentId,
99
+ heads: (0, import_automerge.getHeads)(this._newRoot.docSync())
100
+ });
101
+ }
102
+ /**
103
+ * @internal
104
+ */
105
+ async _commit() {
106
+ if (!this._newRoot) {
107
+ this._buildNewRoot();
108
+ }
109
+ (0, import_invariant.invariant)(this._newRoot, "New root not created", {
110
+ F: __dxlog_file,
111
+ L: 98,
112
+ S: this,
113
+ A: [
114
+ "this._newRoot",
115
+ "'New root not created'"
116
+ ]
117
+ });
118
+ await this._automergeContext.flush({
119
+ states: this._flushStates
120
+ });
121
+ await this._space.internal.createEpoch({
122
+ migration: import_halo.CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,
123
+ automergeRootUrl: this._newRoot.url
124
+ });
125
+ }
126
+ _buildNewRoot() {
127
+ const previousLinks = {
128
+ ...this._rootDoc.links ?? {}
129
+ };
130
+ for (const id of this._deleteObjects) {
131
+ delete previousLinks[id];
132
+ }
133
+ this._newRoot = this._repo.create({
134
+ access: {
135
+ spaceKey: this._space.key.toHex()
136
+ },
137
+ objects: this._rootDoc.objects,
138
+ links: {
139
+ ...previousLinks,
140
+ ...this._newLinks
141
+ }
142
+ });
143
+ this._flushStates.push({
144
+ documentId: this._newRoot.documentId,
145
+ heads: (0, import_automerge.getHeads)(this._newRoot.docSync())
146
+ });
147
+ }
148
+ _createObject({ id, schema, props }) {
149
+ const core = new import_echo_db.ObjectCore();
150
+ if (id) {
151
+ core.id = id;
152
+ }
153
+ core.initNewObject(props);
154
+ core.setType((0, import_echo_schema.requireTypeReference)(schema));
155
+ const newHandle = this._repo.create({
156
+ access: {
157
+ spaceKey: this._space.key.toHex()
158
+ },
159
+ objects: {
160
+ [core.id]: core.getDoc()
161
+ }
162
+ });
163
+ this._newLinks[core.id] = newHandle.url;
164
+ this._flushStates.push({
165
+ documentId: newHandle.documentId,
166
+ heads: (0, import_automerge.getHeads)(newHandle.docSync())
167
+ });
168
+ return core;
169
+ }
170
+ };
171
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
27
172
  var Migrations = class {
28
173
  static {
29
174
  this.migrations = [];
30
175
  }
176
+ static {
177
+ this._state = (0, import_echo.create)({
178
+ running: []
179
+ });
180
+ }
31
181
  static get versionProperty() {
32
182
  return this.namespace && `${this.namespace}.version`;
33
183
  }
34
184
  static get targetVersion() {
35
185
  return this.migrations[this.migrations.length - 1].version;
36
186
  }
187
+ static running(space) {
188
+ return this._state.running.includes(space.key.toHex());
189
+ }
37
190
  static define(namespace, migrations) {
38
191
  this.namespace = namespace;
39
192
  this.migrations = migrations;
40
193
  }
41
- // TODO(wittjosiah): Multi-space migrations.
42
194
  static async migrate(space, targetVersion) {
43
- (0, import_invariant.invariant)(this.versionProperty, "Migrations namespace not set", {
44
- F: __dxlog_file,
45
- L: 40,
195
+ (0, import_invariant2.invariant)(!this.running(space), "Migration already running", {
196
+ F: __dxlog_file2,
197
+ L: 44,
198
+ S: this,
199
+ A: [
200
+ "!this.running(space)",
201
+ "'Migration already running'"
202
+ ]
203
+ });
204
+ (0, import_invariant2.invariant)(this.versionProperty, "Migrations namespace not set", {
205
+ F: __dxlog_file2,
206
+ L: 45,
46
207
  S: this,
47
208
  A: [
48
209
  "this.versionProperty",
49
210
  "'Migrations namespace not set'"
50
211
  ]
51
212
  });
52
- (0, import_invariant.invariant)(space.state.get() === import_echo.SpaceState.READY, "Space not ready", {
53
- F: __dxlog_file,
54
- L: 41,
213
+ (0, import_invariant2.invariant)(space.state.get() === import_echo.SpaceState.READY, "Space not ready", {
214
+ F: __dxlog_file2,
215
+ L: 46,
55
216
  S: this,
56
217
  A: [
57
218
  "space.state.get() === SpaceState.READY",
@@ -65,30 +226,37 @@ var Migrations = class {
65
226
  if (currentIndex === targetIndex) {
66
227
  return false;
67
228
  }
229
+ this._state.running.push(space.key.toHex());
68
230
  if (targetIndex > currentIndex) {
69
231
  const migrations = this.migrations.slice(currentIndex, targetIndex);
70
232
  for (const migration of migrations) {
71
- await migration.up({
72
- space
233
+ const builder = new MigrationBuilder(space);
234
+ await migration.next({
235
+ space,
236
+ builder
73
237
  });
74
- space.properties[this.versionProperty] = migration.version;
75
- }
76
- } else {
77
- const migrations = this.migrations.slice(targetIndex, currentIndex);
78
- migrations.reverse();
79
- for (const migration of migrations) {
80
- await migration.down({
81
- space
238
+ builder.changeProperties((propertiesStructure) => {
239
+ (0, import_invariant2.invariant)(this.versionProperty, "Migrations namespace not set", {
240
+ F: __dxlog_file2,
241
+ L: 62,
242
+ S: this,
243
+ A: [
244
+ "this.versionProperty",
245
+ "'Migrations namespace not set'"
246
+ ]
247
+ });
248
+ propertiesStructure.data[this.versionProperty] = migration.version;
82
249
  });
83
- const index = this.migrations.indexOf(migration);
84
- space.properties[this.versionProperty] = this.migrations[index - 1]?.version;
250
+ await builder._commit();
85
251
  }
86
252
  }
253
+ this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);
87
254
  return true;
88
255
  }
89
256
  };
90
257
  // Annotate the CommonJS export names for ESM import in node:
91
258
  0 && (module.exports = {
259
+ MigrationBuilder,
92
260
  Migrations
93
261
  });
94
262
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/migrations.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Space, SpaceState } from '@dxos/client/echo';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\n// TODO(burdon): Merge with successor to serialization mechanism in braneframe/types.\n\nexport type MigrationContext = {\n space: Space;\n};\n\nexport type Migration = {\n version: string | number;\n up: (context: MigrationContext) => MaybePromise<void>;\n down: (context: MigrationContext) => MaybePromise<void>;\n};\n\nexport class Migrations {\n static namespace?: string;\n static migrations: Migration[] = [];\n\n static get versionProperty() {\n return this.namespace && `${this.namespace}.version`;\n }\n\n static get targetVersion() {\n return this.migrations[this.migrations.length - 1].version;\n }\n\n static define(namespace: string, migrations: Migration[]) {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n // TODO(wittjosiah): Multi-space migrations.\n static async migrate(space: Space, targetVersion?: string | number) {\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.READY, 'Space not ready');\n const currentVersion = space.properties[this.versionProperty];\n const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;\n const i = this.migrations.findIndex((m) => m.version === targetVersion);\n const targetIndex = i === -1 ? this.migrations.length : i + 1;\n if (currentIndex === targetIndex) {\n return false;\n }\n\n if (targetIndex > currentIndex) {\n const migrations = this.migrations.slice(currentIndex, targetIndex);\n for (const migration of migrations) {\n await migration.up({ space });\n space.properties[this.versionProperty] = migration.version;\n }\n } else {\n const migrations = this.migrations.slice(targetIndex, currentIndex);\n migrations.reverse();\n for (const migration of migrations) {\n await migration.down({ space });\n const index = this.migrations.indexOf(migration);\n space.properties[this.versionProperty] = this.migrations[index - 1]?.version;\n }\n }\n\n return true;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAIA,kBAAuC;AACvC,uBAA0B;;AAenB,IAAMA,aAAN,MAAMA;EAEX,OAAA;SAAOC,aAA0B,CAAA;;EAEjC,WAAWC,kBAAkB;AAC3B,WAAO,KAAKC,aAAa,GAAG,KAAKA,S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"versionProperty", "namespace", "targetVersion", "length", "version", "define", "migrate", "space", "invariant", "state", "get", "SpaceState", "READY", "currentVersion", "properties", "currentIndex", "findIndex", "m", "i", "targetIndex", "slice", "migration", "up", "reverse", "down", "index", "indexOf"]
3
+ "sources": ["../../../src/migration-builder.ts", "../../../src/migrations.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Doc, getHeads } from '@dxos/automerge/automerge';\nimport { type AnyDocumentId, type DocHandle, type Repo } from '@dxos/automerge/automerge-repo';\nimport { type Space } from '@dxos/client/echo';\nimport { CreateEpochRequest } from '@dxos/client/halo';\nimport { type AutomergeContext, ObjectCore } from '@dxos/echo-db';\nimport { encodeReference, type ObjectStructure, Reference, type SpaceDoc } from '@dxos/echo-protocol';\nimport { requireTypeReference, type S } from '@dxos/echo-schema';\nimport { invariant } from '@dxos/invariant';\nimport { type FlushRequest } from '@dxos/protocols/proto/dxos/echo/service';\nimport { type MaybePromise } from '@dxos/util';\n\nexport class MigrationBuilder {\n private readonly _repo: Repo;\n private readonly _automergeContext: AutomergeContext;\n private readonly _rootDoc: Doc<SpaceDoc>;\n\n // echoId -> automergeUrl\n private readonly _newLinks: Record<string, string> = {};\n private readonly _flushStates: FlushRequest.DocState[] = [];\n private readonly _deleteObjects: string[] = [];\n\n private _newRoot?: DocHandle<SpaceDoc> = undefined;\n\n constructor(private readonly _space: Space) {\n this._repo = this._space.db.coreDatabase.automerge.repo;\n this._automergeContext = this._space.db.coreDatabase.automerge;\n // TODO(wittjosiah): Accessing private API.\n this._rootDoc = (this._space.db.coreDatabase as any)._automergeDocLoader\n .getSpaceRootDocHandle()\n .docSync() as Doc<SpaceDoc>;\n }\n\n async findObject(id: string): Promise<ObjectStructure | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id]) as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n const doc = docHandle.docSync() as Doc<SpaceDoc>;\n return doc.objects?.[id];\n }\n\n async migrateObject(\n id: string,\n migrate: (objectStructure: ObjectStructure) => MaybePromise<{ schema: S.Schema<any>; props: any }>,\n ) {\n const objectStructure = await this.findObject(id);\n if (!objectStructure) {\n return;\n }\n\n const { schema, props } = await migrate(objectStructure);\n this._createObject({ id, schema, props });\n }\n\n async addObject(schema: S.Schema<any>, props: any) {\n const core = this._createObject({ schema, props });\n return core.id;\n }\n\n createReference(id: string) {\n return encodeReference(new Reference(id));\n }\n\n deleteObject(id: string) {\n this._deleteObjects.push(id);\n }\n\n changeProperties(changeFn: (properties: ObjectStructure) => void) {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n this._newRoot.change((doc: SpaceDoc) => {\n const propertiesStructure = doc.objects?.[this._space.properties.id];\n propertiesStructure && changeFn(propertiesStructure);\n });\n this._flushStates.push({\n documentId: this._newRoot.documentId,\n heads: getHeads(this._newRoot.docSync()),\n });\n }\n\n /**\n * @internal\n */\n async _commit() {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n await this._automergeContext.flush({\n states: this._flushStates,\n });\n\n // Create new epoch.\n await this._space.internal.createEpoch({\n migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,\n automergeRootUrl: this._newRoot.url,\n });\n }\n\n private _buildNewRoot() {\n const previousLinks = { ...(this._rootDoc.links ?? {}) };\n for (const id of this._deleteObjects) {\n delete previousLinks[id];\n }\n\n this._newRoot = this._repo.create<SpaceDoc>({\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: this._rootDoc.objects,\n links: {\n ...previousLinks,\n ...this._newLinks,\n },\n });\n this._flushStates.push({\n documentId: this._newRoot.documentId,\n heads: getHeads(this._newRoot.docSync()),\n });\n }\n\n private _createObject({ id, schema, props }: { id?: string; schema: S.Schema<any>; props: any }) {\n const core = new ObjectCore();\n if (id) {\n core.id = id;\n }\n\n core.initNewObject(props);\n core.setType(requireTypeReference(schema));\n const newHandle = this._repo.create<SpaceDoc>({\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [core.id]: core.getDoc(),\n },\n });\n this._newLinks[core.id] = newHandle.url;\n this._flushStates.push({\n documentId: newHandle.documentId,\n heads: getHeads(newHandle.docSync()),\n });\n\n return core;\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Space, create, SpaceState } from '@dxos/client/echo';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { MigrationBuilder } from './migration-builder';\n\nexport type MigrationContext = {\n space: Space;\n builder: MigrationBuilder;\n};\n\nexport type Migration = {\n version: string;\n next: (context: MigrationContext) => MaybePromise<void>;\n};\n\nexport class Migrations {\n static namespace?: string;\n static migrations: Migration[] = [];\n private static _state = create<{ running: string[] }>({ running: [] });\n\n static get versionProperty() {\n return this.namespace && `${this.namespace}.version`;\n }\n\n static get targetVersion() {\n return this.migrations[this.migrations.length - 1].version;\n }\n\n static running(space: Space) {\n return this._state.running.includes(space.key.toHex());\n }\n\n static define(namespace: string, migrations: Migration[]) {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n static async migrate(space: Space, targetVersion?: string | number) {\n invariant(!this.running(space), 'Migration already running');\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.READY, 'Space not ready');\n const currentVersion = space.properties[this.versionProperty];\n const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;\n const i = this.migrations.findIndex((m) => m.version === targetVersion);\n const targetIndex = i === -1 ? this.migrations.length : i + 1;\n if (currentIndex === targetIndex) {\n return false;\n }\n\n this._state.running.push(space.key.toHex());\n if (targetIndex > currentIndex) {\n const migrations = this.migrations.slice(currentIndex, targetIndex);\n for (const migration of migrations) {\n const builder = new MigrationBuilder(space);\n await migration.next({ space, builder });\n builder.changeProperties((propertiesStructure) => {\n invariant(this.versionProperty, 'Migrations namespace not set');\n propertiesStructure.data[this.versionProperty] = migration.version;\n });\n await builder._commit();\n }\n }\n this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);\n\n return true;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAIA,uBAAmC;AAGnC,kBAAmC;AACnC,qBAAkD;AAClD,2BAAgF;AAChF,yBAA6C;AAC7C,uBAA0B;ACP1B,kBAA+C;AAC/C,IAAAA,oBAA0B;;ADUnB,IAAMC,mBAAN,MAAMA;EAYXC,YAA6BC,QAAe;SAAfA,SAAAA;SANZC,YAAoC,CAAC;SACrCC,eAAwC,CAAA;SACxCC,iBAA2B,CAAA;SAEpCC,WAAiCC;AAGvC,SAAKC,QAAQ,KAAKN,OAAOO,GAAGC,aAAaC,UAAUC;AACnD,SAAKC,oBAAoB,KAAKX,OAAOO,GAAGC,aAAaC;AAErD,SAAKG,WAAY,KAAKZ,OAAOO,GAAGC,aAAqBK,oBAClDC,sBAAqB,EACrBC,QAAO;EACZ;EAEA,MAAMC,WAAWC,IAAkD;AACjE,UAAMC,aAAc,KAAKN,SAASO,QAAQF,EAAAA,KAAO,KAAKhB,UAAUgB,EAAAA;AAChE,UAAMG,YAAYF,cAAc,KAAKZ,MAAMe,KAAKH,UAAAA;AAChD,QAAI,CAACE,WAAW;AACd,aAAOf;IACT;AAEA,UAAMe,UAAUE,UAAS;AACzB,UAAMC,MAAMH,UAAUL,QAAO;AAC7B,WAAOQ,IAAIC,UAAUP,EAAAA;EACvB;EAEA,MAAMQ,cACJR,IACAS,SACA;AACA,UAAMC,kBAAkB,MAAM,KAAKX,WAAWC,EAAAA;AAC9C,QAAI,CAACU,iBAAiB;AACpB;IACF;AAEA,UAAM,EAAEC,QAAQC,MAAK,IAAK,MAAMH,QAAQC,eAAAA;AACxC,SAAKG,cAAc;MAAEb;MAAIW;MAAQC;IAAM,CAAA;EACzC;EAEA,MAAME,UAAUH,QAAuBC,OAAY;AACjD,UAAMG,OAAO,KAAKF,cAAc;MAAEF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_flushStates", "_deleteObjects", "_newRoot", "undefined", "_repo", "db", "coreDatabase", "automerge", "repo", "_automergeContext", "_rootDoc", "_automergeDocLoader", "getSpaceRootDocHandle", "docSync", "findObject", "id", "documentId", "links", "docHandle", "find", "whenReady", "doc", "objects", "migrateObject", "migrate", "objectStructure", "schema", "props", "_createObject", "addObject", "core", "createReference", "encodeReference", "Reference", "deleteObject", "push", "changeProperties", "changeFn", "_buildNewRoot", "invariant", "change", "propertiesStructure", "properties", "heads", "getHeads", "_commit", "flush", "states", "internal", "createEpoch", "migration", "CreateEpochRequest", "Migration", "REPLACE_AUTOMERGE_ROOT", "automergeRootUrl", "url", "previousLinks", "create", "access", "spaceKey", "key", "toHex", "ObjectCore", "initNewObject", "setType", "requireTypeReference", "newHandle", "getDoc", "Migrations", "migrations", "_state", "running", "versionProperty", "namespace", "targetVersion", "length", "version", "space", "includes", "define", "state", "get", "SpaceState", "READY", "currentVersion", "currentIndex", "findIndex", "m", "i", "targetIndex", "slice", "builder", "next", "data", "splice", "indexOf"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/sdk/migrations/src/migrations.ts":{"bytes":8236,"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/sdk/migrations/src/index.ts":{"bytes":501,"imports":[{"path":"packages/sdk/migrations/src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"packages/sdk/migrations/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":3895},"packages/sdk/migrations/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["Migrations"],"entryPoint":"packages/sdk/migrations/src/index.ts","inputs":{"packages/sdk/migrations/src/migrations.ts":{"bytesInOutput":2163},"packages/sdk/migrations/src/index.ts":{"bytesInOutput":0}},"bytes":2268}}}
1
+ {"inputs":{"packages/sdk/migrations/src/migration-builder.ts":{"bytes":17544,"imports":[{"path":"@dxos/automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/sdk/migrations/src/migrations.ts":{"bytes":9817,"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/sdk/migrations/src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"}],"format":"esm"},"packages/sdk/migrations/src/index.ts":{"bytes":698,"imports":[{"path":"packages/sdk/migrations/src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"},{"path":"packages/sdk/migrations/src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"packages/sdk/migrations/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13051},"packages/sdk/migrations/dist/lib/node/index.cjs":{"imports":[{"path":"@dxos/automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo-protocol","kind":"import-statement","external":true},{"path":"@dxos/echo-schema","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["MigrationBuilder","Migrations"],"entryPoint":"packages/sdk/migrations/src/index.ts","inputs":{"packages/sdk/migrations/src/migration-builder.ts":{"bytesInOutput":3936},"packages/sdk/migrations/src/index.ts":{"bytesInOutput":0},"packages/sdk/migrations/src/migrations.ts":{"bytesInOutput":2745}},"bytes":6859}}}
@@ -1,2 +1,4 @@
1
+ export type { ObjectStructure } from '@dxos/echo-protocol';
2
+ export * from './migration-builder';
1
3
  export * from './migrations';
2
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,YAAY,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,cAAc,qBAAqB,CAAC;AACpC,cAAc,cAAc,CAAC"}
@@ -0,0 +1,27 @@
1
+ import { type Space } from '@dxos/client/echo';
2
+ import { type ObjectStructure } from '@dxos/echo-protocol';
3
+ import { type S } from '@dxos/echo-schema';
4
+ import { type MaybePromise } from '@dxos/util';
5
+ export declare class MigrationBuilder {
6
+ private readonly _space;
7
+ private readonly _repo;
8
+ private readonly _automergeContext;
9
+ private readonly _rootDoc;
10
+ private readonly _newLinks;
11
+ private readonly _flushStates;
12
+ private readonly _deleteObjects;
13
+ private _newRoot?;
14
+ constructor(_space: Space);
15
+ findObject(id: string): Promise<ObjectStructure | undefined>;
16
+ migrateObject(id: string, migrate: (objectStructure: ObjectStructure) => MaybePromise<{
17
+ schema: S.Schema<any>;
18
+ props: any;
19
+ }>): Promise<void>;
20
+ addObject(schema: S.Schema<any>, props: any): Promise<string>;
21
+ createReference(id: string): import("@dxos/echo-protocol").EncodedReferenceObject;
22
+ deleteObject(id: string): void;
23
+ changeProperties(changeFn: (properties: ObjectStructure) => void): void;
24
+ private _buildNewRoot;
25
+ private _createObject;
26
+ }
27
+ //# sourceMappingURL=migration-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-builder.d.ts","sourceRoot":"","sources":["../../../src/migration-builder.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAG/C,OAAO,EAAmB,KAAK,eAAe,EAA4B,MAAM,qBAAqB,CAAC;AACtG,OAAO,EAAwB,KAAK,CAAC,EAAE,MAAM,mBAAmB,CAAC;AAGjE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,qBAAa,gBAAgB;IAYf,OAAO,CAAC,QAAQ,CAAC,MAAM;IAXnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAO;IAC7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAmB;IACrD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgB;IAGzC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA8B;IACxD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA+B;IAC5D,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgB;IAE/C,OAAO,CAAC,QAAQ,CAAC,CAAkC;gBAEtB,MAAM,EAAE,KAAK;IASpC,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;IAY5D,aAAa,CACjB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,CAAC,eAAe,EAAE,eAAe,KAAK,YAAY,CAAC;QAAE,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAAC,KAAK,EAAE,GAAG,CAAA;KAAE,CAAC;IAW9F,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,GAAG;IAKjD,eAAe,CAAC,EAAE,EAAE,MAAM;IAI1B,YAAY,CAAC,EAAE,EAAE,MAAM;IAIvB,gBAAgB,CAAC,QAAQ,EAAE,CAAC,UAAU,EAAE,eAAe,KAAK,IAAI;IAoChE,OAAO,CAAC,aAAa;IAsBrB,OAAO,CAAC,aAAa;CAwBtB"}
@@ -1,18 +1,21 @@
1
1
  import { type Space } from '@dxos/client/echo';
2
2
  import { type MaybePromise } from '@dxos/util';
3
+ import { MigrationBuilder } from './migration-builder';
3
4
  export type MigrationContext = {
4
5
  space: Space;
6
+ builder: MigrationBuilder;
5
7
  };
6
8
  export type Migration = {
7
- version: string | number;
8
- up: (context: MigrationContext) => MaybePromise<void>;
9
- down: (context: MigrationContext) => MaybePromise<void>;
9
+ version: string;
10
+ next: (context: MigrationContext) => MaybePromise<void>;
10
11
  };
11
12
  export declare class Migrations {
12
13
  static namespace?: string;
13
14
  static migrations: Migration[];
15
+ private static _state;
14
16
  static get versionProperty(): string | undefined;
15
- static get targetVersion(): string | number;
17
+ static get targetVersion(): string;
18
+ static running(space: Space): boolean;
16
19
  static define(namespace: string, migrations: Migration[]): void;
17
20
  static migrate(space: Space, targetVersion?: string | number): Promise<boolean>;
18
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../src/migrations.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,KAAK,EAAc,MAAM,mBAAmB,CAAC;AAE3D,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAI/C,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,KAAK,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC;IACzB,EAAE,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;IACtD,IAAI,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;CACzD,CAAC;AAEF,qBAAa,UAAU;IACrB,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,UAAU,EAAE,SAAS,EAAE,CAAM;IAEpC,MAAM,KAAK,eAAe,uBAEzB;IAED,MAAM,KAAK,aAAa,oBAEvB;IAED,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE;WAM3C,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM;CA6BnE"}
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../src/migrations.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,KAAK,EAAsB,MAAM,mBAAmB,CAAC;AAEnE,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,KAAK,CAAC;IACb,OAAO,EAAE,gBAAgB,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;CACzD,CAAC;AAEF,qBAAa,UAAU;IACrB,MAAM,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,UAAU,EAAE,SAAS,EAAE,CAAM;IACpC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAkD;IAEvE,MAAM,KAAK,eAAe,uBAEzB;IAED,MAAM,KAAK,aAAa,WAEvB;IAED,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK;IAI3B,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE;WAK3C,OAAO,CAAC,KAAK,EAAE,KAAK,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM;CA6BnE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/migrations",
3
- "version": "0.5.9-main.8359215",
3
+ "version": "0.5.9-main.89d55b2",
4
4
  "description": "",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -20,10 +20,15 @@
20
20
  "src"
21
21
  ],
22
22
  "dependencies": {
23
- "@dxos/invariant": "0.5.9-main.8359215",
24
- "@dxos/client": "0.5.9-main.8359215",
25
- "@dxos/echo-schema": "0.5.9-main.8359215",
26
- "@dxos/util": "0.5.9-main.8359215"
23
+ "@dxos/client": "0.5.9-main.89d55b2",
24
+ "@dxos/echo-db": "0.5.9-main.89d55b2",
25
+ "@dxos/echo-protocol": "0.5.9-main.89d55b2",
26
+ "@dxos/echo-schema": "0.5.9-main.89d55b2",
27
+ "@dxos/invariant": "0.5.9-main.89d55b2",
28
+ "@dxos/automerge": "0.5.9-main.89d55b2",
29
+ "@dxos/protocols": "0.5.9-main.89d55b2",
30
+ "@dxos/log": "0.5.9-main.89d55b2",
31
+ "@dxos/util": "0.5.9-main.89d55b2"
27
32
  },
28
33
  "devDependencies": {},
29
34
  "publishConfig": {
package/src/index.ts CHANGED
@@ -2,4 +2,7 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
+ export type { ObjectStructure } from '@dxos/echo-protocol';
6
+
7
+ export * from './migration-builder';
5
8
  export * from './migrations';
@@ -0,0 +1,157 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type Doc, getHeads } from '@dxos/automerge/automerge';
6
+ import { type AnyDocumentId, type DocHandle, type Repo } from '@dxos/automerge/automerge-repo';
7
+ import { type Space } from '@dxos/client/echo';
8
+ import { CreateEpochRequest } from '@dxos/client/halo';
9
+ import { type AutomergeContext, ObjectCore } from '@dxos/echo-db';
10
+ import { encodeReference, type ObjectStructure, Reference, type SpaceDoc } from '@dxos/echo-protocol';
11
+ import { requireTypeReference, type S } from '@dxos/echo-schema';
12
+ import { invariant } from '@dxos/invariant';
13
+ import { type FlushRequest } from '@dxos/protocols/proto/dxos/echo/service';
14
+ import { type MaybePromise } from '@dxos/util';
15
+
16
+ export class MigrationBuilder {
17
+ private readonly _repo: Repo;
18
+ private readonly _automergeContext: AutomergeContext;
19
+ private readonly _rootDoc: Doc<SpaceDoc>;
20
+
21
+ // echoId -> automergeUrl
22
+ private readonly _newLinks: Record<string, string> = {};
23
+ private readonly _flushStates: FlushRequest.DocState[] = [];
24
+ private readonly _deleteObjects: string[] = [];
25
+
26
+ private _newRoot?: DocHandle<SpaceDoc> = undefined;
27
+
28
+ constructor(private readonly _space: Space) {
29
+ this._repo = this._space.db.coreDatabase.automerge.repo;
30
+ this._automergeContext = this._space.db.coreDatabase.automerge;
31
+ // TODO(wittjosiah): Accessing private API.
32
+ this._rootDoc = (this._space.db.coreDatabase as any)._automergeDocLoader
33
+ .getSpaceRootDocHandle()
34
+ .docSync() as Doc<SpaceDoc>;
35
+ }
36
+
37
+ async findObject(id: string): Promise<ObjectStructure | undefined> {
38
+ const documentId = (this._rootDoc.links?.[id] || this._newLinks[id]) as AnyDocumentId | undefined;
39
+ const docHandle = documentId && this._repo.find(documentId);
40
+ if (!docHandle) {
41
+ return undefined;
42
+ }
43
+
44
+ await docHandle.whenReady();
45
+ const doc = docHandle.docSync() as Doc<SpaceDoc>;
46
+ return doc.objects?.[id];
47
+ }
48
+
49
+ async migrateObject(
50
+ id: string,
51
+ migrate: (objectStructure: ObjectStructure) => MaybePromise<{ schema: S.Schema<any>; props: any }>,
52
+ ) {
53
+ const objectStructure = await this.findObject(id);
54
+ if (!objectStructure) {
55
+ return;
56
+ }
57
+
58
+ const { schema, props } = await migrate(objectStructure);
59
+ this._createObject({ id, schema, props });
60
+ }
61
+
62
+ async addObject(schema: S.Schema<any>, props: any) {
63
+ const core = this._createObject({ schema, props });
64
+ return core.id;
65
+ }
66
+
67
+ createReference(id: string) {
68
+ return encodeReference(new Reference(id));
69
+ }
70
+
71
+ deleteObject(id: string) {
72
+ this._deleteObjects.push(id);
73
+ }
74
+
75
+ changeProperties(changeFn: (properties: ObjectStructure) => void) {
76
+ if (!this._newRoot) {
77
+ this._buildNewRoot();
78
+ }
79
+ invariant(this._newRoot, 'New root not created');
80
+
81
+ this._newRoot.change((doc: SpaceDoc) => {
82
+ const propertiesStructure = doc.objects?.[this._space.properties.id];
83
+ propertiesStructure && changeFn(propertiesStructure);
84
+ });
85
+ this._flushStates.push({
86
+ documentId: this._newRoot.documentId,
87
+ heads: getHeads(this._newRoot.docSync()),
88
+ });
89
+ }
90
+
91
+ /**
92
+ * @internal
93
+ */
94
+ async _commit() {
95
+ if (!this._newRoot) {
96
+ this._buildNewRoot();
97
+ }
98
+ invariant(this._newRoot, 'New root not created');
99
+
100
+ await this._automergeContext.flush({
101
+ states: this._flushStates,
102
+ });
103
+
104
+ // Create new epoch.
105
+ await this._space.internal.createEpoch({
106
+ migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,
107
+ automergeRootUrl: this._newRoot.url,
108
+ });
109
+ }
110
+
111
+ private _buildNewRoot() {
112
+ const previousLinks = { ...(this._rootDoc.links ?? {}) };
113
+ for (const id of this._deleteObjects) {
114
+ delete previousLinks[id];
115
+ }
116
+
117
+ this._newRoot = this._repo.create<SpaceDoc>({
118
+ access: {
119
+ spaceKey: this._space.key.toHex(),
120
+ },
121
+ objects: this._rootDoc.objects,
122
+ links: {
123
+ ...previousLinks,
124
+ ...this._newLinks,
125
+ },
126
+ });
127
+ this._flushStates.push({
128
+ documentId: this._newRoot.documentId,
129
+ heads: getHeads(this._newRoot.docSync()),
130
+ });
131
+ }
132
+
133
+ private _createObject({ id, schema, props }: { id?: string; schema: S.Schema<any>; props: any }) {
134
+ const core = new ObjectCore();
135
+ if (id) {
136
+ core.id = id;
137
+ }
138
+
139
+ core.initNewObject(props);
140
+ core.setType(requireTypeReference(schema));
141
+ const newHandle = this._repo.create<SpaceDoc>({
142
+ access: {
143
+ spaceKey: this._space.key.toHex(),
144
+ },
145
+ objects: {
146
+ [core.id]: core.getDoc(),
147
+ },
148
+ });
149
+ this._newLinks[core.id] = newHandle.url;
150
+ this._flushStates.push({
151
+ documentId: newHandle.documentId,
152
+ heads: getHeads(newHandle.docSync()),
153
+ });
154
+
155
+ return core;
156
+ }
157
+ }
@@ -5,7 +5,7 @@
5
5
  import { expect } from 'chai';
6
6
 
7
7
  import { Client } from '@dxos/client';
8
- import { type Space } from '@dxos/client/echo';
8
+ import { Filter, type Space } from '@dxos/client/echo';
9
9
  import { TestBuilder } from '@dxos/client/testing';
10
10
  import { Expando, create } from '@dxos/echo-schema';
11
11
  import { describe, test, beforeEach, beforeAll, afterAll } from '@dxos/test';
@@ -14,41 +14,32 @@ import { Migrations } from './migrations';
14
14
 
15
15
  Migrations.define('test', [
16
16
  {
17
- version: 1,
18
- up: async ({ space }) => {
19
- space.db.add(create(Expando, { namespace: 'test', count: 1 }));
20
- },
21
- down: async ({ space }) => {
22
- const { objects } = await space.db.query({ namespace: 'test' }).run();
23
- for (const object of objects) {
24
- space.db.remove(object);
25
- }
17
+ version: '1970-01-01',
18
+ next: async ({ builder }) => {
19
+ await builder.addObject(Expando, { namespace: 'test', count: 1 });
26
20
  },
27
21
  },
28
22
  {
29
- version: 2,
30
- up: async ({ space }) => {
23
+ version: '1970-01-02',
24
+ next: async ({ space, builder }) => {
31
25
  const { objects } = await space.db.query({ namespace: 'test' }).run();
32
26
  for (const object of objects) {
33
- object.count = 2;
27
+ await builder.migrateObject(object.id, ({ data }) => ({
28
+ schema: Expando,
29
+ props: { namespace: data.namespace, count: 2 },
30
+ }));
34
31
  }
35
32
  },
36
- down: async () => {
37
- // No-op.
38
- },
39
33
  },
40
34
  {
41
- version: 3,
42
- up: async ({ space }) => {
43
- const { objects } = await space.db.query({ namespace: 'test' }).run();
44
- for (const object of objects) {
45
- object.count *= 3;
46
- }
47
- },
48
- down: async ({ space }) => {
35
+ version: '1970-01-03',
36
+ next: async ({ space, builder }) => {
49
37
  const { objects } = await space.db.query({ namespace: 'test' }).run();
50
38
  for (const object of objects) {
51
- object.count /= 3;
39
+ await builder.migrateObject(object.id, ({ data }) => ({
40
+ schema: Expando,
41
+ props: { namespace: data.namespace, count: data.count * 3 },
42
+ }));
52
43
  }
53
44
  },
54
45
  },
@@ -75,47 +66,34 @@ describe('Migrations', () => {
75
66
 
76
67
  test('if no migrations have been run before, runs all migrations', async () => {
77
68
  await Migrations.migrate(space);
78
- const { objects } = await space.db.query({ namespace: 'test' }).run();
69
+ const { objects } = await space.db.query(Filter.schema(Expando, { namespace: 'test' })).run();
79
70
  expect(objects).to.have.length(1);
80
71
  expect(objects[0].count).to.equal(6);
81
- expect(space.properties['test.version']).to.equal(3);
72
+ expect(space.properties['test.version']).to.equal('1970-01-03');
82
73
  });
83
74
 
84
75
  test('if some migrations have been run before, runs only the remaining migrations', async () => {
85
- space.properties['test.version'] = 2;
76
+ space.properties['test.version'] = '1970-01-02';
86
77
  space.db.add(create(Expando, { namespace: 'test', count: 5 }));
87
78
  await Migrations.migrate(space);
88
- const { objects } = await space.db.query({ namespace: 'test' }).run();
79
+ const { objects } = await space.db.query(Filter.schema(Expando, { namespace: 'test' })).run();
89
80
  expect(objects).to.have.length(1);
90
81
  expect(objects[0].count).to.equal(15);
91
- expect(space.properties['test.version']).to.equal(3);
82
+ expect(space.properties['test.version']).to.equal('1970-01-03');
92
83
  });
93
84
 
94
85
  test('if all migrations have been run before, does nothing', async () => {
95
- space.properties['test.version'] = 3;
86
+ space.properties['test.version'] = '1970-01-03';
96
87
  await Migrations.migrate(space);
97
- const { objects } = await space.db.query({ namespace: 'test' }).run();
88
+ const { objects } = await space.db.query(Filter.schema(Expando, { namespace: 'test' })).run();
98
89
  expect(objects).to.have.length(0);
99
90
  });
100
91
 
101
92
  test('if target version is specified, runs only the migrations up to that version', async () => {
102
- await Migrations.migrate(space, 2);
103
- const { objects } = await space.db.query({ namespace: 'test' }).run();
93
+ await Migrations.migrate(space, '1970-01-02');
94
+ const { objects } = await space.db.query(Filter.schema(Expando, { namespace: 'test' })).run();
104
95
  expect(objects).to.have.length(1);
105
96
  expect(objects[0].count).to.equal(2);
106
- expect(space.properties['test.version']).to.equal(2);
107
- });
108
-
109
- test('if target version is specified and is lower than current version, runs the down migrations', async () => {
110
- await Migrations.migrate(space);
111
- const beforeDowngrade = await space.db.query({ namespace: 'test' }).run();
112
- expect(beforeDowngrade.objects).to.have.length(1);
113
- expect(beforeDowngrade.objects[0].count).to.equal(6);
114
- expect(space.properties['test.version']).to.equal(3);
115
- await Migrations.migrate(space, 1);
116
- const afterDowngrade = await space.db.query({ namespace: 'test' }).run();
117
- expect(afterDowngrade.objects).to.have.length(1);
118
- expect(afterDowngrade.objects[0].count).to.equal(2);
119
- expect(space.properties['test.version']).to.equal(1);
97
+ expect(space.properties['test.version']).to.equal('1970-01-02');
120
98
  });
121
99
  });
package/src/migrations.ts CHANGED
@@ -2,25 +2,26 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { type Space, SpaceState } from '@dxos/client/echo';
5
+ import { type Space, create, SpaceState } from '@dxos/client/echo';
6
6
  import { invariant } from '@dxos/invariant';
7
7
  import { type MaybePromise } from '@dxos/util';
8
8
 
9
- // TODO(burdon): Merge with successor to serialization mechanism in braneframe/types.
9
+ import { MigrationBuilder } from './migration-builder';
10
10
 
11
11
  export type MigrationContext = {
12
12
  space: Space;
13
+ builder: MigrationBuilder;
13
14
  };
14
15
 
15
16
  export type Migration = {
16
- version: string | number;
17
- up: (context: MigrationContext) => MaybePromise<void>;
18
- down: (context: MigrationContext) => MaybePromise<void>;
17
+ version: string;
18
+ next: (context: MigrationContext) => MaybePromise<void>;
19
19
  };
20
20
 
21
21
  export class Migrations {
22
22
  static namespace?: string;
23
23
  static migrations: Migration[] = [];
24
+ private static _state = create<{ running: string[] }>({ running: [] });
24
25
 
25
26
  static get versionProperty() {
26
27
  return this.namespace && `${this.namespace}.version`;
@@ -30,13 +31,17 @@ export class Migrations {
30
31
  return this.migrations[this.migrations.length - 1].version;
31
32
  }
32
33
 
34
+ static running(space: Space) {
35
+ return this._state.running.includes(space.key.toHex());
36
+ }
37
+
33
38
  static define(namespace: string, migrations: Migration[]) {
34
39
  this.namespace = namespace;
35
40
  this.migrations = migrations;
36
41
  }
37
42
 
38
- // TODO(wittjosiah): Multi-space migrations.
39
43
  static async migrate(space: Space, targetVersion?: string | number) {
44
+ invariant(!this.running(space), 'Migration already running');
40
45
  invariant(this.versionProperty, 'Migrations namespace not set');
41
46
  invariant(space.state.get() === SpaceState.READY, 'Space not ready');
42
47
  const currentVersion = space.properties[this.versionProperty];
@@ -47,21 +52,20 @@ export class Migrations {
47
52
  return false;
48
53
  }
49
54
 
55
+ this._state.running.push(space.key.toHex());
50
56
  if (targetIndex > currentIndex) {
51
57
  const migrations = this.migrations.slice(currentIndex, targetIndex);
52
58
  for (const migration of migrations) {
53
- await migration.up({ space });
54
- space.properties[this.versionProperty] = migration.version;
55
- }
56
- } else {
57
- const migrations = this.migrations.slice(targetIndex, currentIndex);
58
- migrations.reverse();
59
- for (const migration of migrations) {
60
- await migration.down({ space });
61
- const index = this.migrations.indexOf(migration);
62
- space.properties[this.versionProperty] = this.migrations[index - 1]?.version;
59
+ const builder = new MigrationBuilder(space);
60
+ await migration.next({ space, builder });
61
+ builder.changeProperties((propertiesStructure) => {
62
+ invariant(this.versionProperty, 'Migrations namespace not set');
63
+ propertiesStructure.data[this.versionProperty] = migration.version;
64
+ });
65
+ await builder._commit();
63
66
  }
64
67
  }
68
+ this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);
65
69
 
66
70
  return true;
67
71
  }