@coaction/yjs 1.5.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,592 +1,705 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
1
+ import { StateSchemaError, applyRootReplacementWithPatches, isStateSchemaError, onStoreReady } from "coaction";
2
+ import * as Y from "yjs";
3
+ export * from "yjs";
4
+ //#endregion
5
+ //#region packages/coaction-yjs/src/shared.ts
6
+ const scheduleMicrotask = (callback) => {
7
+ if (typeof queueMicrotask === "function") {
8
+ queueMicrotask(callback);
9
+ return;
10
+ }
11
+ Promise.resolve().then(callback);
16
12
  };
17
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
-
19
- // index.ts
20
- var index_exports = {};
21
- __export(index_exports, {
22
- __unsafeTestOnly__: () => __unsafeTestOnly__,
23
- bindYjs: () => bindYjs,
24
- yjs: () => yjs
25
- });
26
-
27
- // src/index.ts
28
- var src_exports = {};
29
- __export(src_exports, {
30
- __unsafeTestOnly__: () => __unsafeTestOnly__,
31
- bindYjs: () => bindYjs,
32
- yjs: () => yjs
33
- });
34
- import * as Y4 from "yjs";
35
-
36
- // src/remoteOperations.ts
37
- import * as Y2 from "yjs";
38
-
39
- // src/shared.ts
40
- var scheduleMicrotask = (callback) => {
41
- if (typeof queueMicrotask === "function") {
42
- queueMicrotask(callback);
43
- return;
44
- }
45
- Promise.resolve().then(callback);
13
+ const isUnsafeKey = (key) => key === "__proto__" || key === "prototype" || key === "constructor";
14
+ const isUnsafePathSegment = (segment) => typeof segment === "string" && isUnsafeKey(segment);
15
+ const cloneFallback = (value, seen = /* @__PURE__ */ new WeakMap()) => {
16
+ if (typeof value !== "object" || value === null) return value;
17
+ const cached = seen.get(value);
18
+ if (cached) return cached;
19
+ if (Array.isArray(value)) {
20
+ const next = [];
21
+ seen.set(value, next);
22
+ for (let index = 0; index < value.length; index += 1) if (Object.prototype.hasOwnProperty.call(value, index)) next[index] = cloneFallback(value[index], seen);
23
+ return next;
24
+ }
25
+ if (isPlainObject(value)) {
26
+ const next = Object.create(Object.getPrototypeOf(value));
27
+ seen.set(value, next);
28
+ for (const key of Reflect.ownKeys(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) {
29
+ if (typeof key === "string" && isUnsafeKey(key)) continue;
30
+ next[key] = cloneFallback(value[key], seen);
31
+ }
32
+ return next;
33
+ }
34
+ return JSON.parse(JSON.stringify(value));
46
35
  };
47
36
  function clone(value) {
48
- if (typeof structuredClone === "function") {
49
- return structuredClone(value);
50
- }
51
- return JSON.parse(JSON.stringify(value));
37
+ if (Array.isArray(value) || isPlainObject(value)) return cloneFallback(value);
38
+ if (typeof structuredClone === "function") try {
39
+ return structuredClone(value);
40
+ } catch {
41
+ return cloneFallback(value);
42
+ }
43
+ return cloneFallback(value);
52
44
  }
53
45
  function isPlainObject(value) {
54
- if (typeof value !== "object" || value === null) {
55
- return false;
56
- }
57
- const prototype = Object.getPrototypeOf(value);
58
- return prototype === Object.prototype || prototype === null;
46
+ if (typeof value !== "object" || value === null) return false;
47
+ const prototype = Object.getPrototypeOf(value);
48
+ return prototype === Object.prototype || prototype === null;
59
49
  }
60
-
61
- // src/yjsValue.ts
62
- import * as Y from "yjs";
50
+ function sanitizePlainValue(value, seen = /* @__PURE__ */ new WeakMap()) {
51
+ if (typeof value !== "object" || value === null) return value;
52
+ const cached = seen.get(value);
53
+ if (cached) return cached;
54
+ if (Array.isArray(value)) {
55
+ const next = [];
56
+ seen.set(value, next);
57
+ for (let index = 0; index < value.length; index += 1) if (Object.prototype.hasOwnProperty.call(value, index)) next[index] = sanitizePlainValue(value[index], seen);
58
+ return next;
59
+ }
60
+ if (!isPlainObject(value)) return clone(value);
61
+ const next = {};
62
+ seen.set(value, next);
63
+ for (const key of Object.keys(value)) {
64
+ if (isUnsafeKey(key)) continue;
65
+ next[key] = sanitizePlainValue(value[key], seen);
66
+ }
67
+ return next;
68
+ }
69
+ //#endregion
70
+ //#region packages/coaction-yjs/src/yjsValue.ts
63
71
  function toPlainObject(value) {
64
- const next = {};
65
- value.forEach((item, key) => {
66
- next[key] = toPlainValue(item);
67
- });
68
- return next;
72
+ const next = {};
73
+ value.forEach((item, key) => {
74
+ if (isUnsafeKey(key)) return;
75
+ next[key] = toPlainValue(item);
76
+ });
77
+ return next;
69
78
  }
70
79
  function toPlainArray(value) {
71
- return value.toArray().map((item) => toPlainValue(item));
80
+ return value.toArray().map((item) => toPlainValue(item));
72
81
  }
73
82
  function toPlainValue(value) {
74
- if (value instanceof Y.Map) {
75
- return toPlainObject(value);
76
- }
77
- if (value instanceof Y.Array) {
78
- return toPlainArray(value);
79
- }
80
- return value;
83
+ if (value instanceof Y.Map) return toPlainObject(value);
84
+ if (value instanceof Y.Array) return toPlainArray(value);
85
+ if (value instanceof Y.AbstractType) return toPlainValue(value.toJSON());
86
+ if (Array.isArray(value) || isPlainObject(value)) return sanitizePlainValue(value);
87
+ return value;
81
88
  }
82
89
  function createYMap(value) {
83
- const next = new Y.Map();
84
- for (const [key, item] of Object.entries(value)) {
85
- next.set(key, toYValue(item));
86
- }
87
- return next;
90
+ const next = new Y.Map();
91
+ for (const [key, item] of Object.entries(value)) {
92
+ if (isUnsafeKey(key)) continue;
93
+ next.set(key, toYValue(item));
94
+ }
95
+ return next;
88
96
  }
89
97
  function createYArray(value) {
90
- const next = new Y.Array();
91
- if (value.length > 0) {
92
- next.insert(
93
- 0,
94
- value.map((item) => toYValue(item))
95
- );
96
- }
97
- return next;
98
+ const next = new Y.Array();
99
+ if (value.length > 0) next.insert(0, value.map((item) => toYValue(item)));
100
+ return next;
98
101
  }
99
102
  function toYValue(value) {
100
- if (Array.isArray(value)) {
101
- return createYArray(value);
102
- }
103
- if (isPlainObject(value)) {
104
- return createYMap(value);
105
- }
106
- if (typeof value === "object" && value !== null) {
107
- return clone(value);
108
- }
109
- return value;
103
+ if (Array.isArray(value)) return createYArray(value);
104
+ if (isPlainObject(value)) return createYMap(value);
105
+ if (typeof value === "object" && value !== null) return clone(value);
106
+ return value;
110
107
  }
111
-
112
- // src/remoteOperations.ts
108
+ //#endregion
109
+ //#region packages/coaction-yjs/src/remoteOperations.ts
113
110
  function isSetStateReentryError(error) {
114
- return error instanceof Error && error.message === "setState cannot be called within the updater";
111
+ return error instanceof Error && error.message === "setState cannot be called within the updater";
115
112
  }
116
113
  function cloneForStore(value) {
117
- if (typeof value === "object" && value !== null) {
118
- return clone(value);
119
- }
120
- return value;
114
+ if (typeof value === "object" && value !== null) return sanitizePlainValue(value);
115
+ return value;
121
116
  }
122
117
  function toPathKey(path) {
123
- return path.map((segment) => `${typeof segment}:${String(segment)}`).join("|");
118
+ return path.map((segment) => `${typeof segment}:${String(segment)}`).join("|");
119
+ }
120
+ function toArrayIndex(segment) {
121
+ const index = typeof segment === "number" ? segment : Number.parseInt(segment, 10);
122
+ if (!Number.isInteger(index) || index < 0) return;
123
+ if (typeof segment === "string" && String(index) !== segment) return;
124
+ return index;
125
+ }
126
+ function assertCanSetPathSegment(target, key, path) {
127
+ if (Object.prototype.hasOwnProperty.call(target, key)) return;
128
+ if (Object.isExtensible(target)) return;
129
+ throw new StateSchemaError(`Unknown state key '${path.map((segment) => String(segment)).join(".")}' cannot be added after store initialization. Coaction state schema is fixed.`);
130
+ }
131
+ function clearObjectKey(target, key) {
132
+ if (!Object.prototype.hasOwnProperty.call(target, key)) return;
133
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
134
+ if (descriptor?.configurable) {
135
+ delete target[key];
136
+ return;
137
+ }
138
+ if (descriptor && "set" in descriptor && descriptor.set) {
139
+ target[key] = void 0;
140
+ return;
141
+ }
142
+ if (descriptor && "writable" in descriptor && descriptor.writable) target[key] = void 0;
124
143
  }
125
144
  function compactOperations(operations) {
126
- const deduplicated = /* @__PURE__ */ new Map();
127
- for (const operation of operations) {
128
- const key = toPathKey(operation.path);
129
- if (deduplicated.has(key)) {
130
- deduplicated.delete(key);
131
- }
132
- deduplicated.set(key, operation);
133
- }
134
- return Array.from(deduplicated.values()).sort(
135
- (left, right) => left.path.length - right.path.length
136
- );
145
+ const deduplicated = /* @__PURE__ */ new Map();
146
+ for (const operation of operations) {
147
+ const key = toPathKey(operation.path);
148
+ if (deduplicated.has(key)) deduplicated.delete(key);
149
+ deduplicated.set(key, operation);
150
+ }
151
+ return Array.from(deduplicated.values()).sort((left, right) => left.path.length - right.path.length);
137
152
  }
138
153
  function getYValueAtPath(root, path) {
139
- let current = root;
140
- for (const segment of path) {
141
- if (current instanceof Y2.Map) {
142
- current = current.get(String(segment));
143
- continue;
144
- }
145
- if (current instanceof Y2.Array) {
146
- const index = typeof segment === "number" ? segment : Number.parseInt(segment, 10);
147
- if (!Number.isInteger(index)) {
148
- return void 0;
149
- }
150
- current = current.get(index);
151
- continue;
152
- }
153
- return void 0;
154
- }
155
- return current;
154
+ let current = root;
155
+ for (const segment of path) {
156
+ if (current instanceof Y.Map) {
157
+ current = current.get(String(segment));
158
+ continue;
159
+ }
160
+ if (current instanceof Y.Array) {
161
+ const index = toArrayIndex(segment);
162
+ if (typeof index === "undefined") return;
163
+ current = current.get(index);
164
+ continue;
165
+ }
166
+ return;
167
+ }
168
+ return current;
156
169
  }
157
170
  function setAtPath(target, path, value) {
158
- if (path.length === 0) {
159
- return;
160
- }
161
- let current = target;
162
- for (let index = 0; index < path.length - 1; index += 1) {
163
- const segment = path[index];
164
- const nextSegment = path[index + 1];
165
- const nextValue = current[segment];
166
- if (typeof nextValue !== "object" || nextValue === null) {
167
- current[segment] = typeof nextSegment === "number" ? [] : {};
168
- }
169
- current = current[segment];
170
- }
171
- const leaf = path[path.length - 1];
172
- current[leaf] = cloneForStore(value);
171
+ if (path.length === 0) return;
172
+ if (path.some(isUnsafePathSegment)) return;
173
+ let current = target;
174
+ for (let index = 0; index < path.length - 1; index += 1) {
175
+ const segment = path[index];
176
+ const nextSegment = path[index + 1];
177
+ const segmentIndex = Array.isArray(current) ? toArrayIndex(segment) : void 0;
178
+ const targetKey = typeof segmentIndex === "undefined" ? segment : segmentIndex;
179
+ const nextValue = current[targetKey];
180
+ const needsArray = typeof nextSegment === "number" || Array.isArray(nextValue) && typeof toArrayIndex(nextSegment) !== "undefined";
181
+ if (typeof nextValue !== "object" || nextValue === null || (needsArray ? !Array.isArray(nextValue) : Array.isArray(nextValue))) {
182
+ assertCanSetPathSegment(current, targetKey, path.slice(0, index + 1));
183
+ current[targetKey] = typeof nextSegment === "number" ? [] : {};
184
+ }
185
+ current = current[targetKey];
186
+ }
187
+ const leaf = path[path.length - 1];
188
+ const leafIndex = Array.isArray(current) ? toArrayIndex(leaf) : void 0;
189
+ const leafKey = typeof leafIndex === "undefined" ? leaf : leafIndex;
190
+ assertCanSetPathSegment(current, leafKey, path);
191
+ current[leafKey] = cloneForStore(value);
173
192
  }
174
193
  function deleteAtPath(target, path) {
175
- if (path.length === 0) {
176
- return;
177
- }
178
- let current = target;
179
- for (let index = 0; index < path.length - 1; index += 1) {
180
- current = current[path[index]];
181
- if (typeof current !== "object" || current === null) {
182
- return;
183
- }
184
- }
185
- const leaf = path[path.length - 1];
186
- if (Array.isArray(current) && typeof leaf === "number") {
187
- if (leaf >= 0 && leaf < current.length) {
188
- current.splice(leaf, 1);
189
- }
190
- return;
191
- }
192
- delete current[leaf];
194
+ if (path.length === 0) return;
195
+ if (path.some(isUnsafePathSegment)) return;
196
+ let current = target;
197
+ for (let index = 0; index < path.length - 1; index += 1) {
198
+ const segment = path[index];
199
+ const segmentIndex = Array.isArray(current) ? toArrayIndex(segment) : void 0;
200
+ current = current[typeof segmentIndex === "undefined" ? segment : segmentIndex];
201
+ if (typeof current !== "object" || current === null) return;
202
+ }
203
+ const leaf = path[path.length - 1];
204
+ if (Array.isArray(current)) {
205
+ const leafIndex = toArrayIndex(leaf);
206
+ if (typeof leafIndex !== "undefined" && leafIndex >= 0 && leafIndex < current.length) current.splice(leafIndex, 1);
207
+ return;
208
+ }
209
+ clearObjectKey(current, leaf);
193
210
  }
194
211
  function collectRemoteOperations(events, stateMap) {
195
- const operations = [];
196
- for (const event of events) {
197
- if (event instanceof Y2.YMapEvent) {
198
- for (const changedKey of event.keysChanged) {
199
- const path = [...event.path, changedKey];
200
- const keyChange = event.changes.keys.get(changedKey);
201
- if (keyChange?.action === "delete") {
202
- operations.push({
203
- type: "delete",
204
- path
205
- });
206
- continue;
207
- }
208
- operations.push({
209
- type: "set",
210
- path,
211
- value: toPlainValue(getYValueAtPath(stateMap, path))
212
- });
213
- }
214
- continue;
215
- }
216
- if (event instanceof Y2.YArrayEvent) {
217
- const path = [...event.path];
218
- operations.push({
219
- type: "set",
220
- path,
221
- value: toPlainValue(getYValueAtPath(stateMap, path))
222
- });
223
- }
224
- }
225
- return operations;
212
+ const operations = [];
213
+ for (const event of events) {
214
+ if (event instanceof Y.YMapEvent) {
215
+ for (const changedKey of event.keysChanged) {
216
+ const path = [...event.path, changedKey];
217
+ if (path.some(isUnsafePathSegment)) continue;
218
+ if (event.changes.keys.get(changedKey)?.action === "delete") {
219
+ operations.push({
220
+ type: "delete",
221
+ path
222
+ });
223
+ continue;
224
+ }
225
+ operations.push({
226
+ type: "set",
227
+ path,
228
+ value: toPlainValue(getYValueAtPath(stateMap, path))
229
+ });
230
+ }
231
+ continue;
232
+ }
233
+ if (event instanceof Y.YArrayEvent) {
234
+ const path = [...event.path];
235
+ operations.push({
236
+ type: "set",
237
+ path,
238
+ value: toPlainValue(getYValueAtPath(stateMap, path))
239
+ });
240
+ }
241
+ }
242
+ return operations;
226
243
  }
227
-
228
- // src/sync.ts
229
- import * as Y3 from "yjs";
244
+ //#endregion
245
+ //#region packages/coaction-yjs/src/sync.ts
230
246
  function isEqualValue(left, right) {
231
- if (Object.is(left, right)) {
232
- return true;
233
- }
234
- if (Array.isArray(left) && Array.isArray(right)) {
235
- if (left.length !== right.length) {
236
- return false;
237
- }
238
- for (let index = 0; index < left.length; index += 1) {
239
- if (!isEqualValue(left[index], right[index])) {
240
- return false;
241
- }
242
- }
243
- return true;
244
- }
245
- if (isPlainObject(left) && isPlainObject(right)) {
246
- const leftKeys = Object.keys(left);
247
- const rightKeys = Object.keys(right);
248
- if (leftKeys.length !== rightKeys.length) {
249
- return false;
250
- }
251
- for (const key of leftKeys) {
252
- if (!Object.prototype.hasOwnProperty.call(right, key)) {
253
- return false;
254
- }
255
- if (!isEqualValue(left[key], right[key])) {
256
- return false;
257
- }
258
- }
259
- return true;
260
- }
261
- return false;
247
+ if (Object.is(left, right)) return true;
248
+ if (Array.isArray(left) && Array.isArray(right)) {
249
+ if (left.length !== right.length) return false;
250
+ for (let index = 0; index < left.length; index += 1) if (!isEqualValue(left[index], right[index])) return false;
251
+ return true;
252
+ }
253
+ if (isPlainObject(left) && isPlainObject(right)) {
254
+ const leftKeys = Object.keys(left);
255
+ const rightKeys = Object.keys(right);
256
+ if (leftKeys.length !== rightKeys.length) return false;
257
+ for (const key of leftKeys) {
258
+ if (!Object.prototype.hasOwnProperty.call(right, key)) return false;
259
+ if (!isEqualValue(left[key], right[key])) return false;
260
+ }
261
+ return true;
262
+ }
263
+ return false;
262
264
  }
263
265
  function syncObjectToYMap(target, previous, source) {
264
- const keys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(source)]);
265
- for (const key of keys) {
266
- const hasPrevious = Object.prototype.hasOwnProperty.call(previous, key);
267
- const hasNext = Object.prototype.hasOwnProperty.call(source, key);
268
- if (!hasNext) {
269
- target.delete(key);
270
- continue;
271
- }
272
- const previousValue = hasPrevious ? previous[key] : void 0;
273
- const nextValue = source[key];
274
- if (hasPrevious && isEqualValue(previousValue, nextValue)) {
275
- continue;
276
- }
277
- const current = target.get(key);
278
- if (Array.isArray(nextValue)) {
279
- if (Array.isArray(previousValue) && current instanceof Y3.Array) {
280
- syncArrayToYArray(current, previousValue, nextValue);
281
- } else {
282
- target.set(key, createYArray(nextValue));
283
- }
284
- continue;
285
- }
286
- if (isPlainObject(nextValue)) {
287
- if (isPlainObject(previousValue) && current instanceof Y3.Map) {
288
- syncObjectToYMap(current, previousValue, nextValue);
289
- } else {
290
- target.set(key, createYMap(nextValue));
291
- }
292
- continue;
293
- }
294
- const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
295
- if (!Object.is(current, normalized)) {
296
- target.set(key, normalized);
297
- }
298
- }
266
+ target.forEach((_value, key) => {
267
+ if (isUnsafeKey(key)) target.delete(key);
268
+ });
269
+ const keys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(source)]);
270
+ for (const key of keys) {
271
+ if (isUnsafeKey(key)) {
272
+ target.delete(key);
273
+ continue;
274
+ }
275
+ const hasPrevious = Object.prototype.hasOwnProperty.call(previous, key);
276
+ if (!Object.prototype.hasOwnProperty.call(source, key)) {
277
+ target.delete(key);
278
+ continue;
279
+ }
280
+ const previousValue = hasPrevious ? previous[key] : void 0;
281
+ const nextValue = source[key];
282
+ if (hasPrevious && isEqualValue(previousValue, nextValue)) continue;
283
+ const current = target.get(key);
284
+ if (Array.isArray(nextValue)) {
285
+ if (Array.isArray(previousValue) && current instanceof Y.Array) syncArrayToYArray(current, previousValue, nextValue);
286
+ else target.set(key, createYArray(nextValue));
287
+ continue;
288
+ }
289
+ if (isPlainObject(nextValue)) {
290
+ if (isPlainObject(previousValue) && current instanceof Y.Map) syncObjectToYMap(current, previousValue, nextValue);
291
+ else target.set(key, createYMap(nextValue));
292
+ continue;
293
+ }
294
+ const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
295
+ if (!Object.is(current, normalized)) target.set(key, normalized);
296
+ }
299
297
  }
