@mengine/medeo-client 2.1.1-dsl.0 → 2.1.1-dsl.10

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.
@@ -0,0 +1,1486 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { Cursor } from "loro-crdt";
3
+ //#region ../medeo-dsl/src/ids.ts
4
+ function bytesToBase64url(bytes) {
5
+ let binary = "";
6
+ for (const byte of bytes) binary += String.fromCharCode(byte);
7
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
8
+ }
9
+ function base64urlToBytes(value) {
10
+ if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) throw new Error("Invalid base64url");
11
+ const bytes = Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/")), (c) => c.charCodeAt(0));
12
+ if (bytesToBase64url(bytes) !== value) throw new Error("Non-canonical base64url");
13
+ return bytes;
14
+ }
15
+ function tupleHash(tuple) {
16
+ return bytesToBase64url(sha256(new TextEncoder().encode(JSON.stringify(tuple))));
17
+ }
18
+ function resourceId(kind, system, key) {
19
+ return `${kind}:${tupleHash([system, key])}`;
20
+ }
21
+ function relationId(table, value) {
22
+ const v = value;
23
+ switch (table) {
24
+ case "voice-timbre-relations": return `voice-timbre:${tupleHash([v.recordingId, v.voiceId])}`;
25
+ case "derived-from-relations": return `derived-from:${tupleHash([v.entityId, v.sourceId])}`;
26
+ }
27
+ throw new Error(`Unknown relation table: ${table}`);
28
+ }
29
+ const defaultIdFactory = (kind) => `${kind}_${globalThis.crypto.randomUUID()}`;
30
+ const resourceKinds = {
31
+ "media-entities": "media",
32
+ "voice-entities": "voice"
33
+ };
34
+ /** A resource row's ID is derived from its locator, so one external resource is one entity. */
35
+ function assertResourceIdentity(table, id, value) {
36
+ const kind = resourceKinds[table];
37
+ if (kind && id !== resourceId(kind, value.system, value.key)) throw new Error("Resource identity does not match locator");
38
+ }
39
+ /** A relation row's ID is derived from its two ends. */
40
+ function assertRelationIdentity(table, id, value) {
41
+ if (id !== relationId(table, value)) throw new Error("Relation ID does not match endpoints");
42
+ }
43
+ //#endregion
44
+ //#region ../medeo-dsl/src/fields.ts
45
+ const string = (v) => typeof v === "string";
46
+ const nonempty = (v) => string(v) && v.length > 0;
47
+ const finite = (v) => typeof v === "number" && Number.isFinite(v);
48
+ const integer = (v) => typeof v === "number" && Number.isSafeInteger(v);
49
+ const nonnegative = (v) => integer(v) && v >= 0;
50
+ const positive = (v) => integer(v) && v > 0;
51
+ const oneOf = (...values) => (v) => values.includes(v);
52
+ const required = (check) => ({ check });
53
+ const optional$1 = (check) => ({
54
+ check,
55
+ optional: true
56
+ });
57
+ const reservedIds = [
58
+ "$cid",
59
+ "__proto__",
60
+ "constructor",
61
+ "prototype"
62
+ ];
63
+ const id = (v) => nonempty(v) && !reservedIds.includes(v);
64
+ const cursor = (v) => v instanceof Cursor;
65
+ function isRecord(value) {
66
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Cursor);
67
+ }
68
+ function assertId(value) {
69
+ if (!id(value)) throw new Error("Expected a nonempty, non-reserved ID");
70
+ }
71
+ function validLanguage(value) {
72
+ if (typeof value !== "string") return false;
73
+ if (/^x(?:-[a-z0-9]{1,8})+$/i.test(value)) return true;
74
+ try {
75
+ return value.length > 0 && Intl.getCanonicalLocales(value).length === 1;
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ function object(fields) {
81
+ return (v) => {
82
+ try {
83
+ checkFields(v, fields);
84
+ return true;
85
+ } catch {
86
+ return false;
87
+ }
88
+ };
89
+ }
90
+ function checkFields(value, fields, partial = false) {
91
+ if (!isRecord(value)) throw new Error("Expected an object");
92
+ for (const key of Object.keys(value)) if (!Object.hasOwn(fields, key)) throw new Error(`Unknown field: ${key}`);
93
+ for (const [key, field] of Object.entries(fields)) {
94
+ if (partial && !Object.hasOwn(value, key)) continue;
95
+ const v = value[key];
96
+ if (v === void 0 && field.optional) continue;
97
+ if (!field.check(v)) throw new Error(`Invalid or missing field: ${key}`);
98
+ }
99
+ }
100
+ const styleFields = {
101
+ font: optional$1(object({
102
+ system: required(oneOf("font-library")),
103
+ key: required(nonempty)
104
+ })),
105
+ fontSize: optional$1(finite),
106
+ fontColor: optional$1(string),
107
+ fontWeight: optional$1(finite),
108
+ entranceAnimation: optional$1(string),
109
+ entranceAnimationDurationMs: optional$1(nonnegative),
110
+ strokeColor: optional$1(string),
111
+ strokeWidth: optional$1(finite),
112
+ positionX: optional$1(finite),
113
+ positionY: optional$1(finite)
114
+ };
115
+ const seqMarkerFields = {
116
+ inMs: required(nonnegative),
117
+ outMs: required(nonnegative),
118
+ rate: optional$1((v) => finite(v) && v > 0),
119
+ fillTimeline: optional$1(oneOf(true))
120
+ };
121
+ /** A sequence marker's own fields; the window being nonempty is checked where it is written. */
122
+ function assertSeqMarker(value) {
123
+ checkFields(value, seqMarkerFields);
124
+ }
125
+ const timeAnchorFields = {
126
+ to: required(id),
127
+ offsetMs: required(integer),
128
+ fallback_abs_ms: required(nonnegative)
129
+ };
130
+ /** A time anchor's own fields; what it points at is checked by `assertReferenceAdmitted`. */
131
+ function assertTimeAnchor(value) {
132
+ checkFields(value, timeAnchorFields);
133
+ }
134
+ const selectionFields = {
135
+ audioScriptId: required(id),
136
+ segmentId: required(id),
137
+ start: optional$1(cursor),
138
+ end: optional$1(cursor)
139
+ };
140
+ /** A whole segment, or a run inside it: both ends or neither. */
141
+ const segmentSelection = (fields) => (v) => object(fields)(v) && v.start === void 0 === (v.end === void 0);
142
+ function assertCaptionContent(value) {
143
+ if (!segmentSelection(selectionFields)(value)) throw new Error("Invalid segment selection");
144
+ }
145
+ const phonemeFields = {
146
+ ...selectionFields,
147
+ phonemeScript: optional$1(string)
148
+ };
149
+ function assertPhoneme(value) {
150
+ if (!segmentSelection(phonemeFields)(value)) throw new Error("Invalid phoneme");
151
+ }
152
+ const segmentFields = {
153
+ id: required(id),
154
+ text: required(string)
155
+ };
156
+ /** A script's segments: each with its own id, unique within the script. */
157
+ const segments = (v) => Array.isArray(v) && v.every(object(segmentFields)) && new Set(v.map((segment) => segment.id)).size === v.length;
158
+ const locator = {
159
+ system: required(oneOf("memota", "memota-speech")),
160
+ key: required(nonempty)
161
+ };
162
+ const entityFields = {
163
+ "timeline-entities": {},
164
+ "track-entities": {
165
+ role: required(oneOf("video_clip", "speech", "caption", "bgm")),
166
+ hidden: optional$1((v) => typeof v === "boolean")
167
+ },
168
+ "clip-entities": {
169
+ seqMarker: required(object(seqMarkerFields)),
170
+ volume: optional$1(finite),
171
+ source: required(id),
172
+ anchor: optional$1(object(timeAnchorFields))
173
+ },
174
+ "media-entities": {
175
+ ...locator,
176
+ kind: required(oneOf("video", "audio", "voiceover-recording", "image")),
177
+ storageKey: optional$1(nonempty),
178
+ durationMs: optional$1(positive),
179
+ digest: optional$1(nonempty)
180
+ },
181
+ "audio-script-entities": {
182
+ segments: required(segments),
183
+ defaultLanguage: optional$1(validLanguage)
184
+ },
185
+ "phonetic-script-entities": {
186
+ phoneme: optional$1(segmentSelection(phonemeFields)),
187
+ system: optional$1(oneOf("memota")),
188
+ key: optional$1(nonempty),
189
+ storageKey: optional$1(nonempty),
190
+ digest: optional$1(nonempty)
191
+ },
192
+ "caption-entities": {
193
+ selection: optional$1(segmentSelection(selectionFields)),
194
+ text: optional$1(string),
195
+ style: optional$1(object(styleFields))
196
+ },
197
+ "voice-entities": {
198
+ system: required(oneOf("voice-library")),
199
+ key: required(nonempty),
200
+ name: optional$1(string)
201
+ }
202
+ };
203
+ const entityTables = Object.keys(entityFields);
204
+ /**
205
+ * Fields stored as one encoded string: written whole, never merged field by field. A patch to one
206
+ * is merged into the current value first, then the whole value is written.
207
+ */
208
+ const atomicFields = {
209
+ "clip-entities": ["seqMarker", "anchor"],
210
+ "phonetic-script-entities": ["phoneme"],
211
+ "caption-entities": ["selection"]
212
+ };
213
+ const relationFields = {
214
+ "voice-timbre-relations": {
215
+ recordingId: required(id),
216
+ voiceId: required(id)
217
+ },
218
+ "derived-from-relations": {
219
+ entityId: required(id),
220
+ sourceId: required(id),
221
+ sourceDigest: optional$1(nonempty)
222
+ }
223
+ };
224
+ const relationTables = Object.keys(relationFields);
225
+ const fileFields = [
226
+ "system",
227
+ "key",
228
+ "storageKey",
229
+ "digest"
230
+ ];
231
+ const phonemeScriptOf = (row) => isRecord(row.phoneme) ? row.phoneme.phonemeScript : void 0;
232
+ /**
233
+ * A PhoneticScript as a write leaves it: written for a segment (D181), and its phonemeScript is raw
234
+ * content stored as its file (D178) — with text the row names that file and its digest, without
235
+ * text it has no file, and rewritten text is a new file.
236
+ */
237
+ function assertPhoneticScript(before, after) {
238
+ if (!isRecord(after.phoneme)) throw new Error("A PhoneticScript is written for a segment of its base script");
239
+ if (phonemeScriptOf(after) === void 0) {
240
+ if (fileFields.some((field) => after[field] !== void 0)) throw new Error("A PhoneticScript without text has no file");
241
+ } else if (after.system === void 0 || after.key === void 0 || after.digest === void 0) throw new Error("A PhoneticScript stores its phonemeScript as a file: name it by system and key with its digest");
242
+ if (before !== void 0 && phonemeScriptOf(after) !== phonemeScriptOf(before) && after.digest !== void 0 && after.digest === before.digest) throw new Error("A rewritten phonemeScript is stored again: write its new file");
243
+ }
244
+ function assertEntity(table, value) {
245
+ checkFields(value, entityFields[table]);
246
+ if (table === "media-entities") {
247
+ if (value.kind === "image" && value.durationMs !== void 0) throw new Error("Image has no intrinsic duration");
248
+ if (value.kind !== "image" && !positive(value.durationMs)) throw new Error("Finite media requires durationMs");
249
+ if (["audio", "voiceover-recording"].includes(value.kind) && !nonempty(value.storageKey)) throw new Error("Audio requires storageKey");
250
+ }
251
+ }
252
+ /** Validate only touched fields, so an unrelated edit can proceed in a merged, invalid document. */
253
+ function assertEntityPatch(table, patch, current) {
254
+ if (!isRecord(patch)) throw new Error("Expected an entity patch");
255
+ if (table === "audio-script-entities" && Object.hasOwn(patch, "segments")) throw new Error("Change segments with segment mutations and edit their text through the Text adapter");
256
+ if (table === "caption-entities" && current.style !== void 0 && Object.hasOwn(patch, "style") && patch.style === void 0) throw new Error("Reset individual style fields; retain the style Map");
257
+ if (table === "caption-entities" && current.text !== void 0 && patch.text !== void 0) throw new Error("Edit Caption text through the Text adapter");
258
+ const next = patchRow(table, current, patch);
259
+ for (const key of Object.keys(patch)) {
260
+ const field = entityFields[table][key];
261
+ if (!field || !field.optional && next[key] === void 0 || next[key] !== void 0 && !field.check(next[key])) throw new Error(`Invalid patch field: ${key}`);
262
+ }
263
+ if (table === "media-entities" || table === "voice-entities") {
264
+ for (const key of [
265
+ "system",
266
+ "key",
267
+ "kind"
268
+ ]) if (Object.hasOwn(patch, key) && patch[key] !== current[key]) throw new Error(`Resource identity field is immutable: ${key}`);
269
+ }
270
+ if (table === "media-entities") {
271
+ if (Object.hasOwn(patch, "durationMs")) {
272
+ if (next.kind === "image" ? next.durationMs !== void 0 : !positive(next.durationMs)) throw new Error("durationMs must match the media kind");
273
+ }
274
+ if (Object.hasOwn(patch, "storageKey") && ["audio", "voiceover-recording"].includes(next.kind) && !nonempty(next.storageKey)) throw new Error("Audio requires storageKey");
275
+ }
276
+ }
277
+ function assertRelation(table, value) {
278
+ checkFields(value, relationFields[table]);
279
+ }
280
+ /**
281
+ * The row after a patch. An atomic field merges into its current value, so a partial patch keeps
282
+ * the rest of it; an unreadable stored value is replaced instead, so writing a whole value repairs it.
283
+ */
284
+ function patchRow(table, current, patch) {
285
+ const next = mergeFields(current, patch);
286
+ for (const key of atomicFields[table] ?? []) {
287
+ const old = current[key];
288
+ const value = patch[key];
289
+ if (value !== void 0 && isRecord(old) && old.invalid === true) next[key] = isRecord(value) ? mergeFields({}, value) : value;
290
+ }
291
+ return next;
292
+ }
293
+ /** Undefined deletes; nested patches retain sibling fields and an existing empty style Map. */
294
+ function mergeFields(target, patch) {
295
+ const result = { ...target };
296
+ for (const [key, value] of Object.entries(patch)) {
297
+ if (reservedIds.includes(key)) throw new Error(`Reserved field: ${key}`);
298
+ if (value === void 0) delete result[key];
299
+ else result[key] = isRecord(value) ? mergeFields(isRecord(result[key]) ? result[key] : {}, value) : value;
300
+ }
301
+ return result;
302
+ }
303
+ //#endregion
304
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/schema/resolver.js
305
+ function getMapFieldSchema(schema, key) {
306
+ if (!schema) return void 0;
307
+ if (Object.prototype.hasOwnProperty.call(schema.definition, key)) return schema.definition[key];
308
+ if (schema.type === "loro-map" && "catchallType" in schema) return schema.catchallType;
309
+ }
310
+ function getChildSchema(schema, childKey) {
311
+ if (!schema) return void 0;
312
+ switch (schema.type) {
313
+ case "schema":
314
+ case "loro-map": return childKey === void 0 ? void 0 : getMapFieldSchema(schema, String(childKey));
315
+ case "loro-list":
316
+ case "loro-movable-list": return schema.itemSchema;
317
+ case "loro-tree": return schema.nodeSchema;
318
+ default: return;
319
+ }
320
+ }
321
+ function getChildContainerSchema(schema, childKey) {
322
+ const childSchema = getChildSchema(schema, childKey);
323
+ if (!childSchema) return void 0;
324
+ switch (childSchema.type) {
325
+ case "loro-map":
326
+ case "loro-list":
327
+ case "loro-movable-list":
328
+ case "loro-text":
329
+ case "loro-tree": return childSchema;
330
+ default: return;
331
+ }
332
+ }
333
+ //#endregion
334
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/constants.js
335
+ const CID_KEY = "$cid";
336
+ //#endregion
337
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/core/container-inference.js
338
+ function isPlainObjectValue(value) {
339
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && typeof value !== "function";
340
+ }
341
+ function inferContainerTypeFromValue$1(value, defaults) {
342
+ switch (getContainerValueKind(value)) {
343
+ case "map": return "Map";
344
+ case "array": return defaults?.defaultMovableList ? "MovableList" : "List";
345
+ case "string": return defaults?.defaultLoroText ? "Text" : void 0;
346
+ default: return;
347
+ }
348
+ }
349
+ function inferSchemaContainerTypeFromValue(value, defaults) {
350
+ switch (inferContainerTypeFromValue$1(value, defaults)) {
351
+ case "Map": return "loro-map";
352
+ case "List": return "loro-list";
353
+ case "MovableList": return "loro-movable-list";
354
+ case "Text": return "loro-text";
355
+ default: return;
356
+ }
357
+ }
358
+ function matchesContainerType(containerType, value) {
359
+ const kind = getContainerValueKind(value);
360
+ switch (containerType) {
361
+ case "Map": return kind === "map";
362
+ case "List":
363
+ case "MovableList":
364
+ case "Tree": return kind === "array";
365
+ case "Text": return kind === "string";
366
+ default: return false;
367
+ }
368
+ }
369
+ function getContainerValueKind(value) {
370
+ if (isPlainObjectValue(value)) return "map";
371
+ if (Array.isArray(value)) return "array";
372
+ if (typeof value === "string") return "string";
373
+ return "other";
374
+ }
375
+ //#endregion
376
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/core/utils.js
377
+ /**
378
+ * Utility functions for Loro Mirror core
379
+ */
380
+ /**
381
+ * Check if a schema has a transform.
382
+ * Distinguishes between the .transform() builder method (function) and an actual
383
+ * TransformDefinition object (with decode/encode functions).
384
+ */
385
+ function hasTransform(schema) {
386
+ if (schema === void 0) return false;
387
+ const t = schema.transform;
388
+ return t != null && typeof t === "object";
389
+ }
390
+ /**
391
+ * Get the transform from a schema, or undefined if none exists.
392
+ */
393
+ function getTransform(schema) {
394
+ if (hasTransform(schema)) return schema.transform;
395
+ }
396
+ /**
397
+ * Get the effective equality strategy for a transform.
398
+ * Default: "reference-equality"
399
+ */
400
+ function getEqualityStrategy(schema, strategyIfNotTransformable) {
401
+ const transform = getTransform(schema);
402
+ if (!transform) return strategyIfNotTransformable;
403
+ return transform.isEqual ?? "reference-equality";
404
+ }
405
+ /**
406
+ * Apply decode transform to a CRDT value.
407
+ * Null/undefined pass through as-is - transform is only called for real values.
408
+ */
409
+ function applyDecode(schema, crdtValue) {
410
+ if (crdtValue === null || crdtValue === void 0) return crdtValue;
411
+ const transform = getTransform(schema);
412
+ return transform ? transform.decode(crdtValue) : crdtValue;
413
+ }
414
+ /**
415
+ * Recursively decode JSON values using schema transforms.
416
+ * Mutates in-place. Used for snapshot initialization where toJSON() skips decode.
417
+ */
418
+ function decodeNestedJsonValues(json, schema) {
419
+ if (json === null || json === void 0 || !schema) return json;
420
+ switch (schema.type) {
421
+ case "loro-map":
422
+ if (!isObject(json)) return json;
423
+ for (const key of Object.keys(json)) {
424
+ const fieldSchema = getChildSchema(schema, key);
425
+ json[key] = decodeNestedJsonValues(json[key], fieldSchema);
426
+ }
427
+ return json;
428
+ case "loro-list":
429
+ case "loro-movable-list": {
430
+ if (!Array.isArray(json)) return json;
431
+ const itemSchema = getChildSchema(schema);
432
+ for (let i = 0; i < json.length; i++) json[i] = decodeNestedJsonValues(json[i], itemSchema);
433
+ return json;
434
+ }
435
+ case "loro-tree": {
436
+ if (!Array.isArray(json)) return json;
437
+ const nodeSchema = getChildSchema(schema);
438
+ const walk = (nodes) => {
439
+ for (const node of nodes) if (node != null && typeof node == "object") {
440
+ if ("data" in node && node.data !== void 0) node.data = decodeNestedJsonValues(node.data, nodeSchema);
441
+ if ("children" in node && Array.isArray(node.children)) walk(node.children);
442
+ }
443
+ };
444
+ walk(json);
445
+ return json;
446
+ }
447
+ case "loro-text":
448
+ case "ignore": return json;
449
+ default: return applyDecode(schema, json);
450
+ }
451
+ }
452
+ /**
453
+ * Apply encode transform to a domain value.
454
+ * Null/undefined pass through as-is - transform is only called for real values.
455
+ */
456
+ function applyEncode(schema, domainValue) {
457
+ if (domainValue === null || domainValue === void 0) return domainValue;
458
+ const transform = getTransform(schema);
459
+ return transform ? transform.encode(domainValue) : domainValue;
460
+ }
461
+ /**
462
+ * Check if two domain values are equal according to the schema's equality strategy.
463
+ *
464
+ * Reference equality is always checked first (performance optimization).
465
+ * If refs match, returns true (no change).
466
+ * If refs differ, behavior depends on isEqual setting.
467
+ */
468
+ function valuesEqual(schema, oldValue, newValue, strategyIfNotTransformable) {
469
+ if (oldValue === newValue) return true;
470
+ const strategy = getEqualityStrategy(schema, strategyIfNotTransformable);
471
+ if (strategy === "reference-equality") return false;
472
+ else if (strategy === "encoded-value-equality") return applyEncode(schema, oldValue) === applyEncode(schema, newValue);
473
+ else if (strategy === "deep-equality") return deepEqual(oldValue, newValue);
474
+ else return strategy(oldValue, newValue);
475
+ }
476
+ function defineCidProperty(target, cid) {
477
+ if (!isObject(target) || Object.prototype.hasOwnProperty.call(target, "$cid")) return;
478
+ Object.defineProperty(target, CID_KEY, { value: cid });
479
+ }
480
+ /**
481
+ * Restore the read-only `$cid` contract on a freshly produced state.
482
+ *
483
+ * `defineCidProperty` stamps `$cid` as `{ writable: false, enumerable: false,
484
+ * configurable: false }`. Immer's `useStrictShallowCopy` preserves the descriptor, but it
485
+ * deliberately rewrites every non-writable data property to `{ writable: true,
486
+ * configurable: true }` so the draft stays mutable — which would leave `$cid` writable on
487
+ * every object Immer copied, letting callers reassign a published `$cid`.
488
+ *
489
+ * Two things keep this proportional to what Immer actually copied rather than to the size
490
+ * of the state:
491
+ *
492
+ * - `prev` is the state `produce` was called with, and Immer shares everything it did not
493
+ * copy, so a subtree reference-equal to `prev` cannot have been touched.
494
+ * - An already-locked `$cid` means this object was not copied this round, so its children
495
+ * are the same references they were when it was last hardened and are locked too. This
496
+ * is what makes a reorder cheap: moved items are shared references that land at a new
497
+ * index, so `prev` no longer lines up with them, but they are still locked.
498
+ */
499
+ function hardenCidDescriptors(next, prev, visited) {
500
+ if (next === prev) return;
501
+ if (Array.isArray(next)) {
502
+ if ((visited ?? (visited = /* @__PURE__ */ new Set())).has(next)) return;
503
+ visited.add(next);
504
+ const prevArr = Array.isArray(prev) ? prev : void 0;
505
+ for (let i = 0; i < next.length; i++) hardenCidDescriptors(next[i], prevArr?.[i], visited);
506
+ return;
507
+ }
508
+ if (!isObject(next)) return;
509
+ const descriptor = Object.getOwnPropertyDescriptor(next, CID_KEY);
510
+ if (descriptor) {
511
+ if (!descriptor.configurable) return;
512
+ if ("value" in descriptor) Object.defineProperty(next, CID_KEY, {
513
+ value: descriptor.value,
514
+ writable: false,
515
+ enumerable: false,
516
+ configurable: false
517
+ });
518
+ }
519
+ if ((visited ?? (visited = /* @__PURE__ */ new Set())).has(next)) return;
520
+ visited.add(next);
521
+ const prevObj = isObject(prev) ? prev : void 0;
522
+ for (const key of Object.keys(next)) hardenCidDescriptors(next[key], prevObj?.[key], visited);
523
+ }
524
+ /**
525
+ * Check if a value is an object
526
+ */
527
+ function isObject(value) {
528
+ return isPlainObjectValue(value);
529
+ }
530
+ const UNSAFE_KEYS = new Set([
531
+ "__proto__",
532
+ "constructor",
533
+ "prototype"
534
+ ]);
535
+ /**
536
+ * Recursively removes undefined values from an object.
537
+ * This treats undefined values as non-existent fields.
538
+ * Preserves non-enumerable properties like $cid.
539
+ * Returns the original object if no undefined values are found.
540
+ * Protects against prototype pollution by skipping unsafe keys.
541
+ */
542
+ function stripUndefined(value) {
543
+ return stripUndefinedInner(value, 0, void 0);
544
+ }
545
+ /**
546
+ * Depth at which we start recording the recursion path to detect cycles.
547
+ *
548
+ * This runs over the whole state on every `setState`, and tracking every node costs more
549
+ * than the stripping itself. Mirror state is a tree whose depth follows the schema, so a
550
+ * real state never gets near this; only a cycle recurses without bound. Once the path is
551
+ * being recorded, any cycle revisits one of its own nodes within a single lap, so starting
552
+ * late still terminates.
553
+ */
554
+ const CYCLE_GUARD_DEPTH = 64;
555
+ /**
556
+ * Placeholder for a key that must not reach the rebuilt object: an unsafe key, or one whose
557
+ * value is `undefined` and is therefore treated as a non-existent field.
558
+ */
559
+ const DROPPED = Symbol("dropped");
560
+ function stripUndefinedInner(value, depth, path) {
561
+ if (value === void 0) return value;
562
+ if (Array.isArray(value)) {
563
+ if (depth >= CYCLE_GUARD_DEPTH) {
564
+ if ((path ?? (path = /* @__PURE__ */ new Set())).has(value)) return value;
565
+ path.add(value);
566
+ }
567
+ let hasChanges = false;
568
+ const result = value.map((item) => {
569
+ const stripped = stripUndefinedInner(item, depth + 1, path);
570
+ if (stripped !== item) hasChanges = true;
571
+ return stripped;
572
+ });
573
+ path?.delete(value);
574
+ return hasChanges ? result : value;
575
+ }
576
+ if (isObject(value)) {
577
+ if (depth >= CYCLE_GUARD_DEPTH) {
578
+ if ((path ?? (path = /* @__PURE__ */ new Set())).has(value)) return value;
579
+ path.add(value);
580
+ }
581
+ const keys = Object.keys(value);
582
+ const strippedValues = Array.from({ length: keys.length });
583
+ let changed = false;
584
+ for (let i = 0; i < keys.length; i++) {
585
+ const key = keys[i];
586
+ if (UNSAFE_KEYS.has(key)) {
587
+ strippedValues[i] = DROPPED;
588
+ continue;
589
+ }
590
+ const val = value[key];
591
+ if (val === void 0) {
592
+ strippedValues[i] = DROPPED;
593
+ changed = true;
594
+ continue;
595
+ }
596
+ const stripped = stripUndefinedInner(val, depth + 1, path);
597
+ strippedValues[i] = stripped;
598
+ if (stripped !== val) changed = true;
599
+ }
600
+ path?.delete(value);
601
+ if (!changed) return value;
602
+ const result = Object.create(null);
603
+ const allProps = Object.getOwnPropertyNames(value);
604
+ for (const key of allProps) {
605
+ if (UNSAFE_KEYS.has(key)) continue;
606
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
607
+ if (descriptor && !descriptor.enumerable) Object.defineProperty(result, key, descriptor);
608
+ }
609
+ for (let i = 0; i < keys.length; i++) {
610
+ const val = strippedValues[i];
611
+ if (val === DROPPED) continue;
612
+ Object.defineProperty(result, keys[i], {
613
+ value: val,
614
+ writable: true,
615
+ enumerable: true,
616
+ configurable: true
617
+ });
618
+ }
619
+ return result;
620
+ }
621
+ return value;
622
+ }
623
+ /**
624
+ * Performs a deep equality check between two values
625
+ */
626
+ function deepEqual(a, b) {
627
+ if (a === b) return true;
628
+ if (a === null || b === null || typeof a !== "object" && typeof a !== "function" || typeof b !== "object" && typeof b !== "function") return false;
629
+ if (Array.isArray(a) && Array.isArray(b)) {
630
+ if (a.length !== b.length) return false;
631
+ for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
632
+ return true;
633
+ }
634
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
635
+ if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
636
+ if (!Array.isArray(a) && !Array.isArray(b)) {
637
+ const keysA = Object.keys(a);
638
+ const keysB = Object.keys(b);
639
+ if (keysA.length !== keysB.length) return false;
640
+ for (const key of keysA) {
641
+ if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
642
+ if (!deepEqual(a[key], b[key])) return false;
643
+ }
644
+ return true;
645
+ }
646
+ return false;
647
+ }
648
+ /**
649
+ * Recursively compare the `$cid` markers of two state trees.
650
+ *
651
+ * `deepEqual` only walks enumerable keys, so it cannot see `$cid` (which is stamped as a
652
+ * non-enumerable descriptor). Used by `Mirror.checkStateConsistency` so that a tampered
653
+ * or stale `$cid` is reported as a divergence instead of silently sitting in the state.
654
+ * Only the markers are compared here; value equality is `deepEqual`'s job.
655
+ */
656
+ function cidsEqual(a, b, seen) {
657
+ if (a === b) return true;
658
+ if (Array.isArray(a) && Array.isArray(b)) {
659
+ if (a.length !== b.length) return false;
660
+ if (markSeen(a, b, seen ?? (seen = /* @__PURE__ */ new Map())) === "seen") return true;
661
+ for (let i = 0; i < a.length; i++) if (!cidsEqual(a[i], b[i], seen)) return false;
662
+ return true;
663
+ }
664
+ if (!isObject(a) || !isObject(b)) return true;
665
+ if (a["$cid"] !== b["$cid"]) return false;
666
+ if (markSeen(a, b, seen ?? (seen = /* @__PURE__ */ new Map())) === "seen") return true;
667
+ for (const key of Object.keys(a)) {
668
+ if (!Object.prototype.hasOwnProperty.call(b, key)) continue;
669
+ if (!cidsEqual(a[key], b[key], seen)) return false;
670
+ }
671
+ return true;
672
+ }
673
+ function markSeen(a, b, seen) {
674
+ let partners = seen.get(a);
675
+ if (!partners) {
676
+ partners = /* @__PURE__ */ new Set();
677
+ seen.set(a, partners);
678
+ }
679
+ if (partners.has(b)) return "seen";
680
+ partners.add(b);
681
+ return "new";
682
+ }
683
+ function containerIdToContainerType(containerId) {
684
+ const parts = containerId.split(":");
685
+ return parts[parts.length - 1];
686
+ }
687
+ function getRootContainerByType(doc, key, type) {
688
+ if (type === "Text") return doc.getText(key);
689
+ else if (type === "List") return doc.getList(key);
690
+ else if (type === "MovableList") return doc.getMovableList(key);
691
+ else if (type === "Map") return doc.getMap(key);
692
+ else if (type === "Tree") return doc.getTree(key);
693
+ else throw new Error();
694
+ }
695
+ function insertChildToMap(containerId, key, value, inferOptions) {
696
+ const ct = tryInferContainerType(value, inferOptions);
697
+ if (ct) return {
698
+ container: containerId,
699
+ key,
700
+ value,
701
+ kind: "insert-container",
702
+ childContainerType: ct
703
+ };
704
+ return {
705
+ container: containerId,
706
+ key,
707
+ value,
708
+ kind: "insert"
709
+ };
710
+ }
711
+ function tryUpdateToContainer(change, toUpdate, schema, inferOptions) {
712
+ if (!toUpdate) return change;
713
+ if (change.kind !== "insert" && change.kind !== "set") return change;
714
+ const effectiveInferOptions = applySchemaToInferOptions(schema, inferOptions);
715
+ const containerType = schema ? schemaToContainerType(schema) ?? tryInferContainerType(change.value, effectiveInferOptions) : tryInferContainerType(change.value, effectiveInferOptions);
716
+ if (containerType == null || schema && hasTransform(schema)) {
717
+ const encodedValue = applyEncode(schema, change.value);
718
+ return encodedValue !== change.value ? {
719
+ ...change,
720
+ value: encodedValue
721
+ } : change;
722
+ }
723
+ if (change.kind === "insert") return {
724
+ container: change.container,
725
+ key: change.key,
726
+ value: change.value,
727
+ kind: "insert-container",
728
+ childContainerType: containerType
729
+ };
730
+ if (change.kind === "set") return {
731
+ container: change.container,
732
+ key: change.key,
733
+ value: change.value,
734
+ kind: "set-container",
735
+ childContainerType: containerType
736
+ };
737
+ return change;
738
+ }
739
+ function schemaToContainerType(schema) {
740
+ const containerType = schema.getContainerType();
741
+ return containerType === null ? void 0 : containerType;
742
+ }
743
+ function tryInferContainerType(value, defaults) {
744
+ return inferContainerTypeFromValue$1(value, defaults);
745
+ }
746
+ function applySchemaToInferOptions(schema, base) {
747
+ if (!schema || schema.type !== "any") return base;
748
+ const next = { ...base };
749
+ next.defaultLoroText = schema.options.defaultLoroText ?? false;
750
+ if (schema.options.defaultMovableList !== void 0) next.defaultMovableList = schema.options.defaultMovableList;
751
+ return next;
752
+ }
753
+ function isValueOfContainerType(containerType, value) {
754
+ return matchesContainerType(containerType, value);
755
+ }
756
+ function inferContainerTypeFromValue(value, defaults) {
757
+ return inferSchemaContainerTypeFromValue(value, defaults);
758
+ }
759
+ function isObjectLike(value) {
760
+ return typeof value === "object";
761
+ }
762
+ function isArrayLike(value) {
763
+ return Array.isArray(value);
764
+ }
765
+ function isStateAndSchemaOfType(values, stateGuard, schemaGuard) {
766
+ return stateGuard(values.oldState) && stateGuard(values.newState) && (!values.schema || schemaGuard(values.schema));
767
+ }
768
+ function isTreeID(id) {
769
+ if (!(typeof id === "string")) return false;
770
+ return !!id.match(/[0-9]+@[0-9]+/);
771
+ }
772
+ /**
773
+ * Stringify a value safely, handling non-JSON-serializable types.
774
+ * Handles BigInt, Date, RegExp, functions, and custom objects.
775
+ */
776
+ function safeStringify(value, indent = 2) {
777
+ const seen = /* @__PURE__ */ new WeakSet();
778
+ function replacer(val) {
779
+ if (val === null || val === void 0) return val;
780
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") return val;
781
+ if (typeof val === "bigint") return `[BigInt: ${val.toString()}]`;
782
+ if (typeof val === "function") return `[Function: ${val.name || "anonymous"}]`;
783
+ if (typeof val === "symbol") return `[Symbol: ${val.description || ""}]`;
784
+ if (typeof val === "object") {
785
+ if (seen.has(val)) return "[Circular]";
786
+ seen.add(val);
787
+ if (val instanceof Date) return `[Date: ${val.toISOString()}]`;
788
+ if (val instanceof RegExp) return `[RegExp: ${val.toString()}]`;
789
+ if (val instanceof Error) return `[Error: ${val.message}]`;
790
+ if (Array.isArray(val)) return val.map(replacer);
791
+ const result = {};
792
+ for (const key of Object.keys(val)) result[key] = replacer(val[key]);
793
+ return result;
794
+ }
795
+ return Object.prototype.toString.call(val);
796
+ }
797
+ return JSON.stringify(replacer(value), null, indent);
798
+ }
799
+ //#endregion
800
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/schema/validators.js
801
+ const schemaValidationCache = /* @__PURE__ */ new WeakMap();
802
+ function isCacheableValue(value) {
803
+ return typeof value === "object" && value !== null;
804
+ }
805
+ function isSchemaValidated(schema, value) {
806
+ if (!isCacheableValue(value)) return false;
807
+ return schemaValidationCache.get(value)?.has(schema) ?? false;
808
+ }
809
+ function markSchemaValidated(schema, value) {
810
+ if (!isCacheableValue(value)) return;
811
+ let cache = schemaValidationCache.get(value);
812
+ if (!cache) {
813
+ cache = /* @__PURE__ */ new WeakSet();
814
+ schemaValidationCache.set(value, cache);
815
+ }
816
+ cache.add(schema);
817
+ }
818
+ /**
819
+ * Type guard for LoroMapSchema
820
+ */
821
+ function isLoroMapSchema(schema) {
822
+ return !!schema && schema.type === "loro-map";
823
+ }
824
+ /**
825
+ * Type guard for LoroListSchema
826
+ */
827
+ function isLoroListSchema(schema) {
828
+ return !!schema && schema.type === "loro-list";
829
+ }
830
+ function isListLikeSchema(schema) {
831
+ return isLoroListSchema(schema) || isLoroMovableListSchema(schema);
832
+ }
833
+ function isLoroMovableListSchema(schema) {
834
+ return !!schema && schema.type === "loro-movable-list";
835
+ }
836
+ /**
837
+ * Type guard for RootSchemaType
838
+ */
839
+ function isRootSchemaType(schema) {
840
+ return !!schema && schema.type === "schema";
841
+ }
842
+ /**
843
+ * Whether a schema subtree contains any `Ignore` field. Recursive schemas are
844
+ * tolerated (each schema object is visited once).
845
+ */
846
+ function schemaContainsIgnoreField(schema) {
847
+ const visited = /* @__PURE__ */ new Set();
848
+ const walk = (s) => {
849
+ if (!s || visited.has(s)) return false;
850
+ visited.add(s);
851
+ if (s.type === "ignore") return true;
852
+ switch (s.type) {
853
+ case "schema":
854
+ case "loro-map": {
855
+ const record = s;
856
+ return Object.values(record.definition).some(walk) || walk(record.catchallType);
857
+ }
858
+ case "loro-list":
859
+ case "loro-movable-list": return walk(s.itemSchema);
860
+ case "loro-tree": return walk(s.nodeSchema);
861
+ default: return false;
862
+ }
863
+ };
864
+ return walk(schema);
865
+ }
866
+ /**
867
+ * Type guard for LoroTreeSchema
868
+ */
869
+ function isLoroTreeSchema(schema) {
870
+ return !!schema && schema.type === "loro-tree";
871
+ }
872
+ /**
873
+ * Check if a schema is for a Loro container
874
+ */
875
+ function isContainerSchema(schema) {
876
+ return !!schema && (schema.type === "loro-map" || schema.type === "loro-list" || schema.type === "loro-text" || schema.type === "loro-movable-list" || schema.type === "loro-tree");
877
+ }
878
+ /**
879
+ * Validate a value against a schema
880
+ *
881
+ * When `options.ignoreUnknownProperties` is true, the root schema check does
882
+ * not reject properties missing from the schema definition — typically
883
+ * written by peers on a newer schema version. (Nested map schemas never
884
+ * reject undeclared properties.)
885
+ */
886
+ function validateSchema(schema, value, options) {
887
+ const errors = [];
888
+ const actualType = schema.type;
889
+ if (schema.options.required && (value === void 0 || value === null)) {
890
+ errors.push("Value is required");
891
+ return {
892
+ valid: false,
893
+ errors
894
+ };
895
+ }
896
+ if (value === void 0 || value === null) return { valid: true };
897
+ const useCache = !options?.ignoreUnknownProperties;
898
+ if (useCache && isSchemaValidated(schema, value)) return { valid: true };
899
+ switch (actualType) {
900
+ case "any":
901
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && value !== null && value !== void 0 && !Array.isArray(value) && !isObject(value)) errors.push("Value must be JSON-like");
902
+ break;
903
+ case "string":
904
+ case "number":
905
+ case "boolean":
906
+ validateTransformablePrimitive(schema, value, actualType, errors);
907
+ break;
908
+ case "ignore": break;
909
+ case "loro-text":
910
+ if (typeof value !== "string") errors.push("Content must be a string");
911
+ break;
912
+ case "loro-map":
913
+ if (!isObject(value)) errors.push("Value must be an object");
914
+ else if (isLoroMapSchema(schema)) {
915
+ for (const key in schema.definition) if (Object.prototype.hasOwnProperty.call(schema.definition, key)) {
916
+ const propSchema = schema.definition[key];
917
+ const propValue = value[key];
918
+ const result = validateSchema(propSchema, propValue);
919
+ if (!result.valid && result.errors) {
920
+ const prefixedErrors = result.errors.map((err) => `${key}: ${err}`);
921
+ errors.push(...prefixedErrors);
922
+ }
923
+ }
924
+ }
925
+ break;
926
+ case "loro-movable-list":
927
+ case "loro-list":
928
+ if (!Array.isArray(value)) errors.push("Value must be an array");
929
+ else if (isLoroListSchema(schema) || isLoroMovableListSchema(schema)) {
930
+ const itemSchema = schema.itemSchema;
931
+ value.forEach((item, index) => {
932
+ const result = validateSchema(itemSchema, item);
933
+ if (!result.valid && result.errors) {
934
+ const prefixedErrors = result.errors.map((err) => `Item ${index}: ${err}`);
935
+ errors.push(...prefixedErrors);
936
+ }
937
+ });
938
+ }
939
+ break;
940
+ case "loro-tree": {
941
+ if (!Array.isArray(value)) {
942
+ errors.push("Value must be an array of tree nodes");
943
+ break;
944
+ }
945
+ if (!isLoroTreeSchema(schema)) {
946
+ errors.push("Invalid tree schema");
947
+ break;
948
+ }
949
+ const validateNode = (node, path) => {
950
+ if (!isObject(node)) {
951
+ errors.push(`${path}: Node must be an object`);
952
+ return;
953
+ }
954
+ const n = node;
955
+ if (n.id != null && typeof n.id !== "string") errors.push(`${path}: id must be a string if provided`);
956
+ const dataResult = validateSchema(schema.nodeSchema, n.data);
957
+ if (!dataResult.valid && dataResult.errors) errors.push(...dataResult.errors.map((e) => `${path}.data: ${e}`));
958
+ if (!Array.isArray(n.children)) errors.push(`${path}: children must be an array`);
959
+ else n.children.forEach((child, idx) => {
960
+ validateNode(child, `${path}.children[${idx}]`);
961
+ });
962
+ };
963
+ value.forEach((node, i) => {
964
+ validateNode(node, `node[${i}]`);
965
+ });
966
+ break;
967
+ }
968
+ case "schema":
969
+ if (!isObject(value)) errors.push("Value must be an object");
970
+ else if (isRootSchemaType(schema)) if (!isObject(value)) errors.push("Value must be an object");
971
+ else {
972
+ for (const key in schema.definition) if (Object.prototype.hasOwnProperty.call(schema.definition, key)) {
973
+ const propSchema = schema.definition[key];
974
+ const propValue = value[key];
975
+ const result = validateSchema(propSchema, propValue);
976
+ if (!result.valid && result.errors) {
977
+ const prefixedErrors = result.errors.map((err) => `${key}: ${err}`);
978
+ errors.push(...prefixedErrors);
979
+ }
980
+ }
981
+ for (const key in value) if (!Object.prototype.hasOwnProperty.call(schema.definition, key)) {
982
+ if (options?.ignoreUnknownProperties) continue;
983
+ errors.push(`Unknown property: ${key}`);
984
+ }
985
+ }
986
+ else errors.push(`Should be a schema, but got ${actualType}`);
987
+ break;
988
+ default: errors.push(`Unknown schema type: ${actualType}`);
989
+ }
990
+ if (schema.options.validate && typeof schema.options.validate === "function") try {
991
+ const customValidation = schema.options.validate(value);
992
+ if (customValidation !== true) {
993
+ const errorMessage = typeof customValidation === "string" ? customValidation : "Value failed custom validation";
994
+ errors.push(errorMessage);
995
+ }
996
+ } catch (error) {
997
+ errors.push(`Validation error: ${String(error)}`);
998
+ }
999
+ if (errors.length === 0) {
1000
+ if (useCache) markSchemaValidated(schema, value);
1001
+ return { valid: true };
1002
+ }
1003
+ return {
1004
+ valid: false,
1005
+ errors
1006
+ };
1007
+ }
1008
+ function validateTransformablePrimitive(schema, value, expectedType, errors) {
1009
+ const transform = getTransform(schema);
1010
+ if (transform) {
1011
+ if (transform.validate) try {
1012
+ const result = transform.validate(value);
1013
+ if (result !== true) errors.push(typeof result === "string" ? result : "Transform validation failed");
1014
+ } catch (error) {
1015
+ errors.push(`Transform validation error: ${String(error)}`);
1016
+ }
1017
+ if (transform.validateEncodedType) try {
1018
+ const encoded = applyEncode(schema, value);
1019
+ if (typeof encoded !== expectedType) errors.push(`Transform encode must return a ${expectedType}, got ${typeof encoded}`);
1020
+ } catch (error) {
1021
+ errors.push(`Transform encode validation error: ${String(error)}`);
1022
+ }
1023
+ } else if (typeof value !== expectedType) errors.push(`Value must be a ${expectedType}`);
1024
+ }
1025
+ /**
1026
+ * Get default value for a schema
1027
+ * Based on the schema type, it might return a plain value or a wrapped value
1028
+ */
1029
+ function getDefaultValue(schema) {
1030
+ if ("defaultValue" in schema.options) return schema.options.defaultValue;
1031
+ switch (schema.type) {
1032
+ case "any": return;
1033
+ case "string":
1034
+ if (schema.options.required === false) return;
1035
+ if (getTransform(schema)) return;
1036
+ return "";
1037
+ case "number":
1038
+ if (schema.options.required === false) return;
1039
+ if (getTransform(schema)) return;
1040
+ return 0;
1041
+ case "boolean":
1042
+ if (schema.options.required === false) return;
1043
+ if (getTransform(schema)) return;
1044
+ return false;
1045
+ case "loro-text": {
1046
+ const value = schema.options.required ? "" : void 0;
1047
+ if (value === void 0) return void 0;
1048
+ return value;
1049
+ }
1050
+ case "loro-map":
1051
+ if (isLoroMapSchema(schema)) {
1052
+ const result = {};
1053
+ for (const key in schema.definition) if (Object.prototype.hasOwnProperty.call(schema.definition, key)) {
1054
+ const value = getDefaultValue(schema.definition[key]);
1055
+ if (value !== void 0) result[key] = value;
1056
+ }
1057
+ return result;
1058
+ }
1059
+ return {};
1060
+ case "loro-list": return [];
1061
+ case "loro-tree": {
1062
+ const value = schema.options.required ? [] : void 0;
1063
+ if (value === void 0) return void 0;
1064
+ return value;
1065
+ }
1066
+ case "schema":
1067
+ if (isRootSchemaType(schema)) {
1068
+ const result = {};
1069
+ for (const key in schema.definition) if (Object.prototype.hasOwnProperty.call(schema.definition, key)) {
1070
+ const value = getDefaultValue(schema.definition[key]);
1071
+ if (value !== void 0) result[key] = value;
1072
+ }
1073
+ return result;
1074
+ }
1075
+ return {};
1076
+ default: return;
1077
+ }
1078
+ }
1079
+ //#endregion
1080
+ //#region ../../node_modules/.pnpm/loro-mirror@2.3.3_patch_hash=a551a0e4aa4f61ec88b0d9e970a183b5ee2955107a2e0bb03b378bc510c2f395_loro-crdt@1.16.1/node_modules/loro-mirror/dist/schema/index.js
1081
+ /**
1082
+ * Create a schema definition
1083
+ */
1084
+ function schema(definition, options) {
1085
+ return {
1086
+ type: "schema",
1087
+ definition,
1088
+ options: options || {},
1089
+ getContainerType() {
1090
+ return "Map";
1091
+ }
1092
+ };
1093
+ }
1094
+ /**
1095
+ * Define a string field
1096
+ */
1097
+ schema.String = (function(options) {
1098
+ const baseSchema = {
1099
+ type: "string",
1100
+ options: options || {},
1101
+ getContainerType: () => {
1102
+ return null;
1103
+ }
1104
+ };
1105
+ return {
1106
+ ...baseSchema,
1107
+ transform: (def) => ({
1108
+ ...baseSchema,
1109
+ transform: def
1110
+ })
1111
+ };
1112
+ });
1113
+ /**
1114
+ * Define an any field (runtime-inferred by Mirror)
1115
+ */
1116
+ schema.Any = function(options) {
1117
+ return {
1118
+ type: "any",
1119
+ options: options || {},
1120
+ getContainerType: () => {
1121
+ return null;
1122
+ }
1123
+ };
1124
+ };
1125
+ /**
1126
+ * Define a number field
1127
+ */
1128
+ schema.Number = function(options) {
1129
+ const baseSchema = {
1130
+ type: "number",
1131
+ options: options || {},
1132
+ getContainerType: () => {
1133
+ return null;
1134
+ }
1135
+ };
1136
+ return {
1137
+ ...baseSchema,
1138
+ transform: (def) => ({
1139
+ ...baseSchema,
1140
+ transform: def
1141
+ })
1142
+ };
1143
+ };
1144
+ /**
1145
+ * Define a boolean field
1146
+ */
1147
+ schema.Boolean = function(options) {
1148
+ const baseSchema = {
1149
+ type: "boolean",
1150
+ options: options || {},
1151
+ getContainerType: () => {
1152
+ return null;
1153
+ }
1154
+ };
1155
+ return {
1156
+ ...baseSchema,
1157
+ transform: (def) => ({
1158
+ ...baseSchema,
1159
+ transform: def
1160
+ })
1161
+ };
1162
+ };
1163
+ /**
1164
+ * Define a field to be ignored (not synced with Loro)
1165
+ */
1166
+ schema.Ignore = function(options) {
1167
+ return {
1168
+ type: "ignore",
1169
+ options: options || {},
1170
+ getContainerType: () => {
1171
+ return null;
1172
+ }
1173
+ };
1174
+ };
1175
+ /**
1176
+ * Define a Loro map
1177
+ */
1178
+ schema.LoroMap = function(definition, options) {
1179
+ const baseSchema = {
1180
+ type: "loro-map",
1181
+ definition,
1182
+ options: options || {},
1183
+ getContainerType: () => {
1184
+ return "Map";
1185
+ }
1186
+ };
1187
+ const schemaWithCatchall = {
1188
+ ...baseSchema,
1189
+ catchall: (catchallSchema) => {
1190
+ return {
1191
+ ...baseSchema,
1192
+ catchallType: catchallSchema,
1193
+ catchall: (newCatchallSchema) => {
1194
+ return {
1195
+ ...baseSchema,
1196
+ catchallType: newCatchallSchema,
1197
+ catchall: schemaWithCatchall.catchall
1198
+ };
1199
+ }
1200
+ };
1201
+ }
1202
+ };
1203
+ return schemaWithCatchall;
1204
+ };
1205
+ /**
1206
+ * Create a dynamic record schema (like zod's z.record)
1207
+ */
1208
+ schema.LoroMapRecord = function(valueSchema, options) {
1209
+ return {
1210
+ type: "loro-map",
1211
+ definition: {},
1212
+ catchallType: valueSchema,
1213
+ options: options || {},
1214
+ getContainerType: () => {
1215
+ return "Map";
1216
+ },
1217
+ catchall: (newCatchallSchema) => {
1218
+ return schema.LoroMapRecord(newCatchallSchema, options);
1219
+ }
1220
+ };
1221
+ };
1222
+ /**
1223
+ * Define a Loro list
1224
+ */
1225
+ schema.LoroList = function(itemSchema, idSelector, options) {
1226
+ return {
1227
+ type: "loro-list",
1228
+ itemSchema,
1229
+ idSelector,
1230
+ options: options || {},
1231
+ getContainerType: () => {
1232
+ return "List";
1233
+ }
1234
+ };
1235
+ };
1236
+ schema.LoroMovableList = function(itemSchema, idSelector, options) {
1237
+ return {
1238
+ type: "loro-movable-list",
1239
+ itemSchema,
1240
+ idSelector,
1241
+ options: options || {},
1242
+ getContainerType: () => {
1243
+ return "MovableList";
1244
+ }
1245
+ };
1246
+ };
1247
+ /**
1248
+ * Define a Loro text field
1249
+ */
1250
+ schema.LoroText = function(options) {
1251
+ return {
1252
+ type: "loro-text",
1253
+ options: options || {},
1254
+ getContainerType: () => {
1255
+ return "Text";
1256
+ }
1257
+ };
1258
+ };
1259
+ /**
1260
+ * Define a Loro tree
1261
+ *
1262
+ * Each tree node has a `data` map described by `nodeSchema`.
1263
+ */
1264
+ schema.LoroTree = function(nodeSchema, options) {
1265
+ return {
1266
+ type: "loro-tree",
1267
+ nodeSchema,
1268
+ options: options || {},
1269
+ getContainerType() {
1270
+ return "Tree";
1271
+ }
1272
+ };
1273
+ };
1274
+ //#endregion
1275
+ //#region ../medeo-dsl/src/schema/codec.ts
1276
+ function isInvalidAtomic(value) {
1277
+ return typeof value === "object" && value !== null && "invalid" in value && value.invalid === true;
1278
+ }
1279
+ function codec(encode, decode) {
1280
+ return {
1281
+ encode: (v) => isInvalidAtomic(v) ? v.raw : encode(v),
1282
+ decode: (raw) => {
1283
+ try {
1284
+ return decode(raw);
1285
+ } catch (error) {
1286
+ return {
1287
+ invalid: true,
1288
+ raw,
1289
+ reason: String(error)
1290
+ };
1291
+ }
1292
+ }
1293
+ };
1294
+ }
1295
+ /** A Clip's time anchor; the Clip holding it is the anchored end. */
1296
+ const timeAnchorCodec = codec((v) => {
1297
+ assertTimeAnchor(v);
1298
+ return JSON.stringify({
1299
+ to: v.to,
1300
+ offsetMs: v.offsetMs,
1301
+ fallback_abs_ms: v.fallback_abs_ms
1302
+ });
1303
+ }, (raw) => {
1304
+ const v = JSON.parse(raw);
1305
+ assertTimeAnchor(v);
1306
+ return v;
1307
+ });
1308
+ /** A segment selection as stored: a run's Cursors as their native bytes in unpadded base64url. */
1309
+ function encodeSelection(v) {
1310
+ return {
1311
+ audioScriptId: v.audioScriptId,
1312
+ segmentId: v.segmentId,
1313
+ ...v.start === void 0 || v.end === void 0 ? {} : {
1314
+ start: bytesToBase64url(v.start.encode()),
1315
+ end: bytesToBase64url(v.end.encode())
1316
+ }
1317
+ };
1318
+ }
1319
+ function decodeSelection(v) {
1320
+ if (!v || typeof v !== "object") throw new Error("Expected a segment selection");
1321
+ const { start, end, ...rest } = v;
1322
+ if (start === void 0 && end === void 0) return rest;
1323
+ if (typeof start !== "string" || typeof end !== "string") throw new Error("Expected encoded Cursor pair");
1324
+ return {
1325
+ ...rest,
1326
+ start: Cursor.decode(base64urlToBytes(start)),
1327
+ end: Cursor.decode(base64urlToBytes(end))
1328
+ };
1329
+ }
1330
+ /** A Caption's selection. */
1331
+ const captionContentCodec = codec((v) => {
1332
+ assertCaptionContent(v);
1333
+ return JSON.stringify(encodeSelection(v));
1334
+ }, (raw) => {
1335
+ const value = decodeSelection(JSON.parse(raw));
1336
+ assertCaptionContent(value);
1337
+ return value;
1338
+ });
1339
+ /** A PhoneticScript's selection and what to synthesize for it, stored as one string so they move together. */
1340
+ const phonemeCodec = codec((v) => {
1341
+ assertPhoneme(v);
1342
+ return JSON.stringify({
1343
+ ...encodeSelection(v),
1344
+ ...v.phonemeScript === void 0 ? {} : { phonemeScript: v.phonemeScript }
1345
+ });
1346
+ }, (raw) => {
1347
+ const value = decodeSelection(JSON.parse(raw));
1348
+ assertPhoneme(value);
1349
+ return value;
1350
+ });
1351
+ /** A Clip's sequence marker is stored as one string, so it is taken or replaced whole. */
1352
+ const seqMarkerCodec = codec((v) => {
1353
+ assertSeqMarker(v);
1354
+ return JSON.stringify({
1355
+ inMs: v.inMs,
1356
+ outMs: v.outMs,
1357
+ ...v.rate === void 0 ? {} : { rate: v.rate },
1358
+ ...v.fillTimeline === void 0 ? {} : { fillTimeline: v.fillTimeline }
1359
+ });
1360
+ }, (raw) => {
1361
+ const v = JSON.parse(raw);
1362
+ assertSeqMarker(v);
1363
+ return v;
1364
+ });
1365
+ //#endregion
1366
+ //#region ../medeo-dsl/src/schema/loro-shape.ts
1367
+ const optional = { required: false };
1368
+ const mergeable = { mergeableMapChildContainers: true };
1369
+ const strings = (keys) => Object.fromEntries(keys.map((key) => [key, schema.String()]));
1370
+ const relation = (keys) => schema.LoroMapRecord(schema.LoroMap(strings(keys)), mergeable);
1371
+ const transform = (codec) => ({
1372
+ ...codec,
1373
+ isEqual: "encoded-value-equality",
1374
+ validateEncodedType: true
1375
+ });
1376
+ /** One field stored as one encoded string, so it is taken or replaced whole. */
1377
+ const atomicValue = (codec) => schema.String().transform(transform(codec));
1378
+ const optionalAtomicValue = (codec) => schema.String(optional).transform(transform(codec));
1379
+ /**
1380
+ * Only direct children inherit mergeable identity. Text and ordinary entity rows keep normal
1381
+ * identities, so deleting a row also drops what a peer wrote into it concurrently: a relation an
1382
+ * entity holds at most one of is a field of that row and never outlives it.
1383
+ */
1384
+ const medeoDslLoroShape = schema({
1385
+ "timeline-entities": schema.LoroMapRecord(schema.LoroMap({})),
1386
+ "track-entities": schema.LoroMapRecord(schema.LoroMap({
1387
+ role: schema.String(),
1388
+ hidden: schema.Boolean(optional)
1389
+ })),
1390
+ "clip-entities": schema.LoroMapRecord(schema.LoroMap({
1391
+ seqMarker: atomicValue(seqMarkerCodec),
1392
+ volume: schema.Number(optional),
1393
+ source: schema.String(),
1394
+ anchor: optionalAtomicValue(timeAnchorCodec)
1395
+ })),
1396
+ "media-entities": schema.LoroMapRecord(schema.LoroMap({
1397
+ kind: schema.String(),
1398
+ system: schema.String(),
1399
+ key: schema.String(),
1400
+ storageKey: schema.String(optional),
1401
+ durationMs: schema.Number(optional),
1402
+ digest: schema.String(optional)
1403
+ }), mergeable),
1404
+ "audio-script-entities": schema.LoroMapRecord(schema.LoroMap({
1405
+ segments: schema.LoroMovableList(schema.LoroMap({
1406
+ id: schema.String(),
1407
+ text: schema.LoroText()
1408
+ }), (segment) => segment.id),
1409
+ defaultLanguage: schema.String(optional)
1410
+ })),
1411
+ "phonetic-script-entities": schema.LoroMapRecord(schema.LoroMap({
1412
+ phoneme: atomicValue(phonemeCodec),
1413
+ system: schema.String(optional),
1414
+ key: schema.String(optional),
1415
+ storageKey: schema.String(optional),
1416
+ digest: schema.String(optional)
1417
+ })),
1418
+ "caption-entities": schema.LoroMapRecord(schema.LoroMap({
1419
+ selection: optionalAtomicValue(captionContentCodec),
1420
+ text: schema.LoroText(optional),
1421
+ style: schema.LoroMap({
1422
+ font: schema.LoroMap({
1423
+ system: schema.String(),
1424
+ key: schema.String()
1425
+ }, optional),
1426
+ fontSize: schema.Number(optional),
1427
+ fontColor: schema.String(optional),
1428
+ fontWeight: schema.Number(optional),
1429
+ entranceAnimation: schema.String(optional),
1430
+ entranceAnimationDurationMs: schema.Number(optional),
1431
+ strokeColor: schema.String(optional),
1432
+ strokeWidth: schema.Number(optional),
1433
+ positionX: schema.Number(optional),
1434
+ positionY: schema.Number(optional)
1435
+ }, {
1436
+ ...optional,
1437
+ ...mergeable
1438
+ })
1439
+ }, mergeable)),
1440
+ "voice-entities": schema.LoroMapRecord(schema.LoroMap({
1441
+ system: schema.String(),
1442
+ key: schema.String(),
1443
+ name: schema.String(optional)
1444
+ }), mergeable),
1445
+ "contain-relations": schema.LoroTree(schema.LoroMap({ entityId: schema.String() })),
1446
+ "voice-timbre-relations": relation(["recordingId", "voiceId"]),
1447
+ "derived-from-relations": schema.LoroMapRecord(schema.LoroMap({
1448
+ entityId: schema.String(),
1449
+ sourceId: schema.String(),
1450
+ sourceDigest: schema.String(optional)
1451
+ }), mergeable)
1452
+ });
1453
+ //#endregion
1454
+ //#region ../medeo-dsl/src/schema/document-format.ts
1455
+ /** Format discrimination does not register containers or alter the document. */
1456
+ function documentFormat(doc) {
1457
+ const roots = doc.getShallowValue();
1458
+ const legacy = [
1459
+ "medeo",
1460
+ "timeline",
1461
+ "tracks",
1462
+ "part_library"
1463
+ ].some((key) => Object.hasOwn(roots, key));
1464
+ const dsl = Object.keys(roots).some((key) => key.endsWith("-entities") || key.endsWith("-relations"));
1465
+ return legacy && dsl ? "mixed" : legacy ? "legacy" : dsl ? "dsl" : "unknown";
1466
+ }
1467
+ var UnsupportedDocumentFormatError = class extends Error {
1468
+ code = "unsupported_document_format";
1469
+ constructor() {
1470
+ super("Expected a new DSL document; legacy, mixed or uninitialized content is not supported");
1471
+ this.name = "UnsupportedDocumentFormatError";
1472
+ }
1473
+ };
1474
+ /** Run after initial import, before opening an editable handle. Empty new documents still have one Timeline. */
1475
+ function assertDslDocument(doc) {
1476
+ if (documentFormat(doc) !== "dsl" || doc.getMap("timeline-entities").keys().length !== 1) throw new UnsupportedDocumentFormatError();
1477
+ }
1478
+ //#endregion
1479
+ //#region ../medeo-dsl/src/schema/text-styles.ts
1480
+ /** How rich-text marks extend at their edges: a language runs on into text typed after it. */
1481
+ const textStyles = { language: { expand: "after" } };
1482
+ //#endregion
1483
+ //#region src/dsl/projection/video-draft-types.ts
1484
+ const DEFAULT_UNIT_TIME_MS = 33.333;
1485
+ //#endregion
1486
+ export { assertEntityPatch as $, getRootContainerByType as A, isValueOfContainerType as B, applyEncode as C, decodeNestedJsonValues as D, containerIdToContainerType as E, isArrayLike as F, tryUpdateToContainer as G, schemaToContainerType as H, isObject as I, getChildContainerSchema as J, valuesEqual as K, isObjectLike as L, hasTransform as M, inferContainerTypeFromValue as N, deepEqual as O, insertChildToMap as P, assertEntity as Q, isStateAndSchemaOfType as R, applyDecode as S, cidsEqual as T, stripUndefined as U, safeStringify as V, tryInferContainerType as W, getMapFieldSchema as X, getChildSchema as Y, assertCaptionContent as Z, isLoroMovableListSchema as _, tupleHash as _t, documentFormat as a, atomicFields as at, schemaContainsIgnoreField as b, isInvalidAtomic as c, mergeFields as ct, schema as d, validLanguage as dt, assertId as et, getDefaultValue as f, assertRelationIdentity as ft, isLoroMapSchema as g, resourceId as gt, isLoroListSchema as h, relationId as ht, assertDslDocument as i, assertTimeAnchor as it, hardenCidDescriptors as j, defineCidProperty as k, phonemeCodec as l, patchRow as lt, isListLikeSchema as m, defaultIdFactory as mt, textStyles as n, assertPhoneticScript as nt, medeoDslLoroShape as o, entityTables as ot, isContainerSchema as p, assertResourceIdentity as pt, CID_KEY as q, UnsupportedDocumentFormatError as r, assertRelation as rt, captionContentCodec as s, isRecord as st, DEFAULT_UNIT_TIME_MS as t, assertPhoneme as tt, timeAnchorCodec as u, relationTables as ut, isLoroTreeSchema as v, applySchemaToInferOptions as w, validateSchema as x, isRootSchemaType as y, isTreeID as z };