@dxos/migrations 0.8.4-main.ead640a → 0.8.4-main.effb148878

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,8 +1,105 @@
1
- MIT License
2
- Copyright (c) 2022 DXOS
1
+ # Functional Source License, Version 1.1, ALv2 Future License
3
2
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ ## Abbreviation
5
4
 
6
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ FSL-1.1-Apache-2.0
7
6
 
8
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,9 +1,9 @@
1
- # @dxos/echo-signals
1
+ # @dxos/migrations
2
2
 
3
3
  ## Installation
4
4
 
5
5
  ```bash
6
- pnpm i @dxos/echo-signals
6
+ pnpm i @dxos/migrations
7
7
  ```
8
8
 
9
9
  ## DXOS Resources
@@ -16,4 +16,4 @@ pnpm i @dxos/echo-signals
16
16
 
17
17
  Your ideas, issues, and code are most welcome. Please take a look at our [community code of conduct](https://github.com/dxos/dxos/blob/main/CODE_OF_CONDUCT.md), the [issue guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-issues), and the [PR contribution guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-prs).
18
18
 
19
- License: [MIT](./LICENSE) Copyright 2022 © DXOS
19
+ License: [FSL-1.1-Apache-2.0](./LICENSE) Copyright 2022 © DXOS
@@ -1,25 +1,27 @@
1
1
  // src/migration-builder.ts
2
2
  import { next as A } from "@automerge/automerge";
3
3
  import { CreateEpochRequest } from "@dxos/client/halo";
4
- import { requireTypeReference } from "@dxos/echo/internal";
5
4
  import { ObjectCore, migrateDocument } from "@dxos/echo-db";
6
- import { Reference, SpaceDocVersion, encodeReference } from "@dxos/echo-protocol";
5
+ import { EncodedReference, SpaceDocVersion } from "@dxos/echo-protocol";
6
+ import { getSchemaURI } from "@dxos/echo/internal";
7
+ import * as Type from "@dxos/echo/Type";
7
8
  import { invariant } from "@dxos/invariant";
8
- function _define_property(obj, key, value) {
9
- if (key in obj) {
10
- Object.defineProperty(obj, key, {
11
- value,
12
- enumerable: true,
13
- configurable: true,
14
- writable: true
15
- });
16
- } else {
17
- obj[key] = value;
18
- }
19
- return obj;
20
- }
9
+ import { EchoURI, ObjectId } from "@dxos/keys";
21
10
  var __dxlog_file = "/__w/dxos/dxos/packages/sdk/migrations/src/migration-builder.ts";
22
11
  var MigrationBuilder = class {
12
+ _space;
13
+ _repo;
14
+ _rootDoc;
15
+ // echoUri -> automergeUrl
16
+ _newLinks = {};
17
+ _flushIds = [];
18
+ _deleteObjects = [];
19
+ _newRoot = void 0;
20
+ constructor(_space) {
21
+ this._space = _space;
22
+ this._repo = this._space.internal.db.coreDatabase._repo;
23
+ this._rootDoc = this._space.internal.db.coreDatabase._automergeDocLoader.getSpaceRootDocHandle().doc();
24
+ }
23
25
  async findObject(id) {
24
26
  const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString();
25
27
  const docHandle = documentId && this._repo.find(documentId);
@@ -35,17 +37,10 @@ var MigrationBuilder = class {
35
37
  if (!objectStructure) {
36
38
  return;
37
39
  }
38
- const { schema, props } = await migrate(objectStructure);
40
+ const { type, props } = await migrate(objectStructure);
41
+ const schema = Type.getSchema(type);
39
42
  const oldHandle = await this._findObjectContainingHandle(id);
40
- invariant(oldHandle, void 0, {
41
- F: __dxlog_file,
42
- L: 84,
43
- S: this,
44
- A: [
45
- "oldHandle",
46
- ""
47
- ]
48
- });
43
+ invariant(oldHandle, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 61, S: this, A: ["oldHandle", ""] });
49
44
  const newState = {
50
45
  version: SpaceDocVersion.CURRENT,
51
46
  access: {
@@ -54,7 +49,7 @@ var MigrationBuilder = class {
54
49
  objects: {
55
50
  [id]: {
56
51
  system: {
57
- type: encodeReference(requireTypeReference(schema))
52
+ type: EncodedReference.fromURI(getSchemaURI(schema))
58
53
  },
59
54
  data: props,
60
55
  meta: {
@@ -65,58 +60,50 @@ var MigrationBuilder = class {
65
60
  };
66
61
  const migratedDoc = migrateDocument(oldHandle.doc(), newState);
67
62
  const newHandle = this._repo.import(A.save(migratedDoc));
63
+ await newHandle.whenReady();
64
+ invariant(newHandle.url, "Migrated document URL not available after whenReady", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 82, S: this, A: ["newHandle.url", "'Migrated document URL not available after whenReady'"] });
68
65
  this._newLinks[id] = newHandle.url;
69
- this._addHandleToFlushList(newHandle);
66
+ this._addHandleToFlushList(newHandle.documentId);
70
67
  }
71
- async addObject(schema, props) {
72
- const core = this._createObject({
73
- schema,
68
+ async addObject(type, props) {
69
+ const resolved = Type.getSchema(type);
70
+ const core = await this._createObject({
71
+ schema: resolved,
74
72
  props
75
73
  });
76
74
  return core.id;
77
75
  }
78
76
  createReference(id) {
79
- return encodeReference(Reference.localObjectReference(id));
77
+ invariant(ObjectId.isValid(id), "Invalid ObjectId.", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 95, S: this, A: ["ObjectId.isValid(id)", "'Invalid ObjectId.'"] });
78
+ return EncodedReference.fromURI(EchoURI.make({
79
+ objectId: id
80
+ }));
80
81
  }
81
82
  deleteObject(id) {
82
83
  this._deleteObjects.push(id);
83
84
  }
84
- changeProperties(changeFn) {
85
+ async changeProperties(changeFn) {
85
86
  if (!this._newRoot) {
86
- this._buildNewRoot();
87
+ await this._buildNewRoot();
87
88
  }
88
- invariant(this._newRoot, "New root not created", {
89
- F: __dxlog_file,
90
- L: 126,
91
- S: this,
92
- A: [
93
- "this._newRoot",
94
- "'New root not created'"
95
- ]
96
- });
89
+ invariant(this._newRoot, "New root not created", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 107, S: this, A: ["this._newRoot", "'New root not created'"] });
97
90
  this._newRoot.change((doc) => {
98
91
  const propertiesStructure = doc.objects?.[this._space.properties.id];
99
92
  propertiesStructure && changeFn(propertiesStructure);
100
93
  });
101
- this._addHandleToFlushList(this._newRoot);
94
+ await this._newRoot.whenReady();
95
+ this._addHandleToFlushList(this._newRoot.documentId);
102
96
  }
103
97
  /**
104
98
  * @internal
105
99
  */
106
100
  async _commit() {
107
101
  if (!this._newRoot) {
108
- this._buildNewRoot();
102
+ await this._buildNewRoot();
109
103
  }
110
- invariant(this._newRoot, "New root not created", {
111
- F: __dxlog_file,
112
- L: 142,
113
- S: this,
114
- A: [
115
- "this._newRoot",
116
- "'New root not created'"
117
- ]
118
- });
104
+ invariant(this._newRoot, "New root not created", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 121, S: this, A: ["this._newRoot", "'New root not created'"] });
119
105
  await this._space.db.flush();
106
+ invariant(this._newRoot.url, "New root URL not available", { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 124, S: this, A: ["this._newRoot.url", "'New root URL not available'"] });
120
107
  await this._space.internal.createEpoch({
121
108
  migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,
122
109
  automergeRootUrl: this._newRoot.url
@@ -131,7 +118,7 @@ var MigrationBuilder = class {
131
118
  await docHandle.whenReady();
132
119
  return docHandle;
133
120
  }
134
- _buildNewRoot() {
121
+ async _buildNewRoot() {
135
122
  const links = {
136
123
  ...this._rootDoc.links ?? {}
137
124
  };
@@ -149,15 +136,16 @@ var MigrationBuilder = class {
149
136
  objects: this._rootDoc.objects,
150
137
  links
151
138
  });
152
- this._addHandleToFlushList(this._newRoot);
139
+ await this._newRoot.whenReady();
140
+ this._addHandleToFlushList(this._newRoot.documentId);
153
141
  }
154
- _createObject({ id, schema, props }) {
142
+ async _createObject({ id, schema, props }) {
155
143
  const core = new ObjectCore();
156
144
  if (id) {
157
145
  core.id = id;
158
146
  }
159
147
  core.initNewObject(props);
160
- core.setType(requireTypeReference(schema));
148
+ core.setType(EncodedReference.fromURI(getSchemaURI(schema)));
161
149
  const newHandle = this._repo.create({
162
150
  version: SpaceDocVersion.CURRENT,
163
151
  access: {
@@ -167,49 +155,29 @@ var MigrationBuilder = class {
167
155
  [core.id]: core.getDoc()
168
156
  }
169
157
  });
158
+ await newHandle.whenReady();
170
159
  this._newLinks[core.id] = newHandle.url;
171
- this._addHandleToFlushList(newHandle);
160
+ this._addHandleToFlushList(newHandle.documentId);
172
161
  return core;
173
162
  }
174
- _addHandleToFlushList(handle) {
175
- this._flushIds.push(handle.documentId);
176
- }
177
- constructor(_space) {
178
- _define_property(this, "_space", void 0);
179
- _define_property(this, "_repo", void 0);
180
- _define_property(this, "_rootDoc", void 0);
181
- _define_property(this, "_newLinks", void 0);
182
- _define_property(this, "_flushIds", void 0);
183
- _define_property(this, "_deleteObjects", void 0);
184
- _define_property(this, "_newRoot", void 0);
185
- this._space = _space;
186
- this._newLinks = {};
187
- this._flushIds = [];
188
- this._deleteObjects = [];
189
- this._newRoot = void 0;
190
- this._repo = this._space.db.coreDatabase._repo;
191
- this._rootDoc = this._space.db.coreDatabase._automergeDocLoader.getSpaceRootDocHandle().doc();
163
+ _addHandleToFlushList(id) {
164
+ this._flushIds.push(id);
192
165
  }
193
166
  };
194
167
 
195
168
  // src/migrations.ts
196
- import { SpaceState, live } from "@dxos/client/echo";
169
+ import { Atom } from "@effect-atom/atom";
170
+ import * as Registry from "@effect-atom/atom/Registry";
171
+ import { SpaceState } from "@dxos/client/echo";
197
172
  import { invariant as invariant2 } from "@dxos/invariant";
198
- function _define_property2(obj, key, value) {
199
- if (key in obj) {
200
- Object.defineProperty(obj, key, {
201
- value,
202
- enumerable: true,
203
- configurable: true,
204
- writable: true
205
- });
206
- } else {
207
- obj[key] = value;
208
- }
209
- return obj;
210
- }
211
173
  var __dxlog_file2 = "/__w/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
212
174
  var Migrations = class {
175
+ static namespace;
176
+ static migrations = [];
177
+ static _registry = Registry.make();
178
+ static _stateAtom = Atom.make({
179
+ running: []
180
+ }).pipe(Atom.keepAlive);
213
181
  static get versionProperty() {
214
182
  return this.namespace && `${this.namespace}.version`;
215
183
  }
@@ -217,40 +185,17 @@ var Migrations = class {
217
185
  return this.migrations[this.migrations.length - 1]?.version;
218
186
  }
219
187
  static running(space) {
220
- return this._state.running.includes(space.key.toHex());
188
+ const state = this._registry.get(this._stateAtom);
189
+ return state.running.includes(space.key.toHex());
221
190
  }
222
191
  static define(namespace, migrations) {
223
192
  this.namespace = namespace;
224
193
  this.migrations = migrations;
225
194
  }
226
195
  static async migrate(space, targetVersion) {
227
- invariant2(!this.running(space), "Migration already running", {
228
- F: __dxlog_file2,
229
- L: 44,
230
- S: this,
231
- A: [
232
- "!this.running(space)",
233
- "'Migration already running'"
234
- ]
235
- });
236
- invariant2(this.versionProperty, "Migrations namespace not set", {
237
- F: __dxlog_file2,
238
- L: 45,
239
- S: this,
240
- A: [
241
- "this.versionProperty",
242
- "'Migrations namespace not set'"
243
- ]
244
- });
245
- invariant2(space.state.get() === SpaceState.SPACE_READY, "Space not ready", {
246
- F: __dxlog_file2,
247
- L: 46,
248
- S: this,
249
- A: [
250
- "space.state.get() === SpaceState.SPACE_READY",
251
- "'Space not ready'"
252
- ]
253
- });
196
+ invariant2(!this.running(space), "Migration already running", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 31, S: this, A: ["!this.running(space)", "'Migration already running'"] });
197
+ invariant2(this.versionProperty, "Migrations namespace not set", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 32, S: this, A: ["this.versionProperty", "'Migrations namespace not set'"] });
198
+ invariant2(space.state.get() === SpaceState.SPACE_READY, "Space not ready", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 33, S: this, A: ["space.state.get() === SpaceState.SPACE_READY", "'Space not ready'"] });
254
199
  const currentVersion = space.properties[this.versionProperty];
255
200
  const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;
256
201
  const i = this.migrations.findIndex((m) => m.version === targetVersion);
@@ -258,7 +203,14 @@ var Migrations = class {
258
203
  if (currentIndex === targetIndex) {
259
204
  return false;
260
205
  }
261
- this._state.running.push(space.key.toHex());
206
+ const spaceKey = space.key.toHex();
207
+ const currentState = this._registry.get(this._stateAtom);
208
+ this._registry.set(this._stateAtom, {
209
+ running: [
210
+ ...currentState.running,
211
+ spaceKey
212
+ ]
213
+ });
262
214
  if (targetIndex > currentIndex) {
263
215
  const migrations = this.migrations.slice(currentIndex, targetIndex);
264
216
  for (const migration of migrations) {
@@ -267,30 +219,20 @@ var Migrations = class {
267
219
  space,
268
220
  builder
269
221
  });
270
- builder.changeProperties((propertiesStructure) => {
271
- invariant2(this.versionProperty, "Migrations namespace not set", {
272
- F: __dxlog_file2,
273
- L: 62,
274
- S: this,
275
- A: [
276
- "this.versionProperty",
277
- "'Migrations namespace not set'"
278
- ]
279
- });
222
+ await builder.changeProperties((propertiesStructure) => {
223
+ invariant2(this.versionProperty, "Migrations namespace not set", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 58, S: this, A: ["this.versionProperty", "'Migrations namespace not set'"] });
280
224
  propertiesStructure.data[this.versionProperty] = migration.version;
281
225
  });
282
226
  await builder._commit();
283
227
  }
284
228
  }
285
- this._state.running.splice(this._state.running.indexOf(space.key.toHex()), 1);
229
+ const finalState = this._registry.get(this._stateAtom);
230
+ this._registry.set(this._stateAtom, {
231
+ running: finalState.running.filter((key) => key !== spaceKey)
232
+ });
286
233
  return true;
287
234
  }
288
235
  };
289
- _define_property2(Migrations, "namespace", void 0);
290
- _define_property2(Migrations, "migrations", []);
291
- _define_property2(Migrations, "_state", live({
292
- running: []
293
- }));
294
236
  export {
295
237
  MigrationBuilder,
296
238
  Migrations
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/migration-builder.ts", "../../../src/migrations.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A, type Doc } from '@automerge/automerge';\nimport { type AnyDocumentId, type DocumentId } from '@automerge/automerge-repo';\nimport type * as Schema from 'effect/Schema';\n\nimport { type Space } from '@dxos/client/echo';\nimport { CreateEpochRequest } from '@dxos/client/halo';\nimport { requireTypeReference } from '@dxos/echo/internal';\nimport { type DocHandleProxy, ObjectCore, type RepoProxy, migrateDocument } from '@dxos/echo-db';\nimport {\n type DatabaseDirectory,\n type ObjectStructure,\n Reference,\n SpaceDocVersion,\n encodeReference,\n} from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\n/*\n\nConsidering a better API for this:\n\n```ts\nconst migration = space.db.beginMigration(); // all actions are not visible to queries and are only applied once you call `apply`\n\nmigration.applyObjectMigration(defineMigration(From, To, { ... }));\n\nmigration.delete(id);\nmigration.add(obj);\n\nawait migration.apply(); // Will create new epoch.\n```\n\n*/\n\n// TODO(dmaretskyi): We no longer need to hook into ECHO internals, with the changes to echo APIs.\nexport class MigrationBuilder {\n private readonly _repo: RepoProxy;\n private readonly _rootDoc: Doc<DatabaseDirectory>;\n\n // echoId -> automergeUrl\n private readonly _newLinks: Record<string, string> = {};\n private readonly _flushIds: DocumentId[] = [];\n private readonly _deleteObjects: string[] = [];\n\n private _newRoot?: DocHandleProxy<DatabaseDirectory> = undefined;\n\n constructor(private readonly _space: Space) {\n this._repo = this._space.db.coreDatabase._repo;\n // TODO(wittjosiah): Accessing private API.\n this._rootDoc = (this._space.db.coreDatabase as any)._automergeDocLoader\n .getSpaceRootDocHandle()\n .doc() as Doc<DatabaseDirectory>;\n }\n\n async findObject(id: string): Promise<ObjectStructure | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() 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.doc() as Doc<DatabaseDirectory>;\n return doc.objects?.[id];\n }\n\n async migrateObject(\n id: string,\n migrate: (objectStructure: ObjectStructure) => MaybePromise<{ schema: Schema.Schema.AnyNoContext; props: any }>,\n ): Promise<void> {\n const objectStructure = await this.findObject(id);\n if (!objectStructure) {\n return;\n }\n\n const { schema, props } = await migrate(objectStructure);\n\n const oldHandle = await this._findObjectContainingHandle(id);\n invariant(oldHandle);\n\n const newState: DatabaseDirectory = {\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [id]: {\n system: {\n type: encodeReference(requireTypeReference(schema)),\n },\n data: props,\n meta: {\n keys: [],\n },\n },\n },\n };\n const migratedDoc = migrateDocument(oldHandle.doc() as Doc<DatabaseDirectory>, newState);\n const newHandle = this._repo.import<DatabaseDirectory>(A.save(migratedDoc));\n this._newLinks[id] = newHandle.url;\n this._addHandleToFlushList(newHandle);\n }\n\n async addObject(schema: Schema.Schema.AnyNoContext, props: any): Promise<string> {\n const core = this._createObject({ schema, props });\n return core.id;\n }\n\n createReference(id: string) {\n return encodeReference(Reference.localObjectReference(id));\n }\n\n deleteObject(id: string): void {\n this._deleteObjects.push(id);\n }\n\n changeProperties(changeFn: (properties: ObjectStructure) => void): void {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n this._newRoot.change((doc: DatabaseDirectory) => {\n const propertiesStructure = doc.objects?.[this._space.properties.id];\n propertiesStructure && changeFn(propertiesStructure);\n });\n this._addHandleToFlushList(this._newRoot);\n }\n\n /**\n * @internal\n */\n async _commit(): Promise<void> {\n if (!this._newRoot) {\n this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n await this._space.db.flush();\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 async _findObjectContainingHandle(id: string): Promise<DocHandleProxy<DatabaseDirectory> | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n return docHandle;\n }\n\n private _buildNewRoot(): void {\n const links = { ...(this._rootDoc.links ?? {}) };\n for (const id of this._deleteObjects) {\n delete links[id];\n }\n\n for (const [id, url] of Object.entries(this._newLinks)) {\n links[id] = new A.RawString(url);\n }\n\n this._newRoot = this._repo.create<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: this._rootDoc.objects,\n links,\n });\n this._addHandleToFlushList(this._newRoot);\n }\n\n private _createObject({\n id,\n schema,\n props,\n }: {\n id?: string;\n schema: Schema.Schema.AnyNoContext;\n props: any;\n }): ObjectCore {\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<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [core.id]: core.getDoc() as ObjectStructure,\n },\n });\n this._newLinks[core.id] = newHandle.url;\n this._addHandleToFlushList(newHandle);\n\n return core;\n }\n\n private _addHandleToFlushList(handle: DocHandleProxy<any>): void {\n this._flushIds.push(handle.documentId);\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Space, SpaceState, live } 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 = live<{ 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): boolean {\n return this._state.running.includes(space.key.toHex());\n }\n\n static define(namespace: string, migrations: Migration[]): void {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n static async migrate(space: Space, targetVersion?: string | number): Promise<boolean> {\n invariant(!this.running(space), 'Migration already running');\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.SPACE_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,SAASA,QAAQC,SAAmB;AAKpC,SAASC,0BAA0B;AACnC,SAASC,4BAA4B;AACrC,SAA8BC,YAA4BC,uBAAuB;AACjF,SAGEC,WACAC,iBACAC,uBACK;AACP,SAASC,iBAAiB;;;;;;;;;;;;;;;AAqBnB,IAAMC,mBAAN,MAAMA;EAmBX,MAAMC,WAAWC,IAAkD;AACjE,UAAMC,cAAc,KAAKC,SAASC,QAAQH,EAAAA,KAAO,KAAKI,UAAUJ,EAAAA,IAAMK,SAAAA;AACtE,UAAMC,YAAYL,cAAc,KAAKM,MAAMC,KAAKP,UAAAA;AAChD,QAAI,CAACK,WAAW;AACd,aAAOG;IACT;AAEA,UAAMH,UAAUI,UAAS;AACzB,UAAMC,MAAML,UAAUK,IAAG;AACzB,WAAOA,IAAIC,UAAUZ,EAAAA;EACvB;EAEA,MAAMa,cACJb,IAC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KAAK,KAAKlC,eAAe,IAAI4B,UAAUvB;QAC7D,CAAA;AACA,cAAMwB,QAAQM,QAAO;MACvB;IACF;AACA,SAAK3B,OAAOF,QAAQ8B,OAAO,KAAK5B,OAAOF,QAAQ+B,QAAQ9B,MAAMG,IAAIC,MAAK,CAAA,GAAK,CAAA;AAE3E,WAAO;EACT;AACF;AAlDE2B,kBADWvC,YACJE,aAAP,MAAA;AACAqC,kBAFWvC,YAEJI,cAA0B,CAAA,CAAE;AACnCmC,kBAHWvC,YAGIS,UAAS+B,KAA4B;EAAEjC,SAAS,CAAA;AAAG,CAAA,CAAA;",
6
- "names": ["next", "A", "CreateEpochRequest", "requireTypeReference", "ObjectCore", "migrateDocument", "Reference", "SpaceDocVersion", "encodeReference", "invariant", "MigrationBuilder", "findObject", "id", "documentId", "_rootDoc", "links", "_newLinks", "toString", "docHandle", "_repo", "find", "undefined", "whenReady", "doc", "objects", "migrateObject", "migrate", "objectStructure", "schema", "props", "oldHandle", "_findObjectContainingHandle", "newState", "version", "CURRENT", "access", "spaceKey", "_space", "key", "toHex", "system", "type", "data", "meta", "keys", "migratedDoc", "newHandle", "import", "save", "url", "_addHandleToFlushList", "addObject", "core", "_createObject", "createReference", "localObjectReference", "deleteObject", "_deleteObjects", "push", "changeProperties", "changeFn", "_newRoot", "_buildNewRoot", "change", "propertiesStructure", "properties", "_commit", "db", "flush", "internal", "createEpoch", "migration", "Migration", "REPLACE_AUTOMERGE_ROOT", "automergeRootUrl", "Object", "entries", "RawString", "create", "initNewObject", "setType", "getDoc", "handle", "_flushIds", "coreDatabase", "_automergeDocLoader", "getSpaceRootDocHandle", "SpaceState", "live", "invariant", "Migrations", "versionProperty", "namespace", "targetVersion", "migrations", "length", "version", "running", "space", "_state", "includes", "key", "toHex", "define", "migrate", "invariant", "state", "get", "SpaceState", "SPACE_READY", "currentVersion", "properties", "currentIndex", "findIndex", "m", "i", "targetIndex", "push", "slice", "migration", "builder", "MigrationBuilder", "next", "changeProperties", "propertiesStructure", "data", "_commit", "splice", "indexOf", "_define_property", "live"]
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A, type Doc } from '@automerge/automerge';\nimport { type AnyDocumentId, type DocumentId } from '@automerge/automerge-repo';\nimport type * as Schema from 'effect/Schema';\n\nimport { type Space } from '@dxos/client/echo';\nimport { CreateEpochRequest } from '@dxos/client/halo';\nimport { type DocHandleProxy, ObjectCore, type RepoProxy, migrateDocument } from '@dxos/echo-db';\nimport { type DatabaseDirectory, EncodedReference, type ObjectStructure, SpaceDocVersion } from '@dxos/echo-protocol';\nimport { getSchemaURI } from '@dxos/echo/internal';\nimport * as Type from '@dxos/echo/Type';\nimport { invariant } from '@dxos/invariant';\nimport { EchoURI, ObjectId } from '@dxos/keys';\nimport { type MaybePromise } from '@dxos/util';\n\n/*\n\nConsidering a better API for this:\n\n```ts\nconst migration = space.db.beginMigration(); // all actions are not visible to queries and are only applied once you call `apply`\n\nmigration.applyObjectMigration(defineMigration(From, To, { ... }));\n\nmigration.delete(id);\nmigration.add(obj);\n\nawait migration.apply(); // Will create new epoch.\n```\n\n*/\n\n// TODO(dmaretskyi): We no longer need to hook into ECHO internals, with the changes to echo APIs.\nexport class MigrationBuilder {\n private readonly _repo: RepoProxy;\n private readonly _rootDoc: Doc<DatabaseDirectory>;\n\n // echoUri -> automergeUrl\n private readonly _newLinks: Record<string, string> = {};\n private readonly _flushIds: DocumentId[] = [];\n private readonly _deleteObjects: string[] = [];\n\n private _newRoot?: DocHandleProxy<DatabaseDirectory> = undefined;\n\n constructor(private readonly _space: Space) {\n this._repo = this._space.internal.db.coreDatabase._repo;\n // TODO(wittjosiah): Accessing private API.\n this._rootDoc = (this._space.internal.db.coreDatabase as any)._automergeDocLoader\n .getSpaceRootDocHandle()\n .doc() as Doc<DatabaseDirectory>;\n }\n\n async findObject(id: string): Promise<ObjectStructure | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() 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.doc() as Doc<DatabaseDirectory>;\n return doc.objects?.[id];\n }\n\n async migrateObject(\n id: string,\n migrate: (objectStructure: ObjectStructure) => MaybePromise<{ type: Type.AnyEntity; props: any }>,\n ): Promise<void> {\n const objectStructure = await this.findObject(id);\n if (!objectStructure) {\n return;\n }\n\n const { type, props } = await migrate(objectStructure);\n const schema = Type.getSchema(type);\n\n const oldHandle = await this._findObjectContainingHandle(id);\n invariant(oldHandle);\n\n const newState: DatabaseDirectory = {\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [id]: {\n system: {\n type: EncodedReference.fromURI(getSchemaURI(schema)!),\n },\n data: props,\n meta: {\n keys: [],\n },\n },\n },\n };\n const migratedDoc = migrateDocument(oldHandle.doc() as Doc<DatabaseDirectory>, newState);\n const newHandle = this._repo.import<DatabaseDirectory>(A.save(migratedDoc));\n await newHandle.whenReady();\n invariant(newHandle.url, 'Migrated document URL not available after whenReady');\n this._newLinks[id] = newHandle.url;\n this._addHandleToFlushList(newHandle.documentId!);\n }\n\n async addObject(type: Type.AnyEntity, props: any): Promise<string> {\n const resolved = Type.getSchema(type);\n const core = await this._createObject({ schema: resolved, props });\n return core.id;\n }\n\n createReference(id: string) {\n invariant(ObjectId.isValid(id), 'Invalid ObjectId.');\n return EncodedReference.fromURI(EchoURI.make({ objectId: id }));\n }\n\n deleteObject(id: string): void {\n this._deleteObjects.push(id);\n }\n\n async changeProperties(changeFn: (properties: ObjectStructure) => void): Promise<void> {\n if (!this._newRoot) {\n await this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n this._newRoot.change((doc: DatabaseDirectory) => {\n const propertiesStructure = doc.objects?.[this._space.properties.id];\n propertiesStructure && changeFn(propertiesStructure);\n });\n await this._newRoot.whenReady();\n this._addHandleToFlushList(this._newRoot.documentId!);\n }\n\n /**\n * @internal\n */\n async _commit(): Promise<void> {\n if (!this._newRoot) {\n await this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n await this._space.db.flush();\n\n // Create new epoch.\n invariant(this._newRoot.url, 'New root URL not available');\n await this._space.internal.createEpoch({\n migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,\n automergeRootUrl: this._newRoot.url,\n });\n }\n\n private async _findObjectContainingHandle(id: string): Promise<DocHandleProxy<DatabaseDirectory> | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n return docHandle;\n }\n\n private async _buildNewRoot(): Promise<void> {\n const links = { ...(this._rootDoc.links ?? {}) };\n for (const id of this._deleteObjects) {\n delete links[id];\n }\n\n for (const [id, url] of Object.entries(this._newLinks)) {\n links[id] = new A.RawString(url);\n }\n\n this._newRoot = this._repo.create<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: this._rootDoc.objects,\n links,\n });\n await this._newRoot.whenReady();\n this._addHandleToFlushList(this._newRoot.documentId!);\n }\n\n private async _createObject({\n id,\n schema,\n props,\n }: {\n id?: string;\n schema: Schema.Schema.AnyNoContext;\n props: any;\n }): Promise<ObjectCore> {\n const core = new ObjectCore();\n if (id) {\n core.id = id;\n }\n\n core.initNewObject(props);\n core.setType(EncodedReference.fromURI(getSchemaURI(schema)!));\n const newHandle = this._repo.create<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: {\n spaceKey: this._space.key.toHex(),\n },\n objects: {\n [core.id]: core.getDoc() as ObjectStructure,\n },\n });\n await newHandle.whenReady();\n this._newLinks[core.id] = newHandle.url!;\n this._addHandleToFlushList(newHandle.documentId!);\n\n return core;\n }\n\n private _addHandleToFlushList(id: DocumentId): void {\n this._flushIds.push(id);\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Atom } from '@effect-atom/atom';\nimport * as Registry from '@effect-atom/atom/Registry';\n\nimport { type Space, 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 _registry = Registry.make();\n private static _stateAtom = Atom.make<{ running: string[] }>({ running: [] }).pipe(Atom.keepAlive);\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): boolean {\n const state = this._registry.get(this._stateAtom);\n return state.running.includes(space.key.toHex());\n }\n\n static define(namespace: string, migrations: Migration[]): void {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n static async migrate(space: Space, targetVersion?: string | number): Promise<boolean> {\n invariant(!this.running(space), 'Migration already running');\n invariant(this.versionProperty, 'Migrations namespace not set');\n invariant(space.state.get() === SpaceState.SPACE_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 const spaceKey = space.key.toHex();\n const currentState = this._registry.get(this._stateAtom);\n this._registry.set(this._stateAtom, { running: [...currentState.running, spaceKey] });\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 await 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 const finalState = this._registry.get(this._stateAtom);\n this._registry.set(this._stateAtom, { running: finalState.running.filter((key) => key !== spaceKey) });\n\n return true;\n }\n}\n"],
5
+ "mappings": ";AAIA,SAASA,QAAQC,SAAmB;AAKpC,SAASC,0BAA0B;AACnC,SAA8BC,YAA4BC,uBAAuB;AACjF,SAAiCC,kBAAwCC,uBAAuB;AAChG,SAASC,oBAAoB;AAC7B,YAAYC,UAAU;AACtB,SAASC,iBAAiB;AAC1B,SAASC,SAASC,gBAAgB;AAGlC,IAAA,eAAA;AAmBmBC,IAAiB,mBAAjBA,MAAiB;EACjBC;EAEjB;EACiBC;;EAEAC,YAAAA,CAAAA;EAETC,YAA+CC,CAAAA;EAEvD,iBAA6BC,CAAa;aAAbA;cACtBN,QAAQ;AACb,SAAA,SAAA;AACA,SAAKC,QAAQ,KAAI,OAAKK,SAAOC,GAASC,aAAGC;AAK3C,SAAMC,WAAqB,KAAwC,OAAA,SAAA,GAAA,aAAA,oBAAA,sBAAA,EAAA,IAAA;;QAEjE,WAAMC,IAAAA;AACN,UAAKA,cAAW,KAAA,SAAA,QAAA,EAAA,KAAA,KAAA,UAAA,EAAA,IAAA,SAAA;UACd,YAAON,cAAAA,KAAAA,MAAAA,KAAAA,UAAAA;AACT,QAAA,CAAA,WAAA;AAEA,aAAMM;IACN;AACA,UAAA,UAAWC,UAAa;AAC1B,UAAA,MAAA,UAAA,IAAA;AAEA,WAAMC,IAAAA,UAEJC,EAAAA;;QAGA,cAAKC,IAAAA,SAAiB;UACpB,kBAAA,MAAA,KAAA,WAAA,EAAA;AACF,QAAA,CAAA,iBAAA;AAEA;IACA;AAEA,UAAMC,EAAAA,MAAAA,MAAY,IAAM,MAAKC,QAAAA,eAAAA;AAC7BpB,UAAAA,SAAUmB,eAAAA,IAAAA;AAEV,UAAME,YAA8B,MAAA,KAAA,4BAAA,EAAA;cAClCC,WAASzB,QAAAA,EAAAA,YAAuB,YAAA,GAAA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cAAOmB,UAAAA,KAAAA;UAAQ;UACtC;;cAEEE,QAAAA,iBAAyB,CAAA,wBAAwBH;AACnD,UAAAf,WAAA,KAAA,iBAAA,gCAAA,EAAA,YAAA,YAAA,GAAAd,eAAA,GAAA,IAAA,GAAA,MAAA,GAAA,CAAA,wBAAA,gCAAA,EAAA,CAAA;AACA,8BAAqB,KAAA,KAAA,eAAA,IAAA,UAAA;QACvB,CAAA;AACF,cAAA,QAAA,QAAA;MACA;IACA;UAAsCM,aAAS2B,KAAW3B,UAAQ4B,IAAM,KAAEC,UAAQA;AAAkB,SAAA,UAAA,IAAA,KAAA,YAAA;MAEpG,SAAO,WAAA,QAAA,OAAA,CAAA,QAAA,QAAA,QAAA;IACT,CAAA;AACF,WAAA;;;",
6
+ "names": ["next", "A", "CreateEpochRequest", "ObjectCore", "migrateDocument", "EncodedReference", "SpaceDocVersion", "getSchemaURI", "Type", "invariant", "EchoURI", "ObjectId", "_repo", "_rootDoc", "_newLinks", "_deleteObjects", "_newRoot", "undefined", "_space", "internal", "db", "coreDatabase", "findObject", "docHandle", "objects", "migrateObject", "migrate", "objectStructure", "oldHandle", "_findObjectContainingHandle", "newState", "version", "access", "spaceKey", "system", "data", "props", "meta", "keys", "newHandle", "whenReady", "id", "_addHandleToFlushList", "addObject", "core", "_createObject", "schema", "resolved", "createReference", "objectId", "deleteObject", "changeProperties", "changeFn", "_buildNewRoot", "propertiesStructure", "properties", "migration", "REPLACE_AUTOMERGE_ROOT", "automergeRootUrl", "documentId", "url", "create", "links", "initNewObject", "CURRENT", "Atom", "Registry", "SpaceState", "invariant", "__dxlog_file", "Migrations", "migrations", "_registry", "_stateAtom", "Atom", "running", "keepAlive", "versionProperty", "namespace", "targetVersion", "space", "state", "define", "invariant", "get", "SpaceState", "currentVersion", "properties", "currentIndex", "findIndex", "version", "i", "m", "targetIndex", "length", "spaceKey", "set", "currentState", "migration", "builder", "MigrationBuilder", "propertiesStructure", "finalState", "filter", "key"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"src/migration-builder.ts":{"bytes":22856,"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","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/invariant","kind":"import-statement","external":true}],"format":"esm"},"src/migrations.ts":{"bytes":10109,"imports":[{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"}],"format":"esm"},"src/index.ts":{"bytes":653,"imports":[{"path":"src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"},{"path":"src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":15873},"dist/lib/browser/index.mjs":{"imports":[{"path":"@automerge/automerge","kind":"import-statement","external":true},{"path":"@dxos/client/halo","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","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/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":"src/index.ts","inputs":{"src/migration-builder.ts":{"bytesInOutput":5407},"src/index.ts":{"bytesInOutput":0},"src/migrations.ts":{"bytesInOutput":3050}},"bytes":8587}}}
1
+ {"inputs":{"src/migration-builder.ts":{"bytes":24302,"imports":[{"path":"@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/internal","kind":"import-statement","external":true},{"path":"@dxos/echo/Type","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true}],"format":"esm"},"src/migrations.ts":{"bytes":10982,"imports":[{"path":"@effect-atom/atom","kind":"import-statement","external":true},{"path":"@effect-atom/atom/Registry","kind":"import-statement","external":true},{"path":"@dxos/client/echo","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"}],"format":"esm"},"src/index.ts":{"bytes":575,"imports":[{"path":"src/migration-builder.ts","kind":"import-statement","original":"./migration-builder"},{"path":"src/migrations.ts","kind":"import-statement","original":"./migrations"}],"format":"esm"}},"outputs":{"dist/lib/browser/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":17127},"dist/lib/browser/index.mjs":{"imports":[{"path":"@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/internal","kind":"import-statement","external":true},{"path":"@dxos/echo/Type","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@effect-atom/atom","kind":"import-statement","external":true},{"path":"@effect-atom/atom/Registry","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":"src/index.ts","inputs":{"src/migration-builder.ts":{"bytesInOutput":5762},"src/index.ts":{"bytesInOutput":0},"src/migrations.ts":{"bytesInOutput":3055}},"bytes":8947}}}