300
298
  function syncArrayToYArray(target, previous, source) {
301
- if (target.length > source.length) {
302
- target.delete(source.length, target.length - source.length);
303
- }
304
- const maxLength = Math.max(previous.length, source.length);
305
- for (let index = 0; index < maxLength; index += 1) {
306
- const hasPrevious = index < previous.length;
307
- const hasNext = index < source.length;
308
- if (!hasNext) {
309
- continue;
310
- }
311
- const previousValue = hasPrevious ? previous[index] : void 0;
312
- const nextValue = source[index];
313
- if (hasPrevious && isEqualValue(previousValue, nextValue)) {
314
- continue;
315
- }
316
- if (index >= target.length) {
317
- target.insert(index, [toYValue(nextValue)]);
318
- continue;
319
- }
320
- const current = target.get(index);
321
- if (Array.isArray(nextValue)) {
322
- if (Array.isArray(previousValue) && current instanceof Y3.Array) {
323
- syncArrayToYArray(current, previousValue, nextValue);
324
- } else {
325
- target.delete(index, 1);
326
- target.insert(index, [createYArray(nextValue)]);
327
- }
328
- continue;
329
- }
330
- if (isPlainObject(nextValue)) {
331
- if (isPlainObject(previousValue) && current instanceof Y3.Map) {
332
- syncObjectToYMap(current, previousValue, nextValue);
333
- } else {
334
- target.delete(index, 1);
335
- target.insert(index, [createYMap(nextValue)]);
336
- }
337
- continue;
338
- }
339
- const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
340
- if (!Object.is(current, normalized)) {
341
- target.delete(index, 1);
342
- target.insert(index, [normalized]);
343
- }
344
- }
299
+ if (target.length > source.length) target.delete(source.length, target.length - source.length);
300
+ const maxLength = Math.max(previous.length, source.length);
301
+ for (let index = 0; index < maxLength; index += 1) {
302
+ const hasPrevious = index < previous.length;
303
+ if (!(index < source.length)) continue;
304
+ const previousValue = hasPrevious ? previous[index] : void 0;
305
+ const nextValue = source[index];
306
+ if (hasPrevious && isEqualValue(previousValue, nextValue)) continue;
307
+ if (index >= target.length) {
308
+ target.insert(index, [toYValue(nextValue)]);
309
+ continue;
310
+ }
311
+ const current = target.get(index);
312
+ if (Array.isArray(nextValue)) {
313
+ if (Array.isArray(previousValue) && current instanceof Y.Array) syncArrayToYArray(current, previousValue, nextValue);
314
+ else {
315
+ target.delete(index, 1);
316
+ target.insert(index, [createYArray(nextValue)]);
317
+ }
318
+ continue;
319
+ }
320
+ if (isPlainObject(nextValue)) {
321
+ if (isPlainObject(previousValue) && current instanceof Y.Map) syncObjectToYMap(current, previousValue, nextValue);
322
+ else {
323
+ target.delete(index, 1);
324
+ target.insert(index, [createYMap(nextValue)]);
325
+ }
326
+ continue;
327
+ }
328
+ const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
329
+ if (!Object.is(current, normalized)) {
330
+ target.delete(index, 1);
331
+ target.insert(index, [normalized]);
332
+ }
333
+ }
345
334
  }
