@coaction/yjs 1.5.0 → 2.0.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,728 @@
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 { 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;
124
125
  }
125
126
  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
- );
127
+ const deduplicated = /* @__PURE__ */ new Map();
128
+ for (const operation of operations) {
129
+ const key = toPathKey(operation.path);
130
+ if (deduplicated.has(key)) deduplicated.delete(key);
131
+ deduplicated.set(key, operation);
132
+ }
133
+ return Array.from(deduplicated.values()).sort((left, right) => left.path.length - right.path.length);
137
134
  }
138
135
  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;
136
+ let current = root;
137
+ for (const segment of path) {
138
+ if (current instanceof Y.Map) {
139
+ current = current.get(String(segment));
140
+ continue;
141
+ }
142
+ if (current instanceof Y.Array) {
143
+ const index = toArrayIndex(segment);
144
+ if (typeof index === "undefined") return;
145
+ current = current.get(index);
146
+ continue;
147
+ }
148
+ return;
149
+ }
150
+ return current;
156
151
  }
157
152
  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);
153
+ if (path.length === 0) return;
154
+ if (path.some(isUnsafePathSegment)) return;
155
+ let current = target;
156
+ for (let index = 0; index < path.length - 1; index += 1) {
157
+ const segment = path[index];
158
+ const nextSegment = path[index + 1];
159
+ const segmentIndex = Array.isArray(current) ? toArrayIndex(segment) : void 0;
160
+ const targetKey = typeof segmentIndex === "undefined" ? segment : segmentIndex;
161
+ const nextValue = current[targetKey];
162
+ const needsArray = typeof nextSegment === "number" || Array.isArray(nextValue) && typeof toArrayIndex(nextSegment) !== "undefined";
163
+ if (typeof nextValue !== "object" || nextValue === null || (needsArray ? !Array.isArray(nextValue) : Array.isArray(nextValue))) current[targetKey] = typeof nextSegment === "number" ? [] : {};
164
+ current = current[targetKey];
165
+ }
166
+ const leaf = path[path.length - 1];
167
+ const leafIndex = Array.isArray(current) ? toArrayIndex(leaf) : void 0;
168
+ current[typeof leafIndex === "undefined" ? leaf : leafIndex] = cloneForStore(value);
173
169
  }
174
170
  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];
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 segmentIndex = Array.isArray(current) ? toArrayIndex(segment) : void 0;
177
+ current = current[typeof segmentIndex === "undefined" ? segment : segmentIndex];
178
+ if (typeof current !== "object" || current === null) return;
179
+ }
180
+ const leaf = path[path.length - 1];
181
+ if (Array.isArray(current)) {
182
+ const leafIndex = toArrayIndex(leaf);
183
+ if (typeof leafIndex !== "undefined" && leafIndex >= 0 && leafIndex < current.length) current.splice(leafIndex, 1);
184
+ return;
185
+ }
186
+ delete current[leaf];
193
187
  }
194
188
  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;
189
+ const operations = [];
190
+ for (const event of events) {
191
+ if (event instanceof Y.YMapEvent) {
192
+ for (const changedKey of event.keysChanged) {
193
+ const path = [...event.path, changedKey];
194
+ if (path.some(isUnsafePathSegment)) continue;
195
+ if (event.changes.keys.get(changedKey)?.action === "delete") {
196
+ operations.push({
197
+ type: "delete",
198
+ path
199
+ });
200
+ continue;
201
+ }
202
+ operations.push({
203
+ type: "set",
204
+ path,
205
+ value: toPlainValue(getYValueAtPath(stateMap, path))
206
+ });
207
+ }
208
+ continue;
209
+ }
210
+ if (event instanceof Y.YArrayEvent) {
211
+ const path = [...event.path];
212
+ operations.push({
213
+ type: "set",
214
+ path,
215
+ value: toPlainValue(getYValueAtPath(stateMap, path))
216
+ });
217
+ }
218
+ }
219
+ return operations;
226
220
  }
227
-
228
- // src/sync.ts
229
- import * as Y3 from "yjs";
221
+ //#endregion
222
+ //#region packages/coaction-yjs/src/sync.ts
230
223
  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;