346
-
347
- // src/index.ts
348
- __reExport(src_exports, yjs_star);
349
- import * as yjs_star from "yjs";
350
- var STATE_KEY = "state";
351
- var __unsafeTestOnly__ = {
352
- getYValueAtPath: (root, path) => getYValueAtPath(root, path),
353
- setAtPath: (target, path, value) => {
354
- setAtPath(target, path, value);
355
- },
356
- deleteAtPath: (target, path) => {
357
- deleteAtPath(target, path);
358
- }
335
+ //#endregion
336
+ //#region packages/coaction-yjs/src/index.ts
337
+ const STATE_KEY = "state";
338
+ const historySuppressionSymbol = Symbol.for("coaction.history.suppress");
339
+ const runWithoutHistoryRecording = (store, callback) => {
340
+ const runner = store[historySuppressionSymbol];
341
+ return typeof runner === "function" ? runner(callback) : callback();
342
+ };
343
+ const getOwnEnumerableKeys = (value) => Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key) && !(typeof key === "string" && isUnsafeKey(key)));
344
+ const formatPropertyPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
345
+ var YjsSerializableStateError = class extends Error {};
346
+ const isYjsSerializableStateError = (error) => error instanceof YjsSerializableStateError;
347
+ const isArrayIndexKey = (key, length) => {
348
+ if (key === "") return false;
349
+ const index = Number(key);
350
+ return Number.isInteger(index) && index >= 0 && index < length && String(index) === key;
351
+ };
352
+ const findYjsStateViolation = (value, path = [], ancestors = /* @__PURE__ */ new WeakSet()) => {
353
+ switch (typeof value) {
354
+ case "symbol": return {
355
+ type: "symbol-value",
356
+ path
357
+ };
358
+ case "function": return {
359
+ type: "function",
360
+ path
361
+ };
362
+ default: break;
363
+ }
364
+ if (typeof value !== "object" || value === null) return;
365
+ if (ancestors.has(value)) return {
366
+ type: "circular-reference",
367
+ path
368
+ };
369
+ if (Array.isArray(value)) {
370
+ ancestors.add(value);
371
+ for (let index = 0; index < value.length; index += 1) if (!Object.prototype.hasOwnProperty.call(value, index)) return {
372
+ type: "array-hole",
373
+ path: [...path, index]
374
+ };
375
+ for (const key of getOwnEnumerableKeys(value)) {
376
+ const nextPath = [...path, key];
377
+ if (typeof key === "symbol") return {
378
+ type: "symbol-key",
379
+ path: nextPath
380
+ };
381
+ if (!isArrayIndexKey(key, value.length)) return {
382
+ type: "array-property",
383
+ path: nextPath
384
+ };
385
+ const violation = findYjsStateViolation(value[Number(key)], nextPath, ancestors);
386
+ if (violation) return violation;
387
+ }
388
+ ancestors.delete(value);
389
+ return;
390
+ }
391
+ if (!isPlainObject(value)) return {
392
+ type: "non-plain-object",
393
+ path
394
+ };
395
+ ancestors.add(value);
396
+ for (const key of getOwnEnumerableKeys(value)) {
397
+ const nextPath = [...path, key];
398
+ if (typeof key === "symbol") return {
399
+ type: "symbol-key",
400
+ path: nextPath
401
+ };
402
+ const child = value[key];
403
+ const violation = findYjsStateViolation(child, nextPath, ancestors);
404
+ if (violation) return violation;
405
+ }
406
+ ancestors.delete(value);
407
+ };
408
+ const assertYjsSerializableState = (state, path = []) => {
409
+ const violation = findYjsStateViolation(state, path);
410
+ if (!violation) return;
411
+ if (violation.type === "symbol-key") throw new YjsSerializableStateError(`Yjs binding does not support symbol-keyed state because Y.Map keys are strings. Found symbol key at ${formatPropertyPath(violation.path)}.`);
412
+ if (violation.type === "symbol-value") throw new YjsSerializableStateError(`Yjs binding does not support symbol-valued state because symbols cannot be cloned into Yjs documents. Found symbol value at ${formatPropertyPath(violation.path)}.`);
413
+ throw new YjsSerializableStateError(`Yjs binding does not support ${violation.type} state because only plain objects, arrays, and primitive values round-trip through Yjs updates. Found unsupported value at ${formatPropertyPath(violation.path)}.`);
414
+ };
415
+ const assertRemoteOperationsSerializable = (operations) => {
416
+ for (const operation of operations) if (operation.type === "set") assertYjsSerializableState(operation.value, operation.path);
359
417
  };