224
+ if (Object.is(left, right)) return true;
225
+ if (Array.isArray(left) && Array.isArray(right)) {
226
+ if (left.length !== right.length) return false;
227
+ for (let index = 0; index < left.length; index += 1) if (!isEqualValue(left[index], right[index])) return false;
228
+ return true;
229
+ }
230
+ if (isPlainObject(left) && isPlainObject(right)) {
231
+ const leftKeys = Object.keys(left);
232
+ const rightKeys = Object.keys(right);
233
+ if (leftKeys.length !== rightKeys.length) return false;
234
+ for (const key of leftKeys) {
235
+ if (!Object.prototype.hasOwnProperty.call(right, key)) return false;
236
+ if (!isEqualValue(left[key], right[key])) return false;
237
+ }
238
+ return true;
239
+ }
240
+ return false;
262
241
  }
263
242
  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
- }
243
+ target.forEach((_value, key) => {
244
+ if (isUnsafeKey(key)) target.delete(key);
245
+ });
246
+ const keys = /* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(source)]);
247
+ for (const key of keys) {
248
+ if (isUnsafeKey(key)) {
249
+ target.delete(key);
250
+ continue;
251
+ }
252
+ const hasPrevious = Object.prototype.hasOwnProperty.call(previous, key);
253
+ if (!Object.prototype.hasOwnProperty.call(source, key)) {
254
+ target.delete(key);
255
+ continue;
256
+ }
257
+ const previousValue = hasPrevious ? previous[key] : void 0;
258
+ const nextValue = source[key];
259
+ if (hasPrevious && isEqualValue(previousValue, nextValue)) continue;
260
+ const current = target.get(key);
261
+ if (Array.isArray(nextValue)) {
262
+ if (Array.isArray(previousValue) && current instanceof Y.Array) syncArrayToYArray(current, previousValue, nextValue);
263
+ else target.set(key, createYArray(nextValue));
264
+ continue;
265
+ }
266
+ if (isPlainObject(nextValue)) {
267
+ if (isPlainObject(previousValue) && current instanceof Y.Map) syncObjectToYMap(current, previousValue, nextValue);
268
+ else target.set(key, createYMap(nextValue));
269
+ continue;
270
+ }
271
+ const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
272
+ if (!Object.is(current, normalized)) target.set(key, normalized);
273
+ }
299
274
  }
300
275
  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
- }
276
+ if (target.length > source.length) target.delete(source.length, target.length - source.length);
277
+ const maxLength = Math.max(previous.length, source.length);
278
+ for (let index = 0; index < maxLength; index += 1) {
279
+ const hasPrevious = index < previous.length;
280
+ if (!(index < source.length)) continue;
281
+ const previousValue = hasPrevious ? previous[index] : void 0;
282
+ const nextValue = source[index];
283
+ if (hasPrevious && isEqualValue(previousValue, nextValue)) continue;
284
+ if (index >= target.length) {
285
+ target.insert(index, [toYValue(nextValue)]);
286
+ continue;
287
+ }
288
+ const current = target.get(index);
289
+ if (Array.isArray(nextValue)) {
290
+ if (Array.isArray(previousValue) && current instanceof Y.Array) syncArrayToYArray(current, previousValue, nextValue);
291
+ else {
292
+ target.delete(index, 1);
293
+ target.insert(index, [createYArray(nextValue)]);
294
+ }
295
+ continue;
296
+ }
297
+ if (isPlainObject(nextValue)) {
298
+ if (isPlainObject(previousValue) && current instanceof Y.Map) syncObjectToYMap(current, previousValue, nextValue);
299
+ else {
300
+ target.delete(index, 1);
301
+ target.insert(index, [createYMap(nextValue)]);
302
+ }
303
+ continue;
304
+ }
305
+ const normalized = typeof nextValue === "object" && nextValue !== null ? clone(nextValue) : nextValue;
306
+ if (!Object.is(current, normalized)) {
307
+ target.delete(index, 1);
308
+ target.insert(index, [normalized]);
309
+ }
310
+ }
345
311
  }
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
- }
312
+ //#endregion
313
+ //#region packages/coaction-yjs/src/index.ts
314
+ const STATE_KEY = "state";
315
+ const historySuppressionSymbol = Symbol.for("coaction.history.suppress");
316
+ const runWithoutHistoryRecording = (store, callback) => {
317
+ const runner = store[historySuppressionSymbol];
318
+ return typeof runner === "function" ? runner(callback) : callback();
319
+ };
320
+ const getOwnEnumerableKeys = (value) => Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key) && !(typeof key === "string" && isUnsafeKey(key)));
321
+ const formatPropertyPath = (path) => path.length ? path.map((key) => String(key)).join(".") : "<root>";
322
+ var YjsSerializableStateError = class extends Error {};
323
+ const isYjsSerializableStateError = (error) => error instanceof YjsSerializableStateError;
324
+ const isArrayIndexKey = (key, length) => {
325
+ if (key === "") return false;
326
+ const index = Number(key);
327
+ return Number.isInteger(index) && index >= 0 && index < length && String(index) === key;
328
+ };
329
+ const findYjsStateViolation = (value, path = [], ancestors = /* @__PURE__ */ new WeakSet()) => {
330
+ switch (typeof value) {
331
+ case "symbol": return {
332
+ type: "symbol-value",
333
+ path
334
+ };
335
+ case "function": return {
336
+ type: "function",
337
+ path
338
+ };
339
+ default: break;
340
+ }
341
+ if (typeof value !== "object" || value === null) return;
342
+ if (ancestors.has(value)) return {
343
+ type: "circular-reference",
344
+ path
345
+ };
346
+ if (Array.isArray(value)) {
347
+ ancestors.add(value);
348
+ for (let index = 0; index < value.length; index += 1) if (!Object.prototype.hasOwnProperty.call(value, index)) return {
349
+ type: "array-hole",
350
+ path: [...path, index]
351
+ };
352
+ for (const key of getOwnEnumerableKeys(value)) {
353
+ const nextPath = [...path, key];
354
+ if (typeof key === "symbol") return {
355
+ type: "symbol-key",
356
+ path: nextPath
357
+ };
358
+ if (!isArrayIndexKey(key, value.length)) return {
359
+ type: "array-property",
360
+ path: nextPath
361
+ };
362
+ const violation = findYjsStateViolation(value[Number(key)], nextPath, ancestors);
363
+ if (violation) return violation;
364
+ }
365
+ ancestors.delete(value);
366
+ return;
367
+ }
368
+ if (!isPlainObject(value)) return {
369
+ type: "non-plain-object",
370
+ path
371
+ };
372
+ ancestors.add(value);
373
+ for (const key of getOwnEnumerableKeys(value)) {
374
+ const nextPath = [...path, key];
375
+ if (typeof key === "symbol") return {
376
+ type: "symbol-key",
377
+ path: nextPath
378
+ };
379
+ const child = value[key];
380
+ const violation = findYjsStateViolation(child, nextPath, ancestors);
381
+ if (violation) return violation;
382
+ }
383
+ ancestors.delete(value);
384
+ };
385
+ const assertYjsSerializableState = (state, path = []) => {
386
+ const violation = findYjsStateViolation(state, path);
387
+ if (!violation) return;
388
+ 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)}.`);
389
+ 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)}.`);
390
+ 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)}.`);
391
+ };
392
+ const assertRemoteOperationsSerializable = (operations) => {
393
+ for (const operation of operations) if (operation.type === "set") assertYjsSerializableState(operation.value, operation.path);
394
+ };
395
+ const createRootReplacementPatches = (currentState, nextState) => {
396
+ const patches = [];
397
+ const inversePatches = [];
398
+ const nextKeys = new Set(getOwnEnumerableKeys(nextState));
399
+ for (const key of getOwnEnumerableKeys(currentState)) {
400
+ if (typeof key === "symbol" || nextKeys.has(key)) continue;
401
+ patches.push({
402
+ op: "remove",
403
+ path: [key]
404
+ });
405
+ inversePatches.push({
406
+ op: "add",
407
+ path: [key],
408
+ value: currentState[key]
409
+ });
410
+ }
411
+ for (const key of nextKeys) {
412
+ if (typeof key === "symbol") continue;
413
+ if (!Object.prototype.hasOwnProperty.call(currentState, key)) {
414
+ patches.push({
415
+ op: "add",
416
+ path: [key],
417
+ value: nextState[key]
418
+ });
419
+ inversePatches.push({
420
+ op: "remove",
421
+ path: [key]
422
+ });
423
+ continue;
424
+ }
425
+ if (Object.is(currentState[key], nextState[key])) continue;
426
+ patches.push({
427
+ op: "replace",
428
+ path: [key],
429
+ value: nextState[key]
430
+ });
431
+ inversePatches.push({
432
+ op: "replace",
433
+ path: [key],
434
+ value: currentState[key]
435
+ });
436
+ }
437
+ return {
438
+ patches,
439
+ inversePatches
440
+ };
359
441
  };
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;
442
+ const __unsafeTestOnly__ = {
443
+ getYValueAtPath: (root, path) => getYValueAtPath(root, path),
444
+ setAtPath: (target, path, value) => {
445
+ setAtPath(target, path, value);
446
+ },
447
+ deleteAtPath: (target, path) => {
448
+ deleteAtPath(target, path);
449
+ }
575
450
  };
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;
451
+ const bindYjs = (store, options = {}) => {
452
+ if (store.share === "client") throw new Error("Yjs binding is not supported in client store mode.");
453
+ const doc = options.doc ?? new Y.Doc();
454
+ const key = options.key ?? `coaction:${store.name}`;
455
+ const map = doc.getMap(key);
456
+ const localOrigin = Symbol(`coaction-yjs:${store.name}`);
457
+ let destroyed = false;
458
+ let syncingFromYjs = false;
459
+ assertYjsSerializableState(store.getPureState());
460
+ let lastSyncedState = (() => {
461
+ const pureState = clone(store.getPureState());
462
+ return isPlainObject(pureState) ? pureState : {};
463
+ })();
464
+ let flushScheduled = false;
465
+ let pendingSnapshot = null;
466
+ let pendingOperations = [];
467
+ const restoreLastSyncedState = () => {
468
+ syncingFromYjs = true;
469
+ try {
470
+ store.apply(lastSyncedState);
471
+ } finally {
472
+ syncingFromYjs = false;
473
+ }
474
+ };
475
+ const applyRemoteState = (state) => {
476
+ assertYjsSerializableState(state);
477
+ const next = sanitizePlainValue(state);
478
+ syncingFromYjs = true;
479
+ try {
480
+ if (store.share === "main") store.setState(next, () => {
481
+ const { patches, inversePatches } = createRootReplacementPatches(store.getPureState(), next);
482
+ const finalPatches = store.patch ? store.patch({
483
+ patches,
484
+ inversePatches
485
+ }) : {
486
+ patches,
487
+ inversePatches
488
+ };
489
+ if (finalPatches.patches.length) store.apply(store.getPureState(), finalPatches.patches);
490
+ return [
491
+ store.getPureState(),
492
+ finalPatches.patches,
493
+ finalPatches.inversePatches
494
+ ];
495
+ });
496
+ else {
497
+ store.setState(null);
498
+ store.apply(next);
499
+ }
500
+ const pureState = clone(store.getPureState());
501
+ lastSyncedState = isPlainObject(pureState) ? pureState : {};
502
+ } finally {
503
+ syncingFromYjs = false;
504
+ }
505
+ };
506
+ const applyRemoteOperations = (operations) => {
507
+ if (operations.length === 0) return;
508
+ assertRemoteOperationsSerializable(operations);
509
+ syncingFromYjs = true;
510
+ try {
511
+ store.setState((draft) => {
512
+ const mutableDraft = draft;
513
+ for (const operation of operations) if (operation.type === "set") setAtPath(mutableDraft, operation.path, operation.value);
514
+ else deleteAtPath(mutableDraft, operation.path);
515
+ });
516
+ const pureState = clone(store.getPureState());
517
+ lastSyncedState = isPlainObject(pureState) ? pureState : {};
518
+ } finally {
519
+ syncingFromYjs = false;
520
+ }
521
+ };
522
+ const getStateMap = () => {
523
+ const state = map.get(STATE_KEY);
524
+ if (state instanceof Y.Map) return state;
525
+ return null;
526
+ };
527
+ const scheduleFlushFromYjs = () => {
528
+ if (destroyed || flushScheduled) return;
529
+ flushScheduled = true;
530
+ scheduleMicrotask(flushFromYjs);
531
+ };
532
+ const flushFromYjs = () => {
533
+ flushScheduled = false;
534
+ if (destroyed) return;
535
+ if (pendingSnapshot) {
536
+ const snapshot = pendingSnapshot;
537
+ pendingSnapshot = null;
538
+ pendingOperations = [];
539
+ try {
540
+ applyRemoteState(snapshot);
541
+ } catch (error) {
542
+ if (isSetStateReentryError(error)) {
543
+ pendingSnapshot = snapshot;
544
+ setTimeout(scheduleFlushFromYjs, 0);
545
+ return;
546
+ }
547
+ if (isYjsSerializableStateError(error)) {
548
+ restoreRootState();
549
+ return;
550
+ }
551
+ throw error;
552
+ }
553
+ }
554
+ if (pendingOperations.length === 0) return;
555
+ const operations = compactOperations(pendingOperations);
556
+ pendingOperations = [];
557
+ try {
558
+ applyRemoteOperations(operations);
559
+ } catch (error) {
560
+ if (isSetStateReentryError(error)) {
561
+ pendingOperations = [...operations, ...pendingOperations];
562
+ setTimeout(scheduleFlushFromYjs, 0);
563
+ return;
564
+ }
565
+ if (isYjsSerializableStateError(error)) {
566
+ restoreRootState();
567
+ return;
568
+ }
569
+ throw error;
570
+ }
571
+ };
572
+ const enqueueSnapshot = (snapshot) => {
573
+ pendingSnapshot = snapshot;
574
+ pendingOperations = [];
575
+ scheduleFlushFromYjs();
576
+ };
577
+ const enqueueOperations = (operations) => {
578
+ if (operations.length === 0) return;
579
+ if (!pendingSnapshot) pendingOperations.push(...operations);
580
+ scheduleFlushFromYjs();
581
+ };
582
+ const syncNow = () => {
583
+ if (destroyed || syncingFromYjs) return;
584
+ try {
585
+ assertYjsSerializableState(store.getPureState());
586
+ } catch (error) {
587
+ restoreLastSyncedState();
588
+ throw error;
589
+ }
590
+ const pureState = clone(store.getPureState());
591
+ if (!isPlainObject(pureState)) return;
592
+ doc.transact(() => {
593
+ syncObjectToYMap(stateMap, lastSyncedState, pureState);
594
+ }, localOrigin);
595
+ lastSyncedState = pureState;
596
+ };
597
+ const stateObserver = (events, transaction) => {
598
+ if (transaction.origin === localOrigin) return;
599
+ enqueueOperations(collectRemoteOperations(events, stateMap));
600
+ };
601
+ let stateMap;
602
+ let stateMapObserved = false;
603
+ const unobserveStateMap = () => {
604
+ if (!stateMapObserved) return;
605
+ stateMap.unobserveDeep(stateObserver);
606
+ stateMapObserved = false;
607
+ };
608
+ const observeStateMap = (nextStateMap) => {
609
+ if (stateMap === nextStateMap && stateMapObserved) return;
610
+ unobserveStateMap();
611
+ stateMap = nextStateMap;
612
+ stateMap.observeDeep(stateObserver);
613
+ stateMapObserved = true;
614
+ };
615
+ const migrateRootState = (nextState) => {
616
+ const migrated = createYMap(nextState);
617
+ doc.transact(() => {
618
+ map.set(STATE_KEY, migrated);
619
+ }, localOrigin);
620
+ observeStateMap(migrated);
621
+ enqueueSnapshot(nextState);
622
+ };
623
+ const restoreRootState = () => {
624
+ const pureState = clone(store.getPureState());
625
+ const nextState = isPlainObject(pureState) ? pureState : lastSyncedState;
626
+ const restored = createYMap(nextState);
627
+ doc.transact(() => {
628
+ map.set(STATE_KEY, restored);
629
+ }, localOrigin);
630
+ observeStateMap(restored);
631
+ lastSyncedState = nextState;
632
+ };
633
+ const applyInitialRemoteState = (state) => {
634
+ runWithoutHistoryRecording(store, () => {
635
+ try {
636
+ applyRemoteState(state);
637
+ } catch (error) {
638
+ if (isYjsSerializableStateError(error)) {
639
+ restoreRootState();
640
+ return;
641
+ }
642
+ throw error;
643
+ }
644
+ });
645
+ };
646
+ const existingStateMap = getStateMap();
647
+ if (existingStateMap) {
648
+ stateMap = existingStateMap;
649
+ applyInitialRemoteState(toPlainObject(stateMap));
650
+ } else {
651
+ const currentState = map.get(STATE_KEY);
652
+ if (isPlainObject(currentState)) {
653
+ stateMap = createYMap(currentState);
654
+ doc.transact(() => {
655
+ map.set(STATE_KEY, stateMap);
656
+ }, localOrigin);
657
+ applyInitialRemoteState(currentState);
658
+ } else {
659
+ const pureState = clone(store.getPureState());
660
+ stateMap = createYMap(isPlainObject(pureState) ? pureState : {});
661
+ doc.transact(() => {
662
+ map.set(STATE_KEY, stateMap);
663
+ }, localOrigin);
664
+ }
665
+ }
666
+ observeStateMap(stateMap);
667
+ const observer = (event) => {
668
+ if (event.transaction.origin === localOrigin) return;
669
+ if (!event.keysChanged.has(STATE_KEY)) return;
670
+ const stateChange = event.changes.keys.get(STATE_KEY);
671
+ const nextStateMap = getStateMap();
672
+ if (nextStateMap) {
673
+ observeStateMap(nextStateMap);
674
+ enqueueSnapshot(toPlainObject(nextStateMap));
675
+ return;
676
+ }
677
+ const currentState = map.get(STATE_KEY);
678
+ if (isPlainObject(currentState)) {
679
+ migrateRootState(currentState);
680
+ return;
681
+ }
682
+ if (stateChange?.action === "delete") {
683
+ migrateRootState({});
684
+ return;
685
+ }
686
+ restoreRootState();
687
+ };
688
+ map.observe(observer);
689
+ const unsubscribe = store.subscribe(() => {
690
+ syncNow();
691
+ });
692
+ const binding = {
693
+ doc,
694
+ map,
695
+ syncNow,
696
+ destroy: () => {
697
+ if (destroyed) return;
698
+ destroyed = true;
699
+ unsubscribe();
700
+ map.unobserve(observer);
701
+ unobserveStateMap();
702
+ if (!options.doc) doc.destroy();
703
+ }
704
+ };
705
+ if (process.env.NODE_ENV === "test") binding.__unsafeTestOnly__ = { applyRemoteOperations: (operations) => {
706
+ applyRemoteOperations(operations);
707
+ } };
708
+ return binding;
584
709
  };
585
-
586
- // index.ts
587
- __reExport(index_exports, src_exports);
588
- export {
589
- __unsafeTestOnly__,
590
- bindYjs,
591
- yjs
710
+ const yjs = (options = {}) => (store) => {
711
+ let binding;
712
+ const cancelBinding = onStoreReady(store, () => {
713
+ binding = bindYjs(store, options);
714
+ });
715
+ const baseDestroy = store.destroy;
716
+ let destroyed = false;
717
+ store.destroy = () => {
718
+ if (destroyed) return;
719
+ destroyed = true;
720
+ cancelBinding();
721
+ binding?.destroy();
722
+ binding = void 0;
723
+ baseDestroy();
724
+ };
725
+ return store;
592
726
  };
727
+ //#endregion
728
+ export { __unsafeTestOnly__, bindYjs, yjs };