360
- var bindYjs = (store, options = {}) => {
361
- if (store.share === "client") {
362
- throw new Error("Yjs binding is not supported in client store mode.");
363
- }
364
- const doc = options.doc ?? new Y4.Doc();
365
- const key = options.key ?? `coaction:${store.name}`;
366
- const map = doc.getMap(key);
367
- const localOrigin = /* @__PURE__ */ Symbol(`coaction-yjs:${store.name}`);
368
- let destroyed = false;
369
- let syncingFromYjs = false;
370
- let lastSyncedState = (() => {
371
- const pureState = clone(store.getPureState());
372
- return isPlainObject(pureState) ? pureState : {};
373
- })();
374
- let flushScheduled = false;
375
- let pendingSnapshot = null;
376
- let pendingOperations = [];
377
- const applyRemoteState = (state) => {
378
- const next = clone(state);
379
- syncingFromYjs = true;
380
- try {
381
- store.setState(next);
382
- const pureState = clone(store.getPureState());
383
- lastSyncedState = isPlainObject(pureState) ? pureState : {};
384
- } finally {
385
- syncingFromYjs = false;
386
- }
387
- };
388
- const applyRemoteOperations = (operations) => {
389
- if (operations.length === 0) {
390
- return;
391
- }
392
- syncingFromYjs = true;
393
- try {
394
- store.setState((draft) => {
395
- const mutableDraft = draft;
396
- for (const operation of operations) {
397
- if (operation.type === "set") {
398
- setAtPath(mutableDraft, operation.path, operation.value);
399
- } else {
400
- deleteAtPath(mutableDraft, operation.path);
401
- }
402
- }
403
- });
404
- const pureState = clone(store.getPureState());
405
- lastSyncedState = isPlainObject(pureState) ? pureState : {};
406
- } finally {
407
- syncingFromYjs = false;
408
- }
409
- };
410
- const getStateMap = () => {
411
- const state = map.get(STATE_KEY);
412
- if (state instanceof Y4.Map) {
413
- return state;
414
- }
415
- return null;
416
- };
417
- const scheduleFlushFromYjs = () => {
418
- if (destroyed || flushScheduled) {
419
- return;
420
- }
421
- flushScheduled = true;
422
- scheduleMicrotask(flushFromYjs);
423
- };
424
- const flushFromYjs = () => {
425
- flushScheduled = false;
426
- if (destroyed) {
427
- return;
428
- }
429
- if (pendingSnapshot) {
430
- const snapshot = pendingSnapshot;
431
- pendingSnapshot = null;
432
- pendingOperations = [];
433
- try {
434
- applyRemoteState(snapshot);
435
- } catch (error) {
436
- if (isSetStateReentryError(error)) {
437
- pendingSnapshot = snapshot;
438
- setTimeout(scheduleFlushFromYjs, 0);
439
- return;
440
- }
441
- throw error;
442
- }
443
- }
444
- if (pendingOperations.length === 0) {
445
- return;
446
- }
447
- const operations = compactOperations(pendingOperations);
448
- pendingOperations = [];
449
- try {
450
- applyRemoteOperations(operations);
451
- } catch (error) {
452
- if (isSetStateReentryError(error)) {
453
- pendingOperations = [...operations, ...pendingOperations];
454
- setTimeout(scheduleFlushFromYjs, 0);
455
- return;
456
- }
457
- throw error;
458
- }
459
- };
460
- const enqueueSnapshot = (snapshot) => {
461
- pendingSnapshot = snapshot;
462
- pendingOperations = [];
463
- scheduleFlushFromYjs();
464
- };
465
- const enqueueOperations = (operations) => {
466
- if (operations.length === 0) {
467
- return;
468
- }
469
- if (!pendingSnapshot) {
470
- pendingOperations.push(...operations);
471
- }
472
- scheduleFlushFromYjs();
473
- };
474
- const syncNow = () => {
475
- if (destroyed || syncingFromYjs) {
476
- return;
477
- }
478
- const pureState = clone(store.getPureState());
479
- if (!isPlainObject(pureState)) {
480
- return;
481
- }
482
- doc.transact(() => {
483
- syncObjectToYMap(stateMap, lastSyncedState, pureState);
484
- }, localOrigin);
485
- lastSyncedState = pureState;
486
- };
487
- const stateObserver = (events, transaction) => {
488
- if (transaction.origin === localOrigin) {
489
- return;
490
- }
491
- enqueueOperations(collectRemoteOperations(events, stateMap));
492
- };
493
- let stateMap;
494
- const existingStateMap = getStateMap();
495
- if (existingStateMap) {
496
- stateMap = existingStateMap;
497
- applyRemoteState(toPlainObject(stateMap));
498
- } else {
499
- const currentState = map.get(STATE_KEY);
500
- if (isPlainObject(currentState)) {
501
- stateMap = createYMap(currentState);
502
- doc.transact(() => {
503
- map.set(STATE_KEY, stateMap);
504
- }, localOrigin);
505
- applyRemoteState(currentState);
506
- } else {
507
- const pureState = clone(store.getPureState());
508
- stateMap = createYMap(isPlainObject(pureState) ? pureState : {});
509
- doc.transact(() => {
510
- map.set(STATE_KEY, stateMap);
511
- }, localOrigin);
512
- }
513
- }
514
- stateMap.observeDeep(stateObserver);
515
- const observer = (event) => {
516
- if (event.transaction.origin === localOrigin) {
517
- return;
518
- }
519
- if (!event.keysChanged.has(STATE_KEY)) {
520
- return;
521
- }
522
- const nextStateMap = getStateMap();
523
- if (nextStateMap) {
524
- if (stateMap !== nextStateMap) {
525
- stateMap.unobserveDeep(stateObserver);
526
- stateMap = nextStateMap;
527
- stateMap.observeDeep(stateObserver);
528
- }
529
- enqueueSnapshot(toPlainObject(nextStateMap));
530
- return;
531
- }
532
- const currentState = map.get(STATE_KEY);
533
- if (isPlainObject(currentState)) {
534
- const migrated = createYMap(currentState);
535
- doc.transact(() => {
536
- map.set(STATE_KEY, migrated);
537
- }, localOrigin);
538
- if (stateMap !== migrated) {
539
- stateMap.unobserveDeep(stateObserver);
540
- stateMap = migrated;
541
- stateMap.observeDeep(stateObserver);
542
- }
543
- enqueueSnapshot(currentState);
544
- }
545
- };
546
- map.observe(observer);
547
- const unsubscribe = store.subscribe(() => {
548
- syncNow();
549
- });
550
- const binding = {
551
- doc,
552
- map,
553
- syncNow,
554
- destroy: () => {
555
- if (destroyed) {
556
- return;
557
- }
558
- destroyed = true;
559
- unsubscribe();
560
- map.unobserve(observer);
561
- stateMap.unobserveDeep(stateObserver);
562
- if (!options.doc) {
563
- doc.destroy();
564
- }
565
- }
566
- };
567
- if (process.env.NODE_ENV === "test") {
568
- binding.__unsafeTestOnly__ = {
569
- applyRemoteOperations: (operations) => {
570
- applyRemoteOperations(operations);
571
- }
572
- };
573
- }
574
- return binding;
418
+ const __unsafeTestOnly__ = {
419
+ getYValueAtPath: (root, path) => getYValueAtPath(root, path),
420
+ setAtPath: (target, path, value) => {
421
+ setAtPath(target, path, value);
422
+ },
423
+ deleteAtPath: (target, path) => {
424
+ deleteAtPath(target, path);
425
+ }
575
426
  };
576
- var yjs = (options = {}) => (store) => {
577
- const binding = bindYjs(store, options);
578
- const baseDestroy = store.destroy;
579
- store.destroy = () => {
580
- binding.destroy();
581
- baseDestroy();
582
- };
583
- return store;
427
+ const bindYjs = (store, options = {}) => {
428
+ if (store.share === "client") throw new Error("Yjs binding is not supported in client store mode.");
429
+ const doc = options.doc ?? new Y.Doc();
430
+ const key = options.key ?? `coaction:${store.name}`;
431
+ const map = doc.getMap(key);
432
+ const localOrigin = Symbol(`coaction-yjs:${store.name}`);
433
+ let destroyed = false;
434
+ let syncingFromYjs = false;
435
+ assertYjsSerializableState(store.getPureState());
436
+ let lastSyncedState = (() => {
437
+ const pureState = clone(store.getPureState());
438
+ return isPlainObject(pureState) ? pureState : {};
439
+ })();
440
+ let flushScheduled = false;
441
+ let pendingSnapshot = null;
442
+ let pendingOperations = [];
443
+ const restoreLastSyncedState = () => {
444
+ syncingFromYjs = true;
445
+ try {
446
+ store.apply(lastSyncedState);
447
+ } finally {
448
+ syncingFromYjs = false;
449
+ }
450
+ };
451
+ const applyReplacementState = (next) => {
452
+ if (store.share === "main") {
453
+ store.setState(next, () => {
454
+ return applyRootReplacementWithPatches(store, next);
455
+ });
456
+ return;
457
+ }
458
+ store.setState(null);
459
+ store.apply(next);
460
+ };
461
+ const applyRemoteState = (state) => {
462
+ assertYjsSerializableState(state);
463
+ const next = sanitizePlainValue(state);
464
+ syncingFromYjs = true;
465
+ try {
466
+ applyReplacementState(next);
467
+ const pureState = clone(store.getPureState());
468
+ lastSyncedState = isPlainObject(pureState) ? pureState : {};
469
+ } finally {
470
+ syncingFromYjs = false;
471
+ }
472
+ };
473
+ const applyRemoteOperations = (operations) => {
474
+ if (operations.length === 0) return;
475
+ assertRemoteOperationsSerializable(operations);
476
+ syncingFromYjs = true;
477
+ try {
478
+ if (operations.some((operation) => operation.type === "delete" && operation.path.length === 1)) {
479
+ const next = clone(store.getPureState());
480
+ if (!isPlainObject(next)) return;
481
+ for (const operation of operations) if (operation.type === "set") setAtPath(next, operation.path, operation.value);
482
+ else deleteAtPath(next, operation.path);
483
+ applyReplacementState(next);
484
+ const pureState = clone(store.getPureState());
485
+ lastSyncedState = isPlainObject(pureState) ? pureState : {};
486
+ return;
487
+ }
488
+ store.setState((draft) => {
489
+ const mutableDraft = draft;
490
+ for (const operation of operations) if (operation.type === "set") setAtPath(mutableDraft, operation.path, operation.value);
491
+ else deleteAtPath(mutableDraft, operation.path);
492
+ });
493
+ const pureState = clone(store.getPureState());
494
+ lastSyncedState = isPlainObject(pureState) ? pureState : {};
495
+ } finally {
496
+ syncingFromYjs = false;
497
+ }
498
+ };
499
+ const getStateMap = () => {
500
+ const state = map.get(STATE_KEY);
501
+ if (state instanceof Y.Map) return state;
502
+ return null;
503
+ };
504
+ const scheduleFlushFromYjs = () => {
505
+ if (destroyed || flushScheduled) return;
506
+ flushScheduled = true;
507
+ scheduleMicrotask(flushFromYjs);
508
+ };
509
+ const flushFromYjs = () => {
510
+ flushScheduled = false;
511
+ if (destroyed) return;
512
+ if (pendingSnapshot) {
513
+ const snapshot = pendingSnapshot;
514
+ pendingSnapshot = null;
515
+ pendingOperations = [];
516
+ try {
517
+ applyRemoteState(snapshot);
518
+ } catch (error) {
519
+ if (isSetStateReentryError(error)) {
520
+ pendingSnapshot = snapshot;
521
+ setTimeout(scheduleFlushFromYjs, 0);
522
+ return;
523
+ }
524
+ if (isYjsSerializableStateError(error) || isStateSchemaError(error)) {
525
+ restoreRootState();
526
+ return;
527
+ }
528
+ throw error;
529
+ }
530
+ }
531
+ if (pendingOperations.length === 0) return;
532
+ const operations = compactOperations(pendingOperations);
533
+ pendingOperations = [];
534
+ try {
535
+ applyRemoteOperations(operations);
536
+ } catch (error) {
537
+ if (isSetStateReentryError(error)) {
538
+ pendingOperations = [...operations, ...pendingOperations];
539
+ setTimeout(scheduleFlushFromYjs, 0);
540
+ return;
541
+ }
542
+ if (isYjsSerializableStateError(error) || isStateSchemaError(error)) {
543
+ restoreRootState();
544
+ return;
545
+ }
546
+ throw error;
547
+ }
548
+ };
549
+ const enqueueSnapshot = (snapshot) => {
550
+ pendingSnapshot = snapshot;
551
+ pendingOperations = [];
552
+ scheduleFlushFromYjs();
553
+ };
554
+ const enqueueOperations = (operations) => {
555
+ if (operations.length === 0) return;
556
+ if (!pendingSnapshot) pendingOperations.push(...operations);
557
+ scheduleFlushFromYjs();
558
+ };
559
+ const syncNow = () => {
560
+ if (destroyed || syncingFromYjs) return;
561
+ try {
562
+ assertYjsSerializableState(store.getPureState());
563
+ } catch (error) {
564
+ restoreLastSyncedState();
565
+ throw error;
566
+ }
567
+ const pureState = clone(store.getPureState());
568
+ if (!isPlainObject(pureState)) return;
569
+ doc.transact(() => {
570
+ syncObjectToYMap(stateMap, lastSyncedState, pureState);
571
+ }, localOrigin);
572
+ lastSyncedState = pureState;
573
+ };
574
+ const stateObserver = (events, transaction) => {
575
+ if (transaction.origin === localOrigin) return;
576
+ enqueueOperations(collectRemoteOperations(events, stateMap));
577
+ };
578
+ let stateMap;
579
+ let stateMapObserved = false;
580
+ const unobserveStateMap = () => {
581
+ if (!stateMapObserved) return;
582
+ stateMap.unobserveDeep(stateObserver);
583
+ stateMapObserved = false;
584
+ };
585
+ const observeStateMap = (nextStateMap) => {
586
+ if (stateMap === nextStateMap && stateMapObserved) return;
587
+ unobserveStateMap();
588
+ stateMap = nextStateMap;
589
+ stateMap.observeDeep(stateObserver);
590
+ stateMapObserved = true;
591
+ };
592
+ const migrateRootState = (nextState) => {
593
+ const migrated = createYMap(nextState);
594
+ doc.transact(() => {
595
+ map.set(STATE_KEY, migrated);
596
+ }, localOrigin);
597
+ observeStateMap(migrated);
598
+ enqueueSnapshot(nextState);
599
+ };
600
+ const restoreRootState = () => {
601
+ const pureState = clone(store.getPureState());
602
+ const nextState = isPlainObject(pureState) ? pureState : lastSyncedState;
603
+ const restored = createYMap(nextState);
604
+ doc.transact(() => {
605
+ map.set(STATE_KEY, restored);
606
+ }, localOrigin);
607
+ observeStateMap(restored);
608
+ lastSyncedState = nextState;
609
+ };
610
+ const applyInitialRemoteState = (state) => {
611
+ runWithoutHistoryRecording(store, () => {
612
+ try {
613
+ applyRemoteState(state);
614
+ } catch (error) {
615
+ if (isYjsSerializableStateError(error) || isStateSchemaError(error)) {
616
+ restoreRootState();
617
+ return;
618
+ }
619
+ throw error;
620
+ }
621
+ });
622
+ };
623
+ const existingStateMap = getStateMap();
624
+ if (existingStateMap) {
625
+ stateMap = existingStateMap;
626
+ applyInitialRemoteState(toPlainObject(stateMap));
627
+ } else {
628
+ const currentState = map.get(STATE_KEY);
629
+ if (isPlainObject(currentState)) {
630
+ stateMap = createYMap(currentState);
631
+ doc.transact(() => {
632
+ map.set(STATE_KEY, stateMap);
633
+ }, localOrigin);
634
+ applyInitialRemoteState(currentState);
635
+ } else {
636
+ const pureState = clone(store.getPureState());
637
+ stateMap = createYMap(isPlainObject(pureState) ? pureState : {});
638
+ doc.transact(() => {
639
+ map.set(STATE_KEY, stateMap);
640
+ }, localOrigin);
641
+ }
642
+ }
643
+ observeStateMap(stateMap);
644
+ const observer = (event) => {
645
+ if (event.transaction.origin === localOrigin) return;
646
+ if (!event.keysChanged.has(STATE_KEY)) return;
647
+ const stateChange = event.changes.keys.get(STATE_KEY);
648
+ const nextStateMap = getStateMap();
649
+ if (nextStateMap) {
650
+ observeStateMap(nextStateMap);
651
+ enqueueSnapshot(toPlainObject(nextStateMap));
652
+ return;
653
+ }
654
+ const currentState = map.get(STATE_KEY);
655
+ if (isPlainObject(currentState)) {
656
+ migrateRootState(currentState);
657
+ return;
658
+ }
659
+ if (stateChange?.action === "delete") {
660
+ migrateRootState({});
661
+ return;
662
+ }
663
+ restoreRootState();
664
+ };
665
+ map.observe(observer);
666
+ const unsubscribe = store.subscribe(() => {
667
+ syncNow();
668
+ });
669
+ const binding = {
670
+ doc,
671
+ map,
672
+ syncNow,
673
+ destroy: () => {
674
+ if (destroyed) return;
675
+ destroyed = true;
676
+ unsubscribe();
677
+ map.unobserve(observer);
678
+ unobserveStateMap();
679
+ if (!options.doc) doc.destroy();
680
+ }
681
+ };
682
+ if (process.env.NODE_ENV === "test") binding.__unsafeTestOnly__ = { applyRemoteOperations: (operations) => {
683
+ applyRemoteOperations(operations);
684
+ } };
685
+ return binding;
584
686
  };
585
-
586
- // index.ts
587
- __reExport(index_exports, src_exports);
588
- export {
589
- __unsafeTestOnly__,
590
- bindYjs,
591
- yjs
687
+ const yjs = (options = {}) => (store) => {
688
+ let binding;
689
+ const cancelBinding = onStoreReady(store, () => {
690
+ binding = bindYjs(store, options);
691
+ });
692
+ const baseDestroy = store.destroy;
693
+ let destroyed = false;
694
+ store.destroy = () => {
695
+ if (destroyed) return;
696
+ destroyed = true;
697
+ cancelBinding();
698
+ binding?.destroy();
699
+ binding = void 0;
700
+ baseDestroy();
701
+ };
702
+ return store;
592
703
  };
704
+ //#endregion
705
+ export { __unsafeTestOnly__, bindYjs, yjs };