diff --git a/api-reference/classes/Change.html b/api-reference/classes/Change.html index 4b961ffd2..07defa6ac 100644 --- a/api-reference/classes/Change.html +++ b/api-reference/classes/Change.html @@ -1,5 +1,5 @@ Change | yorkie-js-sdk

Class Change<P>

Change represents a unit of modification in the document.

-

Type Parameters

Constructors

Type Parameters

Constructors

Properties

Constructors

  • Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

  • execute executes the operations of this change to the given root.

    -

    Parameters

    • root: CRDTRoot
    • presences: Map<string, P>
    • source: OpSource

    Returns {
        opInfos: OperationInfo[];
        reverseOps: HistoryOperation<P>[];
    }

  • getMessage returns the message of this change.

    -

    Returns undefined | string

  • getPresenceChange returns the presence change of this change.

    -

    Returns undefined | PresenceChange<P>

  • hasOperations returns whether this change has operations or not.

    -

    Returns boolean

  • hasPresenceChange returns whether this change has presence change or not.

    -

    Returns boolean

  • toTestString returns a string containing the meta data of this change.

    -

    Returns string

  • create creates a new instance of Change.

    -

    Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

\ No newline at end of file +

Constructors

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

\ No newline at end of file diff --git a/api-reference/classes/Client.html b/api-reference/classes/Client.html index 2dfcb1cce..7a5f97cf3 100644 --- a/api-reference/classes/Client.html +++ b/api-reference/classes/Client.html @@ -1,7 +1,7 @@ Client | yorkie-js-sdk

Client is a normal client that can communicate with the server. It has documents and sends changes of the documents in local to the server to synchronize with other replicas in remote.

-

Constructors

Constructors

Properties

Constructors

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      +

Returns Client

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      • Readonly I: typeof ActivateClientRequest
      • Readonly O: typeof ActivateClientResponse
      • Readonly kind: Unary
      • Readonly name: "ActivateClient"
    • Readonly attachDocument: {
          I: typeof AttachDocumentRequest;
          O: typeof AttachDocumentResponse;
          kind: Unary;
          name: "AttachDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.AttachDocument

      • Readonly I: typeof AttachDocumentRequest
      • Readonly O: typeof AttachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "AttachDocument"
    • Readonly broadcast: {
          I: typeof BroadcastRequest;
          O: typeof BroadcastResponse;
          kind: Unary;
          name: "Broadcast";
      }

      Generated

      from rpc yorkie.v1.YorkieService.Broadcast

      • Readonly I: typeof BroadcastRequest
      • Readonly O: typeof BroadcastResponse
      • Readonly kind: Unary
      • Readonly name: "Broadcast"
    • Readonly deactivateClient: {
          I: typeof DeactivateClientRequest;
          O: typeof DeactivateClientResponse;
          kind: Unary;
          name: "DeactivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.DeactivateClient

      @@ -46,35 +46,35 @@
      • Readonly I: typeof DetachDocumentRequest
      • Readonly O: typeof DetachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "DetachDocument"
    • Readonly pushPullChanges: {
          I: typeof PushPullChangesRequest;
          O: typeof PushPullChangesResponse;
          kind: Unary;
          name: "PushPullChanges";
      }

      Generated

      from rpc yorkie.v1.YorkieService.PushPullChanges

      • Readonly I: typeof PushPullChangesRequest
      • Readonly O: typeof PushPullChangesResponse
      • Readonly kind: Unary
      • Readonly name: "PushPullChanges"
    • Readonly removeDocument: {
          I: typeof RemoveDocumentRequest;
          O: typeof RemoveDocumentResponse;
          kind: Unary;
          name: "RemoveDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.RemoveDocument

      • Readonly I: typeof RemoveDocumentRequest
      • Readonly O: typeof RemoveDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "RemoveDocument"
    • Readonly watchDocument: {
          I: typeof WatchDocumentRequest;
          O: typeof WatchDocumentResponse;
          kind: ServerStreaming;
          name: "WatchDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.WatchDocument

      -
      • Readonly I: typeof WatchDocumentRequest
      • Readonly O: typeof WatchDocumentResponse
      • Readonly kind: ServerStreaming
      • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
status: ClientStatus
syncLoopDuration: number
taskQueue: (() => Promise<any>)[]

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

Methods

  • activate activates this client. That is, it registers itself to the server +

    • Readonly I: typeof WatchDocumentRequest
    • Readonly O: typeof WatchDocumentResponse
    • Readonly kind: ServerStreaming
    • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
  • status: ClientStatus
    syncLoopDuration: number
    taskQueue: (() => Promise<any>)[]

    Type declaration

      • (): Promise<any>
      • Returns Promise<any>

    Methods

    • activate activates this client. That is, it registers itself to the server and receives a unique ID from the server. The given ID is used to distinguish different clients.

      -

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that +

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that this client will synchronize the given document.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional syncMode?: SyncMode

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      -

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      -

      Returns Promise<void>

    • broadcast broadcasts the given payload to the given topic.

      +

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      +

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the server that this client will no longer synchronize the given document.

      To collect garbage things like CRDT tombstones left on the document, all the changes should be applied to other replicas before GC time. For this, if the document is no longer used by this client, it should be detached.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      -

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      -

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      +

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      +

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be retried after handling, it returns true.

      -

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      -

      Returns boolean

    • processNext processes the next task in the task queue. This method is +

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      +

      Returns boolean

    • processNext processes the next task in the task queue. This method is part of enqueueTask.

      -

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to +

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to the server and pulls remote changes from the server.

      -

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop +

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop listens to the events of the given document from the server.

      -

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and +

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and receives changes of the remote replica from the server then apply them to local documents.

      -

      Type Parameters

      Parameters

      Returns Promise<Document<T, P>[]>

    \ No newline at end of file +

    Type Parameters

    Parameters

    Returns Promise<Document<T, P>[]>

    \ No newline at end of file diff --git a/api-reference/classes/Counter.html b/api-reference/classes/Counter.html index f08290f33..f6c4941aa 100644 --- a/api-reference/classes/Counter.html +++ b/api-reference/classes/Counter.html @@ -1,5 +1,5 @@ Counter | yorkie-js-sdk

    Counter is a custom data type that is used to counter.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    • Internal

      getValue returns the value of this counter;

      -

      Returns number | Long

    • getValueType returns the value type of this counter.

      -

      Returns CounterType

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • counter: CRDTCounter

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    \ No newline at end of file diff --git a/api-reference/classes/Document.html b/api-reference/classes/Document.html index a830e1db0..4d8a6a8de 100644 --- a/api-reference/classes/Document.html +++ b/api-reference/classes/Document.html @@ -1,6 +1,6 @@ Document | yorkie-js-sdk

    Class Document<T, P>

    Document is a CRDT-based data type. We can represent the model of the application and edit it even while offline.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    +

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    Type declaration

    • canRedo: (() => boolean)
        • (): boolean
        • canRedo returns whether there are any operations to redo.

          Returns boolean

    • canUndo: (() => boolean)
        • (): boolean
        • canUndo returns whether there are any operations to undo.

          Returns boolean

    • redo: (() => void)
        • (): void
        • redo redoes the last operation executed by the current client. It does not impact operations made by other clients.

          Returns void

    • undo: (() => void)
        • (): void
        • undo undoes the last operation executed by the current client. It does not impact operations made by other clients.

          -

          Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    -
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is +

    Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    +
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is used to prevent the updater from calling undo/redo.

    -
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    -
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    -
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      -

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      +
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    +
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    +
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      +

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      1. Remove local changes applied to server.
      2. Update the checkpoint.
      3. Do Garbage collection.

      Parameters

      • pack: ChangePack<P>

        change pack

        -

      Returns void

    • applySnapshot applies the given snapshot into this document.

      -

      Parameters

      • serverSeq: Long
      • Optional snapshot: Uint8Array

      Returns void

    • applyWatchStream applies the given watch stream response into this document.

      -

      Parameters

      • resp: WatchDocumentResponse

      Returns void

    • broadcast the payload to the given topic.

      -

      Parameters

      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns void

    • canRedo returns whether there are any operations to redo.

      -

      Returns boolean

    • canUndo returns whether there are any operations to undo.

      -

      Returns boolean

    • Internal

      createChangePack create change pack of the local changes to send to the +

    Returns void

    \ No newline at end of file +

    Returns void

    \ No newline at end of file diff --git a/api-reference/classes/Primitive.html b/api-reference/classes/Primitive.html index 53f96221d..c58691e54 100644 --- a/api-reference/classes/Primitive.html +++ b/api-reference/classes/Primitive.html @@ -1,6 +1,6 @@ Primitive | yorkie-js-sdk

    Class Primitive

    Primitive represents primitive data type including logical clock. It has a type and a value.

    -

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Properties

    Methods

    deepcopy @@ -25,27 +25,27 @@ isSupport of valueFromBytes -

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned +

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned in the document by undo/redo or move operation.

      -

      Returns TimeTicket

    • isRemoved check if this element was removed.

      -

      Returns boolean

    • setMovedAt sets the move time of this element.

      -

      Parameters

      Returns boolean

    • setRemovedAt sets the remove time of this element.

      -

      Parameters

      Returns void

    • toSortedJSON returns the sorted JSON encoding of the value.

      -

      Returns string

    • getPrimitiveType returns the primitive type of the value.

      -

      Parameters

      • value: unknown

      Returns undefined | PrimitiveType

    • isInteger checks if the given number is integer.

      -

      Parameters

      • num: number

      Returns boolean

    • isSupport check if the given value is supported type.

      -

      Parameters

      • value: unknown

      Returns boolean

    \ No newline at end of file +

    Returns TimeTicket

    \ No newline at end of file diff --git a/api-reference/classes/Text.html b/api-reference/classes/Text.html index db715cd80..44680e8e3 100644 --- a/api-reference/classes/Text.html +++ b/api-reference/classes/Text.html @@ -1,5 +1,5 @@ Text | yorkie-js-sdk

    Class Text<A>

    Text is an extended data type for the contents of a text editor.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Accessors

    length @@ -19,23 +19,23 @@ toString toTestString values -

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes for testing purpose.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      -

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      -

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      -

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      -

      Returns string

    • toTestString returns a String containing the meta data of the node +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      +

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      +

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      +

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      +

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      +

      Returns string

    • toTestString returns a String containing the meta data of the node for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/TimeTicket.html b/api-reference/classes/TimeTicket.html index fe080f93e..bb49e2324 100644 --- a/api-reference/classes/TimeTicket.html +++ b/api-reference/classes/TimeTicket.html @@ -1,6 +1,6 @@ TimeTicket | yorkie-js-sdk

    Class TimeTicket

    TimeTicket is a timestamp of the logical clock. Ticket is immutable. It is created by ChangeID.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: Long

    Methods

    • compare returns an integer comparing two Ticket. +

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: Long

    Methods

    • compare returns an integer comparing two Ticket. The result will be 0 if id==other, -1 if id < other, and +1 if id > other. If the receiver or argument is nil, it would panic at runtime.

      -

      Parameters

      Returns number

    • toTestString returns a string containing the meta data of the ticket for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/Tree.html b/api-reference/classes/Tree.html index 1c04dfe99..3dd294b4a 100644 --- a/api-reference/classes/Tree.html +++ b/api-reference/classes/Tree.html @@ -1,6 +1,6 @@ Tree | yorkie-js-sdk

    Tree is a CRDT-based tree structure that is used to represent the document tree of text-based editor such as ProseMirror.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root which set by the user.

      -

      Parameters

      Returns CRDTTreeNode

    • edit edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • editBulk edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editBulkByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • Parameters

      • fromPos: CRDTTreePos
      • toPos: CRDTTreePos
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • getIndexTree returns the index tree of this tree.

      -

      Returns IndexTree<CRDTTreeNode>

    • indexToPath returns the path of the given index.

      -

      Parameters

      • index: number

      Returns number[]

    • Internal

      initialize initialize this tree with context and internal tree.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • tree: CRDTTree

      Returns void

    • pathToIndex returns the index of given path.

      -

      Parameters

      • path: number[]

      Returns number

    • posRangeToPathRange converts the position range into the path range.

      -

      Parameters

      Returns [number[], number[]]

    • removeStyle removes the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributesToRemove: string[]

      Returns void

    • style sets the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    • styleByPath sets the attributes to the elements of the given path.

      -

      Parameters

      • path: number[]
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    \ No newline at end of file +

    Parameters

    Returns CRDTTreeNode

    \ No newline at end of file diff --git a/api-reference/enums/ClientCondition.html b/api-reference/enums/ClientCondition.html index aacae114d..55a5c96da 100644 --- a/api-reference/enums/ClientCondition.html +++ b/api-reference/enums/ClientCondition.html @@ -1,6 +1,6 @@ ClientCondition | yorkie-js-sdk

    Enumeration ClientCondition

    ClientCondition represents the condition of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncLoop: "SyncLoop"

    SyncLoop is a key of the sync loop condition.

    -
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    -
    \ No newline at end of file +
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    +
    \ No newline at end of file diff --git a/api-reference/enums/ClientStatus.html b/api-reference/enums/ClientStatus.html index b70843f00..5b8ac6361 100644 --- a/api-reference/enums/ClientStatus.html +++ b/api-reference/enums/ClientStatus.html @@ -1,9 +1,9 @@ ClientStatus | yorkie-js-sdk

    Enumeration ClientStatus

    ClientStatus represents the status of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Activated: "activated"

    Activated means that the client is activated. If the client is activated, all Documents of the client are also ready to be used.

    -
    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial +

    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial status of the client. If the client is deactivated, all Documents of the client are also not used.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocEventType.html b/api-reference/enums/DocEventType.html index 5e9ead6b9..fd702d182 100644 --- a/api-reference/enums/DocEventType.html +++ b/api-reference/enums/DocEventType.html @@ -1,5 +1,5 @@ DocEventType | yorkie-js-sdk

    Enumeration DocEventType

    DocEventType represents the type of the event that occurs in Document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Broadcast: "broadcast"

    Broadcast means that the broadcast event is received from the remote client.

    -
    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    -
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    -
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    -
    LocalChange: "local-change"

    local document change event type

    -
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    -
    RemoteChange: "remote-change"

    remote document change event type

    -
    Snapshot: "snapshot"

    snapshot event type

    -
    StatusChanged: "status-changed"

    status changed event type

    -
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    -
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    -
    Watched: "watched"

    Watched means that the client has established a connection with the server, +

    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    +
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    +
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    +
    LocalChange: "local-change"

    local document change event type

    +
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    +
    RemoteChange: "remote-change"

    remote document change event type

    +
    Snapshot: "snapshot"

    snapshot event type

    +
    StatusChanged: "status-changed"

    status changed event type

    +
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    +
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    +
    Watched: "watched"

    Watched means that the client has established a connection with the server, enabling real-time synchronization.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentStatus.html b/api-reference/enums/DocumentStatus.html index 519167a78..64472e3c3 100644 --- a/api-reference/enums/DocumentStatus.html +++ b/api-reference/enums/DocumentStatus.html @@ -1,11 +1,11 @@ DocumentStatus | yorkie-js-sdk

    Enumeration DocumentStatus

    DocumentStatus represents the status of the document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Attached: "attached"

    Attached means that this document is attached to the client. The actor of the ticket is created with being assigned by the client.

    -
    Detached: "detached"

    Detached means that the document is not attached to the client. +

    Detached: "detached"

    Detached means that the document is not attached to the client. The actor of the ticket is created without being assigned.

    -
    Removed: "removed"

    Removed means that this document is removed. If the document is removed, +

    Removed: "removed"

    Removed means that this document is removed. If the document is removed, it cannot be edited.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentSyncStatus.html b/api-reference/enums/DocumentSyncStatus.html index 4d505b199..b2a309708 100644 --- a/api-reference/enums/DocumentSyncStatus.html +++ b/api-reference/enums/DocumentSyncStatus.html @@ -1,6 +1,6 @@ DocumentSyncStatus | yorkie-js-sdk

    Enumeration DocumentSyncStatus

    DocumentSyncStatus represents the result of synchronizing the document with the server.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncFailed: "sync-failed"

    SyncFiled means that document synchronization has failed.

    -
    Synced: "synced"

    Synced means that document synced successfully.

    -
    \ No newline at end of file +
    Synced: "synced"

    Synced means that document synced successfully.

    +
    \ No newline at end of file diff --git a/api-reference/enums/LogLevel.html b/api-reference/enums/LogLevel.html index 1be31445c..e59cb5868 100644 --- a/api-reference/enums/LogLevel.html +++ b/api-reference/enums/LogLevel.html @@ -1,7 +1,7 @@ -LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Debug +LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file +

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file diff --git a/api-reference/enums/OpSource.html b/api-reference/enums/OpSource.html index 049bdd184..5f068569c 100644 --- a/api-reference/enums/OpSource.html +++ b/api-reference/enums/OpSource.html @@ -1,7 +1,7 @@ OpSource | yorkie-js-sdk

    Enumeration OpSource

    OpSource represents the source of the operation. It is used to handle corner cases in the operations created by undo/redo allow the removed elements when executing them.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file +

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file diff --git a/api-reference/enums/StreamConnectionStatus.html b/api-reference/enums/StreamConnectionStatus.html index 667b3fa9e..38f6cd0e8 100644 --- a/api-reference/enums/StreamConnectionStatus.html +++ b/api-reference/enums/StreamConnectionStatus.html @@ -1,6 +1,6 @@ StreamConnectionStatus | yorkie-js-sdk

    Enumeration StreamConnectionStatus

    StreamConnectionStatus represents whether the stream connection is connected or not.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Connected: "connected"

    Connected means that the stream connection is connected.

    -
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    -
    \ No newline at end of file +
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    +
    \ No newline at end of file diff --git a/api-reference/enums/SyncMode.html b/api-reference/enums/SyncMode.html index 344cf1160..6e707b447 100644 --- a/api-reference/enums/SyncMode.html +++ b/api-reference/enums/SyncMode.html @@ -1,11 +1,11 @@ SyncMode | yorkie-js-sdk

    Enumeration SyncMode

    SyncMode defines synchronization modes for the PushPullChanges API.

    -

    Enumeration Members

    Enumeration Members

    Manual: "manual"

    Manual mode indicates that changes are not automatically pushed or pulled.

    -
    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    -
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    -
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, +

    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    +
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    +
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, but the watch stream is kept active.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/TreeChangeType.html b/api-reference/enums/TreeChangeType.html index 75a144018..11c6dbf3f 100644 --- a/api-reference/enums/TreeChangeType.html +++ b/api-reference/enums/TreeChangeType.html @@ -1,5 +1,5 @@ TreeChangeType | yorkie-js-sdk

    Enumeration TreeChangeType

    TreeChangeType represents the type of change in the tree.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file +

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file diff --git a/api-reference/interfaces/ChangeInfo.html b/api-reference/interfaces/ChangeInfo.html index 12a4818d9..342eccaa9 100644 --- a/api-reference/interfaces/ChangeInfo.html +++ b/api-reference/interfaces/ChangeInfo.html @@ -1,8 +1,8 @@ ChangeInfo | yorkie-js-sdk

    Interface ChangeInfo<T>

    ChangeInfo represents the modifications made during a document update and the message passed.

    -
    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file +

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file diff --git a/api-reference/interfaces/ClientOptions.html b/api-reference/interfaces/ClientOptions.html index 86e88b202..e98bacc87 100644 --- a/api-reference/interfaces/ClientOptions.html +++ b/api-reference/interfaces/ClientOptions.html @@ -1,5 +1,5 @@ ClientOptions | yorkie-js-sdk

    Interface ClientOptions

    ClientOptions are user-settable options used when defining clients.

    -
    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    apiKey?: string

    apiKey is the API key of the project. It is used to identify the project. If not set, API key of the default project is used.

    -
    key?: string

    key is the client key. It is used to identify the client. +

    key?: string

    key is the client key. It is used to identify the client. If not set, a random key is generated.

    -
    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream +

    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream is disconnected, the client waits for the delay to reconnect the stream. The default value is 1000(ms).

    -
    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop +

    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop fails, the client waits for the delay to retry the sync loop. The default value is 1000(ms).

    -
    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, +

    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, the client waits for the duration to next sync. The default value is 50(ms).

    -
    token?: string

    token is the authentication token of this client. It is used to identify +

    token?: string

    token is the authentication token of this client. It is used to identify the user of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/ConnectionChangedEvent.html b/api-reference/interfaces/ConnectionChangedEvent.html index a85548a63..67136f9a2 100644 --- a/api-reference/interfaces/ConnectionChangedEvent.html +++ b/api-reference/interfaces/ConnectionChangedEvent.html @@ -1,5 +1,5 @@ ConnectionChangedEvent | yorkie-js-sdk

    Interface ConnectionChangedEvent

    ConnectionChangedEvent is an event that occurs when the stream connection state changes.

    -
    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    Properties

    enum DocEventType.ConnectionChanged

    -
    \ No newline at end of file +
    value: StreamConnectionStatus
    \ No newline at end of file diff --git a/api-reference/interfaces/InitializedEvent.html b/api-reference/interfaces/InitializedEvent.html index 0b0d8b333..defd38e29 100644 --- a/api-reference/interfaces/InitializedEvent.html +++ b/api-reference/interfaces/InitializedEvent.html @@ -1,4 +1,4 @@ -InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    source +InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/LocalChangeEvent.html b/api-reference/interfaces/LocalChangeEvent.html index b06aba715..0686acfac 100644 --- a/api-reference/interfaces/LocalChangeEvent.html +++ b/api-reference/interfaces/LocalChangeEvent.html @@ -1,8 +1,8 @@ LocalChangeEvent | yorkie-js-sdk

    Interface LocalChangeEvent<T, P>

    LocalChangeEvent is an event that occurs when the document is changed by local changes.

    -
    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observable.html b/api-reference/interfaces/Observable.html index 9e6b210b7..cce0c6349 100644 --- a/api-reference/interfaces/Observable.html +++ b/api-reference/interfaces/Observable.html @@ -1,3 +1,3 @@ -Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    getProxy? +Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file +

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observer.html b/api-reference/interfaces/Observer.html index c7dab42ff..5d372548a 100644 --- a/api-reference/interfaces/Observer.html +++ b/api-reference/interfaces/Observer.html @@ -1,4 +1,4 @@ -Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    complete? +Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file +

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/PresenceChangedEvent.html b/api-reference/interfaces/PresenceChangedEvent.html index 5ca04e79e..045e4d829 100644 --- a/api-reference/interfaces/PresenceChangedEvent.html +++ b/api-reference/interfaces/PresenceChangedEvent.html @@ -1,4 +1,4 @@ -PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    source +PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/RemoteChangeEvent.html b/api-reference/interfaces/RemoteChangeEvent.html index 36324242d..b0128144c 100644 --- a/api-reference/interfaces/RemoteChangeEvent.html +++ b/api-reference/interfaces/RemoteChangeEvent.html @@ -1,8 +1,8 @@ RemoteChangeEvent | yorkie-js-sdk

    Interface RemoteChangeEvent<T, P>

    RemoteChangeEvent is an event that occurs when the document is changed by remote changes.

    -
    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/SnapshotEvent.html b/api-reference/interfaces/SnapshotEvent.html index 55353dbaf..ef86e1276 100644 --- a/api-reference/interfaces/SnapshotEvent.html +++ b/api-reference/interfaces/SnapshotEvent.html @@ -1,7 +1,7 @@ SnapshotEvent | yorkie-js-sdk

    Interface SnapshotEvent

    SnapshotEvent is an event that occurs when a snapshot is received from the server.

    -
    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot?: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot?: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    -
    value: {
        serverSeq: string;
        snapshot?: string;
    }

    Type declaration

    • serverSeq: string
    • Optional snapshot?: string
    \ No newline at end of file +

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    +
    value: {
        serverSeq: string;
        snapshot?: string;
    }

    Type declaration

    • serverSeq: string
    • Optional snapshot?: string
    \ No newline at end of file diff --git a/api-reference/interfaces/SyncStatusChangedEvent.html b/api-reference/interfaces/SyncStatusChangedEvent.html index 5bc32a4d0..ae09d8d74 100644 --- a/api-reference/interfaces/SyncStatusChangedEvent.html +++ b/api-reference/interfaces/SyncStatusChangedEvent.html @@ -1,5 +1,5 @@ SyncStatusChangedEvent | yorkie-js-sdk

    Interface SyncStatusChangedEvent

    SyncStatusChangedEvent is an event that occurs when document is synced with the server.

    -
    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    Properties

    enum DocEventType.SyncStatusChanged

    -
    \ No newline at end of file +
    value: DocumentSyncStatus
    \ No newline at end of file diff --git a/api-reference/interfaces/UnwatchedEvent.html b/api-reference/interfaces/UnwatchedEvent.html index a28c1d8da..e5f784130 100644 --- a/api-reference/interfaces/UnwatchedEvent.html +++ b/api-reference/interfaces/UnwatchedEvent.html @@ -1,4 +1,4 @@ -UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    source +UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/WatchedEvent.html b/api-reference/interfaces/WatchedEvent.html index ef110891b..380423d89 100644 --- a/api-reference/interfaces/WatchedEvent.html +++ b/api-reference/interfaces/WatchedEvent.html @@ -1,4 +1,4 @@ -WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    source +WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/modules/Devtools.html b/api-reference/modules/Devtools.html index a4e5e96c4..74b1d178a 100644 --- a/api-reference/modules/Devtools.html +++ b/api-reference/modules/Devtools.html @@ -1,4 +1,4 @@ -Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client +Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client ContainerValue JSONElement TreeNodeInfo diff --git a/api-reference/types/ActorID.html b/api-reference/types/ActorID.html index 92479d573..8583cb033 100644 --- a/api-reference/types/ActorID.html +++ b/api-reference/types/ActorID.html @@ -1,3 +1,3 @@ ActorID | yorkie-js-sdk

    Type alias ActorID

    ActorID: string

    ActorID is used to identify who is making changes to the document. It is a hexadecimal string and should be generated by a unique value.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/AddOpInfo.html b/api-reference/types/AddOpInfo.html index c6e7a17c5..f8a2abf23 100644 --- a/api-reference/types/AddOpInfo.html +++ b/api-reference/types/AddOpInfo.html @@ -1,2 +1,2 @@ AddOpInfo | yorkie-js-sdk

    Type alias AddOpInfo

    AddOpInfo: {
        index: number;
        path: string;
        type: "add";
    }

    AddOpInfo represents the information of the add operation.

    -

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file +

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file diff --git a/api-reference/types/ArrayOperationInfo.html b/api-reference/types/ArrayOperationInfo.html index 383dce85d..3590d4efc 100644 --- a/api-reference/types/ArrayOperationInfo.html +++ b/api-reference/types/ArrayOperationInfo.html @@ -1,2 +1,2 @@ ArrayOperationInfo | yorkie-js-sdk

    Type alias ArrayOperationInfo

    ArrayOperationInfo: AddOpInfo | RemoveOpInfo | MoveOpInfo

    ArrayOperationInfo represents the OperationInfo for the JSONArray.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CRDTTreeNodeIDStruct.html b/api-reference/types/CRDTTreeNodeIDStruct.html index c52abed42..d1f2a9f6f 100644 --- a/api-reference/types/CRDTTreeNodeIDStruct.html +++ b/api-reference/types/CRDTTreeNodeIDStruct.html @@ -1,3 +1,3 @@ CRDTTreeNodeIDStruct | yorkie-js-sdk

    Type alias CRDTTreeNodeIDStruct

    CRDTTreeNodeIDStruct: {
        createdAt: TimeTicketStruct;
        offset: number;
    }

    CRDTTreeNodeIDStruct represents the structure of CRDTTreeNodeID. It is used to serialize and deserialize the CRDTTreeNodeID.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/CompleteFn.html b/api-reference/types/CompleteFn.html index 69ec3a653..d5a6be882 100644 --- a/api-reference/types/CompleteFn.html +++ b/api-reference/types/CompleteFn.html @@ -1 +1 @@ -CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/CounterOperationInfo.html b/api-reference/types/CounterOperationInfo.html index b7fccad2a..2d2241a7b 100644 --- a/api-reference/types/CounterOperationInfo.html +++ b/api-reference/types/CounterOperationInfo.html @@ -1,2 +1,2 @@ CounterOperationInfo | yorkie-js-sdk

    Type alias CounterOperationInfo

    CounterOperationInfo: IncreaseOpInfo

    CounterOperationInfo represents the OperationInfo for the yorkie.Counter.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CounterValue.html b/api-reference/types/CounterValue.html index 5a3006c81..1156f0026 100644 --- a/api-reference/types/CounterValue.html +++ b/api-reference/types/CounterValue.html @@ -1 +1 @@ -CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file +CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file diff --git a/api-reference/types/Devtools.Client.html b/api-reference/types/Devtools.Client.html index 557ff3a30..5591cbbc9 100644 --- a/api-reference/types/Devtools.Client.html +++ b/api-reference/types/Devtools.Client.html @@ -1,2 +1,2 @@ Client | yorkie-js-sdk
    Client: {
        clientID: string;
        presence: Json;
    }

    Client represents a client value in devtools.

    -

    Type declaration

    • clientID: string
    • presence: Json
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.ContainerValue.html b/api-reference/types/Devtools.ContainerValue.html index 77344d7bc..fbdd286d4 100644 --- a/api-reference/types/Devtools.ContainerValue.html +++ b/api-reference/types/Devtools.ContainerValue.html @@ -1,3 +1,3 @@ ContainerValue | yorkie-js-sdk

    Type alias ContainerValue

    ContainerValue: {
        [key: string]: Devtools.JSONElement;
    }

    ContainerValue represents the result of Array.toJSForTest() and Object.toJSForTest().

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.JSONElement.html b/api-reference/types/Devtools.JSONElement.html index 45ef86d78..0cc5215bd 100644 --- a/api-reference/types/Devtools.JSONElement.html +++ b/api-reference/types/Devtools.JSONElement.html @@ -1,2 +1,2 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement

    JSONElement: {
        createdAt: string;
        key?: string;
        type: JSONElementType;
        value: JSONElementValue;
    }

    JSONElement represents the result of Element.toJSForTest().

    -

    Type declaration

    • createdAt: string
    • Optional key?: string
    • type: JSONElementType
    • value: JSONElementValue
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.TreeNodeInfo.html b/api-reference/types/Devtools.TreeNodeInfo.html index ccc6cb4b1..a0d67b56e 100644 --- a/api-reference/types/Devtools.TreeNodeInfo.html +++ b/api-reference/types/Devtools.TreeNodeInfo.html @@ -1,2 +1,2 @@ TreeNodeInfo | yorkie-js-sdk

    Type alias TreeNodeInfo

    TreeNodeInfo: {
        attributes?: object;
        children: TreeNodeInfo[];
        depth: number;
        id: string;
        index?: number;
        insNext?: string;
        insPrev?: string;
        isRemoved: boolean;
        parent?: string;
        path?: number[];
        pos?: CRDTTreePosStruct;
        removedAt?: string;
        size: number;
        type: string;
        value?: string;
    }

    TreeNodeInfo represents the crdt tree node information in devtools.

    -

    Type declaration

    • Optional attributes?: object
    • children: TreeNodeInfo[]
    • depth: number
    • id: string
    • Optional index?: number
    • Optional insNext?: string
    • Optional insPrev?: string
    • isRemoved: boolean
    • Optional parent?: string
    • Optional path?: number[]
    • Optional pos?: CRDTTreePosStruct
    • Optional removedAt?: string
    • size: number
    • type: string
    • Optional value?: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/DocEvent.html b/api-reference/types/DocEvent.html index 96b94d21b..119be596b 100644 --- a/api-reference/types/DocEvent.html +++ b/api-reference/types/DocEvent.html @@ -1,3 +1,3 @@ DocEvent | yorkie-js-sdk

    Type alias DocEvent<P, T>

    DocEvent<P, T>: StatusChangedEvent | ConnectionChangedEvent | SyncStatusChangedEvent | SnapshotEvent | LocalChangeEvent<T, P> | RemoteChangeEvent<T, P> | InitializedEvent<P> | WatchedEvent<P> | UnwatchedEvent<P> | PresenceChangedEvent<P> | BroadcastEvent | LocalBroadcastEvent

    DocEvent is an event that occurs in Document. It can be delivered using Document.subscribe().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/EditOpInfo.html b/api-reference/types/EditOpInfo.html index 779df4d2a..ceed8dd0b 100644 --- a/api-reference/types/EditOpInfo.html +++ b/api-reference/types/EditOpInfo.html @@ -1,2 +1,2 @@ EditOpInfo | yorkie-js-sdk

    Type alias EditOpInfo

    EditOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "edit";
        value: {
            attributes: Indexable;
            content: string;
        };
    }

    EditOpInfo represents the information of the edit operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "edit"
    • value: {
          attributes: Indexable;
          content: string;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ElementNode.html b/api-reference/types/ElementNode.html index 8f12b8368..596512f19 100644 --- a/api-reference/types/ElementNode.html +++ b/api-reference/types/ElementNode.html @@ -1,2 +1,2 @@ ElementNode | yorkie-js-sdk

    Type alias ElementNode<A>

    ElementNode<A>: {
        attributes?: A;
        children: TreeNode[];
        type: TreeNodeType;
    }

    ElementNode represents an element node. It has an attributes and children.

    -

    Type Parameters

    Type declaration

    • Optional attributes?: A
    • children: TreeNode[]
    • type: TreeNodeType
    \ No newline at end of file +

    Type Parameters

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ErrorFn.html b/api-reference/types/ErrorFn.html index 9156caaba..23668a13d 100644 --- a/api-reference/types/ErrorFn.html +++ b/api-reference/types/ErrorFn.html @@ -1 +1 @@ -ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file +ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/FullPanelToSDKMessage.html b/api-reference/types/FullPanelToSDKMessage.html index 753c90d4e..0d33c2adc 100644 --- a/api-reference/types/FullPanelToSDKMessage.html +++ b/api-reference/types/FullPanelToSDKMessage.html @@ -1 +1 @@ -FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file +FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file diff --git a/api-reference/types/FullSDKToPanelMessage.html b/api-reference/types/FullSDKToPanelMessage.html index caac403f2..c75cd1a5d 100644 --- a/api-reference/types/FullSDKToPanelMessage.html +++ b/api-reference/types/FullSDKToPanelMessage.html @@ -1 +1 @@ -FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file +FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file diff --git a/api-reference/types/IncreaseOpInfo.html b/api-reference/types/IncreaseOpInfo.html index 3c29de2dc..7c052e30e 100644 --- a/api-reference/types/IncreaseOpInfo.html +++ b/api-reference/types/IncreaseOpInfo.html @@ -1,2 +1,2 @@ IncreaseOpInfo | yorkie-js-sdk

    Type alias IncreaseOpInfo

    IncreaseOpInfo: {
        path: string;
        type: "increase";
        value: number;
    }

    IncreaseOpInfo represents the information of the increase operation.

    -

    Type declaration

    • path: string
    • type: "increase"
    • value: number
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Indexable.html b/api-reference/types/Indexable.html index 599141499..91371254f 100644 --- a/api-reference/types/Indexable.html +++ b/api-reference/types/Indexable.html @@ -1,3 +1,3 @@ Indexable | yorkie-js-sdk

    Type alias Indexable

    Indexable: Record<string, Json>

    Indexable represents the type of the indexable object. It is used to represent the presence information of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/JSONArray.html b/api-reference/types/JSONArray.html index e9fe6fc93..81f439b50 100644 --- a/api-reference/types/JSONArray.html +++ b/api-reference/types/JSONArray.html @@ -1,17 +1,17 @@ JSONArray | yorkie-js-sdk

    Type alias JSONArray<T>

    JSONArray<T>: {
        deleteByID?(createdAt): WrappedElement<T>;
        getElementByID?(createdAt): WrappedElement<T>;
        getElementByIndex?(index): WrappedElement<T>;
        getID?(): TimeTicket;
        getLast?(): WrappedElement<T>;
        insertAfter?(prevID, value): WrappedElement<T>;
        insertBefore?(nextID, value): WrappedElement<T>;
        moveAfter?(prevID, id): void;
        moveBefore?(nextID, id): void;
        moveFront?(id): void;
        moveLast?(id): void;
        toJSForTest?(): Devtools.JSONElement;
        toTestString?(): string;
    } & T[]

    JSONArray represents JSON array, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/types/JSONElement.html b/api-reference/types/JSONElement.html index 4c3a0ed28..e48f7bc81 100644 --- a/api-reference/types/JSONElement.html +++ b/api-reference/types/JSONElement.html @@ -1,3 +1,3 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement<T, A>

    JSONElement<T, A>: PrimitiveValue | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    JSONElement is a wrapper for CRDTElement that provides users with an easy-to-use interface for manipulating Documents.

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/JSONObject.html b/api-reference/types/JSONObject.html index 62882e6df..0103b1db9 100644 --- a/api-reference/types/JSONObject.html +++ b/api-reference/types/JSONObject.html @@ -1,7 +1,7 @@ JSONObject | yorkie-js-sdk

    Type alias JSONObject<T>

    JSONObject<T>: {
        getID?(): TimeTicket;
        toJS?(): T;
        toJSForTest?(): Devtools.JSONElement;
        toJSON?(): string;
    } & T

    JSONObject represents a JSON object, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns TimeTicket

  • toJS?:function
  • toJSForTest?:function
  • toJSON?:function
  • \ No newline at end of file diff --git a/api-reference/types/MoveOpInfo.html b/api-reference/types/MoveOpInfo.html index 44b61c3f8..3c1a28d5e 100644 --- a/api-reference/types/MoveOpInfo.html +++ b/api-reference/types/MoveOpInfo.html @@ -1,2 +1,2 @@ MoveOpInfo | yorkie-js-sdk

    Type alias MoveOpInfo

    MoveOpInfo: {
        index: number;
        path: string;
        previousIndex: number;
        type: "move";
    }

    MoveOpInfo represents the information of the move operation.

    -

    Type declaration

    • index: number
    • path: string
    • previousIndex: number
    • type: "move"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/NextFn.html b/api-reference/types/NextFn.html index c5a347cd9..8a9752a5b 100644 --- a/api-reference/types/NextFn.html +++ b/api-reference/types/NextFn.html @@ -1 +1 @@ -NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file +NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/ObjectOperationInfo.html b/api-reference/types/ObjectOperationInfo.html index b36fb44e8..a1ed0df3f 100644 --- a/api-reference/types/ObjectOperationInfo.html +++ b/api-reference/types/ObjectOperationInfo.html @@ -1,2 +1,2 @@ ObjectOperationInfo | yorkie-js-sdk

    Type alias ObjectOperationInfo

    ObjectOperationInfo: SetOpInfo | RemoveOpInfo

    ObjectOperationInfo represents the OperationInfo for the JSONObject.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/OperationInfo.html b/api-reference/types/OperationInfo.html index 9ca0e5789..6c34a48b9 100644 --- a/api-reference/types/OperationInfo.html +++ b/api-reference/types/OperationInfo.html @@ -1,3 +1,3 @@ OperationInfo | yorkie-js-sdk

    Type alias OperationInfo

    OperationInfo represents the information of an operation. It is used to inform to the user what kind of operation was executed.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/PanelToSDKMessage.html b/api-reference/types/PanelToSDKMessage.html index f54a0c8d6..5f73a981c 100644 --- a/api-reference/types/PanelToSDKMessage.html +++ b/api-reference/types/PanelToSDKMessage.html @@ -1,2 +1,2 @@ PanelToSDKMessage | yorkie-js-sdk

    Type alias PanelToSDKMessage

    PanelToSDKMessage: {
        msg: "devtools::connect";
    } | {
        msg: "devtools::disconnect";
    } | {
        docKey: string;
        msg: "devtools::subscribe";
    }

    PanelToSDKMessage is a message sent from the Devtools panel to the SDK.

    -

    Type declaration

    • msg: "devtools::connect"

    Type declaration

    • msg: "devtools::disconnect"

    Type declaration

    • docKey: string
    • msg: "devtools::subscribe"
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/PrimitiveValue.html b/api-reference/types/PrimitiveValue.html index 9c93ffed2..ae01bdc96 100644 --- a/api-reference/types/PrimitiveValue.html +++ b/api-reference/types/PrimitiveValue.html @@ -1,3 +1,3 @@ PrimitiveValue | yorkie-js-sdk

    Type alias PrimitiveValue

    PrimitiveValue: null | boolean | number | Long | string | Uint8Array | Date

    PrimitiveValue represents a value of primitive type. Only values of type included in PrimitiveValue can be set to the document.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/RemoveOpInfo.html b/api-reference/types/RemoveOpInfo.html index 57dbe51c0..b0aa68840 100644 --- a/api-reference/types/RemoveOpInfo.html +++ b/api-reference/types/RemoveOpInfo.html @@ -1,2 +1,2 @@ RemoveOpInfo | yorkie-js-sdk

    Type alias RemoveOpInfo

    RemoveOpInfo: {
        index?: number;
        key?: string;
        path: string;
        type: "remove";
    }

    RemoveOpInfo represents the information of the remove operation.

    -

    Type declaration

    • Optional index?: number
    • Optional key?: string
    • path: string
    • type: "remove"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SDKToPanelMessage.html b/api-reference/types/SDKToPanelMessage.html index 9f83d3de9..876e045c6 100644 --- a/api-reference/types/SDKToPanelMessage.html +++ b/api-reference/types/SDKToPanelMessage.html @@ -1,2 +1,2 @@ SDKToPanelMessage | yorkie-js-sdk

    Type alias SDKToPanelMessage

    SDKToPanelMessage: {
        msg: "refresh-devtools";
    } | {
        docKey: string;
        msg: "doc::available";
    } | {
        docKey: string;
        events: TransactionEvent[];
        msg: "doc::sync::full";
    } | {
        docKey: string;
        event: TransactionEvent;
        msg: "doc::sync::partial";
    }

    Definition of all messages the SDK can send to the Devtools panel.

    -

    Type declaration

    • msg: "refresh-devtools"

    Type declaration

    • docKey: string
    • msg: "doc::available"

    Type declaration

    Type declaration

    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SetOpInfo.html b/api-reference/types/SetOpInfo.html index 11f337bd2..280bf83ee 100644 --- a/api-reference/types/SetOpInfo.html +++ b/api-reference/types/SetOpInfo.html @@ -1,2 +1,2 @@ SetOpInfo | yorkie-js-sdk

    Type alias SetOpInfo

    SetOpInfo: {
        key: string;
        path: string;
        type: "set";
    }

    SetOpInfo represents the information of the set operation.

    -

    Type declaration

    • key: string
    • path: string
    • type: "set"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/StyleOpInfo.html b/api-reference/types/StyleOpInfo.html index dc2ddeaae..c17013332 100644 --- a/api-reference/types/StyleOpInfo.html +++ b/api-reference/types/StyleOpInfo.html @@ -1,2 +1,2 @@ StyleOpInfo | yorkie-js-sdk

    Type alias StyleOpInfo

    StyleOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "style";
        value: {
            attributes: Indexable;
        };
    }

    StyleOpInfo represents the information of the style operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "style"
    • value: {
          attributes: Indexable;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextNode.html b/api-reference/types/TextNode.html index ea50e9ef0..b89763dda 100644 --- a/api-reference/types/TextNode.html +++ b/api-reference/types/TextNode.html @@ -1,2 +1,2 @@ TextNode | yorkie-js-sdk

    Type alias TextNode

    TextNode: {
        type: typeof DefaultTextType;
        value: string;
    }

    TextNode represents a text node. It has a string value.

    -

    Type declaration

    • type: typeof DefaultTextType
    • value: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextOperationInfo.html b/api-reference/types/TextOperationInfo.html index b8c2afc6f..bd6bfb1b6 100644 --- a/api-reference/types/TextOperationInfo.html +++ b/api-reference/types/TextOperationInfo.html @@ -1,2 +1,2 @@ TextOperationInfo | yorkie-js-sdk

    Type alias TextOperationInfo

    TextOperationInfo: EditOpInfo | StyleOpInfo

    TextOperationInfo represents the OperationInfo for the yorkie.Text.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TextPosStruct.html b/api-reference/types/TextPosStruct.html index 833c5f18f..18aec9018 100644 --- a/api-reference/types/TextPosStruct.html +++ b/api-reference/types/TextPosStruct.html @@ -1,3 +1,3 @@ TextPosStruct | yorkie-js-sdk

    Type alias TextPosStruct

    TextPosStruct: {
        id: {
            createdAt: TimeTicketStruct;
            offset: number;
        };
        relativeOffset: number;
    }

    TextPosStruct represents the structure of RGATreeSplitPos. It is used to serialize and deserialize the RGATreeSplitPos.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextPosStructRange.html b/api-reference/types/TextPosStructRange.html index 19e25897c..7aea8e67b 100644 --- a/api-reference/types/TextPosStructRange.html +++ b/api-reference/types/TextPosStructRange.html @@ -1,3 +1,3 @@ TextPosStructRange | yorkie-js-sdk

    Type alias TextPosStructRange

    TextPosStructRange: [TextPosStruct, TextPosStruct]

    TextPosStructRange represents the structure of RGATreeSplitPosRange. It is used to serialize and deserialize the RGATreeSplitPosRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TimeTicketStruct.html b/api-reference/types/TimeTicketStruct.html index 624789f0c..9d984e461 100644 --- a/api-reference/types/TimeTicketStruct.html +++ b/api-reference/types/TimeTicketStruct.html @@ -1,3 +1,3 @@ TimeTicketStruct | yorkie-js-sdk

    Type alias TimeTicketStruct

    TimeTicketStruct: {
        actorID: ActorID;
        delimiter: number;
        lamport: string;
    }

    TimeTicketStruct is a structure represents the meta data of the ticket. It is used to serialize and deserialize the ticket.

    -

    Type declaration

    • actorID: ActorID
    • delimiter: number
    • lamport: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TransactionEvent.html b/api-reference/types/TransactionEvent.html index de4d645ad..001e11e4a 100644 --- a/api-reference/types/TransactionEvent.html +++ b/api-reference/types/TransactionEvent.html @@ -1,3 +1,3 @@ TransactionEvent | yorkie-js-sdk

    Type alias TransactionEvent<P>

    TransactionEvent<P>: DocEvent<P>[]

    TransactionEvent represents document events that occur within a single transaction (e.g., doc.update).

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/TreeChange.html b/api-reference/types/TreeChange.html index 55328ff7a..6c60611e7 100644 --- a/api-reference/types/TreeChange.html +++ b/api-reference/types/TreeChange.html @@ -1,2 +1,2 @@ TreeChange | yorkie-js-sdk

    Type alias TreeChange

    TreeChange: {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Content;
        value?: TreeNode[];
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Style;
        value: {
            [key: string]: string;
        };
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: RemoveStyle;
        value?: string[];
    }

    TreeChange represents the change in the tree.

    -

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Content
    • Optional value?: TreeNode[]

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Style
    • value: {
          [key: string]: string;
      }
      • [key: string]: string

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: RemoveStyle
    • Optional value?: string[]
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeEditOpInfo.html b/api-reference/types/TreeEditOpInfo.html index 042c77eca..12750d24f 100644 --- a/api-reference/types/TreeEditOpInfo.html +++ b/api-reference/types/TreeEditOpInfo.html @@ -1,2 +1,2 @@ TreeEditOpInfo | yorkie-js-sdk

    Type alias TreeEditOpInfo

    TreeEditOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: "tree-edit";
        value?: TreeNode[];
    }

    TreeEditOpInfo represents the information of the tree edit operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: "tree-edit"
    • Optional value?: TreeNode[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeNode.html b/api-reference/types/TreeNode.html index 954a7d193..1a9449683 100644 --- a/api-reference/types/TreeNode.html +++ b/api-reference/types/TreeNode.html @@ -1,2 +1,2 @@ TreeNode | yorkie-js-sdk

    Type alias TreeNode

    TreeNode: TextNode | ElementNode

    TreeNode represents a node in the tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeOperationInfo.html b/api-reference/types/TreeOperationInfo.html index 1a4942c7c..787bdf266 100644 --- a/api-reference/types/TreeOperationInfo.html +++ b/api-reference/types/TreeOperationInfo.html @@ -1,2 +1,2 @@ TreeOperationInfo | yorkie-js-sdk

    Type alias TreeOperationInfo

    TreeOperationInfo: TreeEditOpInfo | TreeStyleOpInfo

    TreeOperationInfo represents the OperationInfo for the yorkie.Tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreePosStructRange.html b/api-reference/types/TreePosStructRange.html index 78f92b19d..236604497 100644 --- a/api-reference/types/TreePosStructRange.html +++ b/api-reference/types/TreePosStructRange.html @@ -1,3 +1,3 @@ TreePosStructRange | yorkie-js-sdk

    Type alias TreePosStructRange

    TreePosStructRange: [CRDTTreePosStruct, CRDTTreePosStruct]

    TreePosStructRange represents the structure of TreeRange. It is used to serialize and deserialize the TreeRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeStyleOpInfo.html b/api-reference/types/TreeStyleOpInfo.html index 5d6e2ec0a..483665182 100644 --- a/api-reference/types/TreeStyleOpInfo.html +++ b/api-reference/types/TreeStyleOpInfo.html @@ -1,2 +1,2 @@ TreeStyleOpInfo | yorkie-js-sdk

    Type alias TreeStyleOpInfo

    TreeStyleOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        to: number;
        toPath: number[];
        type: "tree-style";
        value: {
            attributes?: Indexable;
            attributesToRemove?: string[];
        };
    }

    TreeStyleOpInfo represents the information of the tree style operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • to: number
    • toPath: number[]
    • type: "tree-style"
    • value: {
          attributes?: Indexable;
          attributesToRemove?: string[];
      }
      • Optional attributes?: Indexable
      • Optional attributesToRemove?: string[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Unsubscribe.html b/api-reference/types/Unsubscribe.html index be928099e..6a2dc4276 100644 --- a/api-reference/types/Unsubscribe.html +++ b/api-reference/types/Unsubscribe.html @@ -1 +1 @@ -Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/WrappedElement.html b/api-reference/types/WrappedElement.html index d54fe77d0..a6204e8ed 100644 --- a/api-reference/types/WrappedElement.html +++ b/api-reference/types/WrappedElement.html @@ -1,2 +1,2 @@ WrappedElement | yorkie-js-sdk

    Type alias WrappedElement<T, A>

    WrappedElement<T, A>: Primitive | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    WrappedElement is a wrapper of JSONElement that provides getID().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/variables/EventSourceDevPanel.html b/api-reference/variables/EventSourceDevPanel.html index bc582fd14..2f3756848 100644 --- a/api-reference/variables/EventSourceDevPanel.html +++ b/api-reference/variables/EventSourceDevPanel.html @@ -1,3 +1,3 @@ EventSourceDevPanel | yorkie-js-sdk

    Variable EventSourceDevPanelConst

    EventSourceDevPanel: "yorkie-devtools-panel" = 'yorkie-devtools-panel'

    EventSourceDevPanel is the name of the source representing messages from the Devtools panel.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/EventSourceSDK.html b/api-reference/variables/EventSourceSDK.html index 7208dcf1b..bdd26c5b4 100644 --- a/api-reference/variables/EventSourceSDK.html +++ b/api-reference/variables/EventSourceSDK.html @@ -1,3 +1,3 @@ EventSourceSDK | yorkie-js-sdk

    Variable EventSourceSDKConst

    EventSourceSDK: "yorkie-devtools-sdk" = 'yorkie-devtools-sdk'

    EventSourceSDK is the name of the source representing messages from the SDK.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/converter.html b/api-reference/variables/converter.html index d66ffa0db..cb9c41f2c 100644 --- a/api-reference/variables/converter.html +++ b/api-reference/variables/converter.html @@ -17,4 +17,4 @@

    Parameters

    Returns string

  • toOperation: ((operation) => PbOperation)
  • toTreeNodes: ((node) => PbTreeNode[])
  • toUint8Array: ((hex) => Uint8Array)
  • \ No newline at end of file +

    Parameters

    Returns Uint8Array

    \ No newline at end of file diff --git a/api-reference/variables/default.html b/api-reference/variables/default.html index b4589ac95..1159b82a1 100644 --- a/api-reference/variables/default.html +++ b/api-reference/variables/default.html @@ -3,4 +3,4 @@ assigned to the yorkie global.

    e.g) new yorkie.Client(...);

    Type declaration

    \ No newline at end of file +

    Parameters

    Returns void

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/404.html b/examples/nextjs-scheduler/404.html index 5bd2ca519..72f05a1c0 100644 --- a/examples/nextjs-scheduler/404.html +++ b/examples/nextjs-scheduler/404.html @@ -1 +1 @@ -Next.js react-calendar example

    404 not found

    \ No newline at end of file +Next.js react-calendar example

    404 not found

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/_next/static/kQt9G5eCknYR1Jo9JAzZb/_buildManifest.js b/examples/nextjs-scheduler/_next/static/BrIaRMbmS6x-HiSUkVY_9/_buildManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/kQt9G5eCknYR1Jo9JAzZb/_buildManifest.js rename to examples/nextjs-scheduler/_next/static/BrIaRMbmS6x-HiSUkVY_9/_buildManifest.js diff --git a/examples/nextjs-scheduler/_next/static/kQt9G5eCknYR1Jo9JAzZb/_ssgManifest.js b/examples/nextjs-scheduler/_next/static/BrIaRMbmS6x-HiSUkVY_9/_ssgManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/kQt9G5eCknYR1Jo9JAzZb/_ssgManifest.js rename to examples/nextjs-scheduler/_next/static/BrIaRMbmS6x-HiSUkVY_9/_ssgManifest.js diff --git a/examples/nextjs-scheduler/_next/static/chunks/app/page-0a8828fab7d2ebab.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-0a8828fab7d2ebab.js new file mode 100644 index 000000000..7f196f6f8 --- /dev/null +++ b/examples/nextjs-scheduler/_next/static/chunks/app/page-0a8828fab7d2ebab.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,6464))},6464:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return ni}});var n,i,s,a,o,h,c,l,d,u,g,f,m,p,y,v,A,T,S,I,C,w,x,k,E,b,P,D,R,N,O,M,_=r(3165),B=r(7397),L=r.n(B),K=r(6189);let z=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function U(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var J=r(8358),j=r(6390),q=r(4715),F=r(1582),V=r(601),W=r(6731),G=r(9782);let H=V.w.makeEnum("yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL",localName:"NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN",localName:"BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER",localName:"INTEGER"},{no:3,name:"VALUE_TYPE_LONG",localName:"LONG"},{no:4,name:"VALUE_TYPE_DOUBLE",localName:"DOUBLE"},{no:5,name:"VALUE_TYPE_STRING",localName:"STRING"},{no:6,name:"VALUE_TYPE_BYTES",localName:"BYTES"},{no:7,name:"VALUE_TYPE_DATE",localName:"DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT",localName:"JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY",localName:"JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT",localName:"TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT",localName:"INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT",localName:"LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE",localName:"TREE"}]),Y=V.w.makeEnum("yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED",localName:"DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED",localName:"DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED",localName:"DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST",localName:"DOCUMENT_BROADCAST"}]),Z=V.w.makeMessageType("yorkie.v1.Snapshot",()=>[{no:1,name:"root",kind:"message",T:eu},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eR}}]),X=V.w.makeMessageType("yorkie.v1.ChangePack",()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eN},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:Q,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:eM},{no:6,name:"is_removed",kind:"scalar",T:8}]),Q=V.w.makeMessageType("yorkie.v1.Change",()=>[{no:1,name:"id",kind:"message",T:$},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ee,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eP}]),$=V.w.makeMessageType("yorkie.v1.ChangeID",()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3,L:1},{no:3,name:"lamport",kind:"scalar",T:3,L:1},{no:4,name:"actor_id",kind:"scalar",T:12}]),ee=V.w.makeMessageType("yorkie.v1.Operation",()=>[{no:1,name:"set",kind:"message",T:et,oneof:"body"},{no:2,name:"add",kind:"message",T:er,oneof:"body"},{no:3,name:"move",kind:"message",T:en,oneof:"body"},{no:4,name:"remove",kind:"message",T:ei,oneof:"body"},{no:5,name:"edit",kind:"message",T:es,oneof:"body"},{no:6,name:"select",kind:"message",T:ea,oneof:"body"},{no:7,name:"style",kind:"message",T:eo,oneof:"body"},{no:8,name:"increase",kind:"message",T:eh,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ec,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:el,oneof:"body"}]),et=V.w.makeMessageType("yorkie.v1.Operation.Set",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ed},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Set"}),er=V.w.makeMessageType("yorkie.v1.Operation.Add",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"prev_created_at",kind:"message",T:eM},{no:3,name:"value",kind:"message",T:ed},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Add"}),en=V.w.makeMessageType("yorkie.v1.Operation.Move",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"prev_created_at",kind:"message",T:eM},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Move"}),ei=V.w.makeMessageType("yorkie.v1.Operation.Remove",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Remove"}),es=V.w.makeMessageType("yorkie.v1.Operation.Edit",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:eM},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"Operation_Edit"}),ea=V.w.makeMessageType("yorkie.v1.Operation.Select",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Select"}),eo=V.w.makeMessageType("yorkie.v1.Operation.Style",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:eM},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}}],{localName:"Operation_Style"}),eh=V.w.makeMessageType("yorkie.v1.Operation.Increase",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"value",kind:"message",T:ed},{no:3,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Increase"}),ec=V.w.makeMessageType("yorkie.v1.Operation.TreeEdit",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eE},{no:3,name:"to",kind:"message",T:eE},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}},{no:5,name:"contents",kind:"message",T:ex,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_TreeEdit"}),el=V.w.makeMessageType("yorkie.v1.Operation.TreeStyle",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eE},{no:3,name:"to",kind:"message",T:eE},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:eM},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}}],{localName:"Operation_TreeStyle"}),ed=V.w.makeMessageType("yorkie.v1.JSONElementSimple",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"moved_at",kind:"message",T:eM},{no:3,name:"removed_at",kind:"message",T:eM},{no:4,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:5,name:"value",kind:"scalar",T:12}]),eu=V.w.makeMessageType("yorkie.v1.JSONElement",()=>[{no:1,name:"json_object",kind:"message",T:eg,oneof:"body"},{no:2,name:"json_array",kind:"message",T:ef,oneof:"body"},{no:3,name:"primitive",kind:"message",T:em,oneof:"body"},{no:5,name:"text",kind:"message",T:ep,oneof:"body"},{no:6,name:"counter",kind:"message",T:ey,oneof:"body"},{no:7,name:"tree",kind:"message",T:ev,oneof:"body"}]),eg=V.w.makeMessageType("yorkie.v1.JSONElement.JSONObject",()=>[{no:1,name:"nodes",kind:"message",T:eA,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_JSONObject"}),ef=V.w.makeMessageType("yorkie.v1.JSONElement.JSONArray",()=>[{no:1,name:"nodes",kind:"message",T:eT,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_JSONArray"}),em=V.w.makeMessageType("yorkie.v1.JSONElement.Primitive",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"moved_at",kind:"message",T:eM},{no:5,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Primitive"}),ep=V.w.makeMessageType("yorkie.v1.JSONElement.Text",()=>[{no:1,name:"nodes",kind:"message",T:eI,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Text"}),ey=V.w.makeMessageType("yorkie.v1.JSONElement.Counter",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"moved_at",kind:"message",T:eM},{no:5,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Counter"}),ev=V.w.makeMessageType("yorkie.v1.JSONElement.Tree",()=>[{no:1,name:"nodes",kind:"message",T:ew,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Tree"}),eA=V.w.makeMessageType("yorkie.v1.RHTNode",()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eu}]),eT=V.w.makeMessageType("yorkie.v1.RGANode",()=>[{no:1,name:"next",kind:"message",T:eT},{no:2,name:"element",kind:"message",T:eu}]),eS=V.w.makeMessageType("yorkie.v1.NodeAttr",()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:eM},{no:3,name:"is_removed",kind:"scalar",T:8}]),eI=V.w.makeMessageType("yorkie.v1.TextNode",()=>[{no:1,name:"id",kind:"message",T:eC},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:eM},{no:4,name:"ins_prev_id",kind:"message",T:eC},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eS}}]),eC=V.w.makeMessageType("yorkie.v1.TextNodeID",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5}]),ew=V.w.makeMessageType("yorkie.v1.TreeNode",()=>[{no:1,name:"id",kind:"message",T:ek},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:eM},{no:5,name:"ins_prev_id",kind:"message",T:ek},{no:6,name:"ins_next_id",kind:"message",T:ek},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eS}}]),ex=V.w.makeMessageType("yorkie.v1.TreeNodes",()=>[{no:1,name:"content",kind:"message",T:ew,repeated:!0}]),ek=V.w.makeMessageType("yorkie.v1.TreeNodeID",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5}]),eE=V.w.makeMessageType("yorkie.v1.TreePos",()=>[{no:1,name:"parent_id",kind:"message",T:ek},{no:2,name:"left_sibling_id",kind:"message",T:ek}]);V.w.makeMessageType("yorkie.v1.User",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:W.E}]),V.w.makeMessageType("yorkie.v1.Project",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:W.E},{no:9,name:"updated_at",kind:"message",T:W.E}]),V.w.makeMessageType("yorkie.v1.UpdatableProjectFields",()=>[{no:1,name:"name",kind:"message",T:G.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:G.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eb},{no:4,name:"client_deactivate_threshold",kind:"message",T:G.Gm}]);let eb=V.w.makeMessageType("yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}],{localName:"UpdatableProjectFields_AuthWebhookMethods"});V.w.makeMessageType("yorkie.v1.DocumentSummary",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:W.E},{no:5,name:"accessed_at",kind:"message",T:W.E},{no:6,name:"updated_at",kind:"message",T:W.E}]);let eP=V.w.makeMessageType("yorkie.v1.PresenceChange",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(eD)},{no:2,name:"presence",kind:"message",T:eR}]),eD=V.w.makeEnum("yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT",localName:"PUT"},{no:2,name:"CHANGE_TYPE_DELETE",localName:"DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR",localName:"CLEAR"}]),eR=V.w.makeMessageType("yorkie.v1.Presence",()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]),eN=V.w.makeMessageType("yorkie.v1.Checkpoint",()=>[{no:1,name:"server_seq",kind:"scalar",T:3,L:1},{no:2,name:"client_seq",kind:"scalar",T:13}]),eO=V.w.makeMessageType("yorkie.v1.TextNodePos",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]),eM=V.w.makeMessageType("yorkie.v1.TimeTicket",()=>[{no:1,name:"lamport",kind:"scalar",T:3,L:1},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]),e_=V.w.makeMessageType("yorkie.v1.DocEventBody",()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]),eB=V.w.makeMessageType("yorkie.v1.DocEvent",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(Y)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:e_}]),eL=V.w.makeMessageType("yorkie.v1.ActivateClientRequest",()=>[{no:1,name:"client_key",kind:"scalar",T:9}]),eK=V.w.makeMessageType("yorkie.v1.ActivateClientResponse",()=>[{no:1,name:"client_id",kind:"scalar",T:9}]),ez=V.w.makeMessageType("yorkie.v1.DeactivateClientRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9}]),eU=V.w.makeMessageType("yorkie.v1.DeactivateClientResponse",[]),eJ=V.w.makeMessageType("yorkie.v1.AttachDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:X}]),ej=V.w.makeMessageType("yorkie.v1.AttachDocumentResponse",()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:X}]),eq=V.w.makeMessageType("yorkie.v1.DetachDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]),eF=V.w.makeMessageType("yorkie.v1.DetachDocumentResponse",()=>[{no:2,name:"change_pack",kind:"message",T:X}]),eV=V.w.makeMessageType("yorkie.v1.WatchDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]),eW=V.w.makeMessageType("yorkie.v1.WatchDocumentResponse",()=>[{no:1,name:"initialization",kind:"message",T:eG,oneof:"body"},{no:2,name:"event",kind:"message",T:eB,oneof:"body"}]),eG=V.w.makeMessageType("yorkie.v1.WatchDocumentResponse.Initialization",()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}],{localName:"WatchDocumentResponse_Initialization"}),eH=V.w.makeMessageType("yorkie.v1.RemoveDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X}]),eY=V.w.makeMessageType("yorkie.v1.RemoveDocumentResponse",()=>[{no:1,name:"change_pack",kind:"message",T:X}]),eZ=V.w.makeMessageType("yorkie.v1.PushPullChangesRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X},{no:4,name:"push_only",kind:"scalar",T:8}]),eX=V.w.makeMessageType("yorkie.v1.PushPullChangesResponse",()=>[{no:1,name:"change_pack",kind:"message",T:X}]),eQ=V.w.makeMessageType("yorkie.v1.BroadcastRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]),e$=V.w.makeMessageType("yorkie.v1.BroadcastResponse",[]);var e0=r(6438);let e1={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eL,O:eK,kind:e0.t.Unary},deactivateClient:{name:"DeactivateClient",I:ez,O:eU,kind:e0.t.Unary},attachDocument:{name:"AttachDocument",I:eJ,O:ej,kind:e0.t.Unary},detachDocument:{name:"DetachDocument",I:eq,O:eF,kind:e0.t.Unary},removeDocument:{name:"RemoveDocument",I:eH,O:eY,kind:e0.t.Unary},pushPullChanges:{name:"PushPullChanges",I:eZ,O:eX,kind:e0.t.Unary},watchDocument:{name:"WatchDocument",I:eV,O:eW,kind:e0.t.ServerStreaming},broadcast:{name:"Broadcast",I:eQ,O:e$,kind:e0.t.Unary}}};var e2=r(7319),e3=r(624);(n=A||(A={})).Ok="ok",n.ErrClientNotActivated="ErrClientNotActivated",n.ErrClientNotFound="ErrClientNotFound",n.ErrUnimplemented="ErrUnimplemented",n.ErrInvalidType="ErrInvalidType",n.ErrDummy="ErrDummy",n.ErrDocumentNotAttached="ErrDocumentNotAttached",n.ErrDocumentNotDetached="ErrDocumentNotDetached",n.ErrDocumentRemoved="ErrDocumentRemoved",n.ErrInvalidObjectKey="ErrInvalidObjectKey",n.ErrInvalidArgument="ErrInvalidArgument",n.ErrNotInitialized="ErrNotInitialized",n.ErrNotReady="ErrNotReady",n.ErrRefused="ErrRefused",n.ErrContextNotProvided="ErrContextNotProvided";class e9 extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function e4(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let e5=e=>!e||0===Object.entries(e).length,e8=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},e6=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(i=T||(T={})).Put="put",i.Clear="clear";class e7{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:e4(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let te="000000000000000000000000";class tt{static of(e,t,r){return new tt(e,t,r)}static fromStruct(e){return tt.of(e2.Z.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new tt(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tr=e2.Z.MAX_VALUE,tn=new tt(e2.Z.fromNumber(0),0,te);new tt(e2.Z.fromNumber(1),1,te);let ti=new tt(tr,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function ts(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ta{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class to extends ta{constructor(e){super(e)}}class th{static of(e,t){return new th(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tc{static create(){return new tc}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=th.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new e9(A.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tl extends to{static create(e,t){if(!t)return new tl(e,tc.create());let r=tc.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tl(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(ts(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(ts(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tl.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof to&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(s=S||(S={})).Local="local",s.Remote="remote",s.UndoRedo="undoredo";class td{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new e9(A.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tu{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tg{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new e9(A.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return this.splayNode(t),[t,e]}indexOf(e){return e&&(e===this.root||e.hasLinks())?(this.splayNode(e),this.root.getLeftWeight()):-1}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tg(e.getLeft());t.root&&t.root.setParent();let r=new tg(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}(a=I||(I={}))[a.Null=0]="Null",a[a.Boolean=1]="Boolean",a[a.Integer=2]="Integer",a[a.Long=3]="Long",a[a.Double=4]="Double",a[a.String=5]="String",a[a.Bytes=6]="Bytes",a[a.Date=7]="Date";class tf extends ta{static of(e,t){return new tf(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return e2.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(e2.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(ts(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tf.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof e2.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tf.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=e2.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tf.getPrimitiveType(e),this.value=void 0===e?null:e}}class tm extends tu{static createAfter(e,t){let r=new tm(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tp{static create(){return new tp}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tm.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tf.of(0,tn);e.setRemovedAt(tn),this.dummyHead=new tm(e),this.last=this.dummyHead,this.nodeMapByIndex=new tg,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class ty extends to{static create(e,t){if(!t)return new ty(e,tp.create());let r=tp.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new ty(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof to&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:e6(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),h,[a,a]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),a=[],o=this.rgaTreeSplit.findBetween(s,i),h=new Map,c=[];for(let e of o){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tn:ti;if(e.canStyle(r,i)){let r=h.get(t),n=e.getCreatedAt();(!r||n.after(r))&&h.set(t,n),c.push(e)}}let l=[];for(let e of c){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,o]of(a.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:e6(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,o,r);void 0!==t&&l.push({parent:e.getValue(),child:t})}}return[h,l,a]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:e6(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tx(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tk extends td{static create(e,t,r,n,i,s,a){return new tk(e,t,r,n,i,s,a)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tx))throw new e9(A.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class tE extends td{static create(e,t,r,n,i,s){return new tE(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tx))throw new e9(A.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tb="text";function tP(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new e9(A.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new e9(A.ErrRefused,"Text node cannot have children")}}function tR(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tR(n,t,r+1);t(e,r)}(h=w||(w={})).Start="Start",h.End="End",h.Text="Text";class tN{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new e9(A.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new e9(A.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new e9(A.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let a of t.children){if(r-a.paddedSizea.size;(a.isText||h)&&i([a,a.isText?"Text":"Start"],c),e(a,Math.max(0,t),Math.min(o,a.size),i),c&&i([a,"End"],c)}s+=a.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tR(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new e9(A.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let a of t.children){if(n&&a.isText&&a.size>=r-s)return e(a,r-s,n);if(r===s)break;if(!n&&a.paddedSize===r-s)return{node:t,offset:i+1};if(a.paddedSize>r-s)return e(a,r-s-1,n);s+=a.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new e9(A.ErrInvalidArgument,"invalid treePos");let i=tP(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tP(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new e9(A.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new e9(A.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tM(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tO,this.counter=0}}(c=x||(x={})).Content="content",c.Style="style",c.RemoveStyle="removeStyle";class tL{static of(e,t){return new tL(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tL.of(n.id,tK.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tL.of(tK.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),tK.of(tt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new e9(A.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tK{static of(e,t){return new tK(e,t)}static fromStruct(e){return tK.of(tt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new e9(A.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new e9(A.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tz(tK.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tz(tK.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tC);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tU(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tU)};if(e.attrs){var r;t.attributes=e6(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tJ(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(ts(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tJ(e)).join(""),"")}class tj extends ta{static create(e,t){return new tj(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,a=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=a.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),a=n?n.has(s)?n.get(s):tn:ti;if(i.canStyle(r,a)&&t){let e=l.get(s),n=i.getCreatedAt();(!e||n.after(e))&&l.set(s,n);let a=i.setAttrs(t,r),o=a.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=c[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(o).length>0&&h.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:o}),a))e&&d.push({parent:i,child:e})}}),[l,d,h]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[a,o]=this.findNodesAndSplitText(e[1],r),h=[],c=new Map,l=[];return this.traverseInPosRange(i,s,a,o,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),a=n?n.has(s)?n.get(s):tn:ti;if(i.canStyle(r,a)&&t){let e=c.get(s),n=i.getCreatedAt();for(let a of((!e||n.after(e))&&c.set(s,n),i.attrs||(i.attrs=new tC),t))for(let e of i.attrs.remove(a,r))l.push({parent:i,child:e});let a=i.parent,o=i.prevSibling||i.parent;h.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(a,o),to:this.toIndex(i,i),fromPath:this.toPath(a,o),toPath:this.toPath(i,i),value:t})}}),[c,l,h]}edit(e,t,r,n,i,s){let[a,o]=this.findNodesAndSplitText(e[0],n),[h,c]=this.findNodesAndSplitText(e[1],n),l=this.toIndex(a,o),d=this.toPath(a,o),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(a,o,h,c,(e,t)=>{let[r,i]=e;if(i===w.Start&&!t)for(let e of r.children)f.push(e);let a=r.getCreatedAt().getActorID(),o=s?s.has(a)?s.get(a):tn:ti;if(r.canDelete(n,o)||u.includes(r.parent)){let e=m.get(a),t=r.getCreatedAt();(!e||t.after(e))&&m.set(a,t),(i===w.Text||i===w.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||a.append(e);if(r>0){let e=0,t=a,s=o;for(;e{a.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tU(e));p.length&&p[p.length-1].from===l?p[p.length-1].value=t:p.push({type:"content",from:l,to:l,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),a=this.findPos(e[1]);this.edit([s,a],t,r,n,i)}move(e,t,r){throw new e9(A.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tL.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tJ(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,a;let o,h,c,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:l&&d?e.toTreePos(l,d):null;g&&(o=e.indexTree.indexOf(g),h=e.indexTree.treePosToPath(g),c=tL.fromTreePos(g).toStruct());let f={type:t.type,parent:null==l?void 0:l.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?e6(null===(a=t.attrs)||void 0===a?void 0:a.toObject()):void 0,index:o,path:h,pos:c};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(l,o)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(c,s),toPath:this.toPath(l,o),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===w.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?w.Text:w.Start]:[t,w.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,w.End];let a=i[s+1];return[a,a.isText?w.Text:w.Start]}findLeftToken(e){let[t,r]=e;if(r===w.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?w.Text:w.End]}return[t,w.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,w.Start];let a=i[s-1];return[a,a.isText?w.Text:w.End]}constructor(e,t){super(t),this.indexTree=new tN(e),this.nodeMapByID=new tB(tK.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class tq extends td{static create(e,t,r,n,i,s,a){return new tq(e,t,r,n,i,s,a)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tj))throw new e9(A.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>tt.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:a,toPath:o}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:a,toPath:o}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tJ(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class tF{static of(e,t,r,n){return new tF(e,t,r,n)}next(){return new tF(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new tF(this.clientSeq,e,this.actor):new tF(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new tF(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n){this.clientSeq=e,this.serverSeq=n,this.lamport=t,this.actor=r}}let tV=new tF(0,e2.Z.fromInt(0,!0),te);class tW{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new tW({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:a,reverseOp:o}=s;n.push(...a),o&&i.unshift(o)}return this.presenceChange&&(this.presenceChange.type===T.Put?t.set(this.id.getActorID(),e4(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rD.bytesToHex(rD.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rD.bytesToHex(rD.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return tW.create({id:rD.bytesToChangeID(rD.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rD.bytesToOperation(rD.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class tG{static create(e,t,r,n,i,s){return new tG(e,t,r,n,i,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}constructor(e,t,r,n,i,s){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=i,this.minSyncedTicket=s}}class tH{static of(e,t){return new tH(e,t)}increaseClientSeq(e){return 0===e?this:new tH(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return tH.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let tY=new tH(e2.Z.fromInt(0,!0),0);class tZ{static of(e,t){return new tZ(e,t)}static fromStruct(e){return tZ.of(tt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new tZ(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let tX=tZ.of(tn,0);class tQ{static of(e,t){return new tQ(e,t)}static fromStruct(e){let t=tZ.fromStruct(e.id);return tQ.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return tZ.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class t$ extends tu{static create(e,t){return new t$(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new e9(A.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,a=new Map,o=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),a.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[o,s,a]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[a,o]=this.findEdgesOfCandidates(e);for(let o of(s.push(a),e)){let e=o.getCreatedAt().getActorID(),a=n?r.has(e)?r.get(e):tn:ti;o.canDelete(t,a)?i.push(o):s.push(o)}return s.push(o),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(l=k||(k={}))[l.IntegerCnt=0]="IntegerCnt",l[l.LongCnt=1]="LongCnt";class t2 extends ta{static create(e,t,r){return new t2(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return e2.Z.fromBytesLE(Array.from(t));default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=t2.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof e2.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!t2.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===I.Long?this.value=this.value+e.getValue().toInt():this.value=e2.Z.fromNumber(this.value+t1(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=e2.Z.fromNumber(t).toInt():this.value=t1(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=e2.Z.fromNumber(t):this.value=t;break;default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class t3 extends td{static create(e,t,r){return new t3(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof t2))throw new e9(A.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===I.Long?e.getValue().multiply(-1):-1*e.getValue();return t3.create(this.getParentCreatedAt(),tf.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class t9 extends td{static create(e,t,r,n,i,s){return new t9(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new t9(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tj))throw new e9(A.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:a}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:a,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function t4(e){return new $({clientSeq:e.getClientSeq(),lamport:e.getLamportAsString(),actorId:rP(e.getActorID())})}function t5(e){if(e)return new eM({lamport:e.getLamportAsString(),delimiter:e.getDelimiter(),actorId:rP(e.getActorID())})}function t8(e){switch(e){case I.Null:return H.NULL;case I.Boolean:return H.BOOLEAN;case I.Integer:return H.INTEGER;case I.Long:return H.LONG;case I.Double:return H.DOUBLE;case I.String:return H.STRING;case I.Bytes:return H.BYTES;case I.Date:return H.DATE;default:throw new e9(A.ErrInvalidType,"unsupported type: ".concat(e))}}function t6(e){switch(e){case k.IntegerCnt:return H.INTEGER_CNT;case k.LongCnt:return H.LONG_CNT;default:throw new e9(A.ErrInvalidType,"unsupported type: ".concat(e))}}function t7(e){if(e instanceof tl)return new ed({type:H.JSON_OBJECT,createdAt:t5(e.getCreatedAt()),value:rE(e)});if(e instanceof ty)return new ed({type:H.JSON_ARRAY,createdAt:t5(e.getCreatedAt()),value:rs(e).toBinary()});if(e instanceof tx)return new ed({type:H.TEXT,createdAt:t5(e.getCreatedAt())});if(e instanceof tf)return new ed({type:t8(e.getType()),createdAt:t5(e.getCreatedAt()),value:e.toBytes()});if(e instanceof t2)return new ed({type:t6(e.getType()),createdAt:t5(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tj)return new ed({type:H.TREE,createdAt:t5(e.getCreatedAt()),value:ra(e).toBinary()});throw new e9(A.ErrUnimplemented,"unimplemented element")}function re(e){return new eO({createdAt:t5(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rt(e){return new eE({parentId:rr(e.getParentID()),leftSiblingId:rr(e.getLeftSiblingID())})}function rr(e){return new ek({createdAt:t5(e.getCreatedAt()),offset:e.getOffset()})}function rn(e){let t=new ee;if(e instanceof tA){let r=new et;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.key=e.getKey(),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tT){let r=new er;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.prevCreatedAt=t5(e.getPrevCreatedAt()),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tS){let r=new en;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.prevCreatedAt=t5(e.getPrevCreatedAt()),r.createdAt=t5(e.getCreatedAt()),r.executedAt=t5(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tv){let r=new ei;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.createdAt=t5(e.getCreatedAt()),r.executedAt=t5(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tk){let r=new es;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=re(e.getFromPos()),r.to=re(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=t5(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tE){let r=new eo;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=re(e.getFromPos()),r.to=re(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=t5(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof t3){let r=new eh;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tq){let r=new ec,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=rt(e.getFromPos()),r.to=rt(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new ex({content:ri(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=t5(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof t9){let r=new el;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=rt(e.getFromPos()),r.to=rt(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=t5(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new e9(A.ErrUnimplemented,"unimplemented operation");return t}function ri(e){if(!e)return[];let t=[];return tR(e,(e,r)=>{let n=new ew({id:rr(e.id),type:e.type,removedAt:t5(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rr(e.insPrevID)),e.insNextID&&(n.insNextId=rr(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new eS({value:r.getValue(),updatedAt:t5(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rs(e){let t=new eu;return t.body.case="jsonArray",t.body.value=new ef({nodes:function(e){let t=[];for(let r of e)t.push(new eT({element:ro(r.getValue())}));return t}(e.getElements()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}function ra(e){let t=new eu;return t.body.case="tree",t.body.value=new ev({nodes:ri(e.getRoot()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}function ro(e){if(e instanceof tl)return function(e){let t=new eu;return t.body.case="jsonObject",t.body.value=new eg({nodes:function(e){let t=[];for(let r of e)t.push(new eA({key:r.getStrKey(),element:ro(r.getValue())}));return t}(e.getRHT()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof ty)return rs(e);if(e instanceof tf)return function(e){let t=new eu;return t.body.case="primitive",t.body.value=new em({type:t8(e.getType()),value:e.toBytes(),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof tx)return function(e){let t=new eu;return t.body.case="text",t.body.value=new ep({nodes:function(e){let t=[];for(let n of e){var r;let e=new eI;e.id=new eC({createdAt:t5((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=t5(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new eS;t.value=e.getValue(),t.updatedAt=t5(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof t2)return function(e){let t=new eu;return t.body.case="counter",t.body.value=new ey({type:t6(e.getType()),value:e.toBytes(),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof tj)return ra(e);throw new e9(A.ErrUnimplemented,"unimplemented element")}function rh(e){for(let t of e.findDetails(e3.Qf))if(t.metadata.code)return t.metadata.code;return""}function rc(e){let t;return e.serverSeq&&(t=e2.Z.fromString(e.serverSeq,!0)),tF.of(e.clientSeq,e2.Z.fromString(e.lamport,!0),rb(e.actorId),t)}function rl(e){if(e)return tt.of(e2.Z.fromString(e.lamport,!0),e.delimiter,rb(e.actorId))}function rd(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function ru(e){switch(e){case H.NULL:return I.Null;case H.BOOLEAN:return I.Boolean;case H.INTEGER:return I.Integer;case H.LONG:return I.Long;case H.DOUBLE:return I.Double;case H.STRING:return I.String;case H.BYTES:return I.Bytes;case H.DATE:return I.Date}throw new e9(A.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rg(e){switch(e){case H.INTEGER_CNT:return k.IntegerCnt;case H.LONG_CNT:return k.LongCnt}throw new e9(A.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rf(e){switch(e.type){case H.JSON_OBJECT:if(!e.value)return tl.create(rl(e.createdAt));return rk(e.value);case H.JSON_ARRAY:if(!e.value)return ty.create(rl(e.createdAt));return function(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rC(eu.fromBinary(e).body.value)}(e.value);case H.TEXT:return tx.create(t0.create(),rl(e.createdAt));case H.TREE:return function(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rw(eu.fromBinary(e).body.value)}(e.value);case H.NULL:case H.BOOLEAN:case H.INTEGER:case H.LONG:case H.DOUBLE:case H.STRING:case H.BYTES:case H.DATE:return tf.of(tf.valueFromBytes(ru(e.type),e.value),rl(e.createdAt));case H.INTEGER_CNT:case H.LONG_CNT:return t2.create(rg(e.type),t2.valueFromBytes(rg(e.type),e.value),rl(e.createdAt))}}function rm(e){return tQ.of(tZ.of(rl(e.createdAt),e.offset),e.relativeOffset)}function rp(e){return tZ.of(rl(e.createdAt),e.offset)}function ry(e){return tL.of(rv(e.parentId),rv(e.leftSiblingId))}function rv(e){return tK.of(rl(e.createdAt),e.offset)}function rA(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rv(e.id),r=tz.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tC.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rl(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rv(e.insPrevId)),e.insNextId&&(r.insNextID=rv(e.insNextId)),r.removedAt=rl(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tj.create(r,tn).getRoot()}function rT(e){if("set"===e.body.case){let t=e.body.value;return tA.create(t.key,rf(t.value),rl(t.parentCreatedAt),rl(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tT.create(rl(t.parentCreatedAt),rl(t.prevCreatedAt),rf(t.value),rl(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tS.create(rl(t.parentCreatedAt),rl(t.prevCreatedAt),rl(t.createdAt),rl(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tv.create(rl(t.parentCreatedAt),rl(t.createdAt),rl(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tk.create(rl(t.parentCreatedAt),rm(t.from),rm(t.to),r,t.content,n,rl(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tE.create(rl(t.parentCreatedAt),rm(t.from),rm(t.to),r,n,rl(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return t3.create(rl(t.parentCreatedAt),rf(t.value),rl(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))}),tq.create(rl(t.parentCreatedAt),ry(t.from),ry(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rA(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rl(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rl(r))}),(null==n?void 0:n.length)>0)?t9.createTreeRemoveStyleOperation(rl(t.parentCreatedAt),ry(t.from),ry(t.to),i,n,rl(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),t9.create(rl(t.parentCreatedAt),ry(t.from),ry(t.to),i,r,rl(t.executedAt)))}else throw new e9(A.ErrUnimplemented,"unimplemented operation")}function rS(e){let t=[];for(let r of e)t.push(tW.create({id:rc(r.id),operations:function(e){let t=[];for(let r of e){let e=rT(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===eD.PUT){let t=rd(e.presence);return{type:T.Put,presence:t}}if(t===eD.CLEAR)return{type:T.Clear};throw new e9(A.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rI(e){let t=new tc;for(let r of e.nodes){let e=rx(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tl(rl(e.createdAt),t);return r.setMovedAt(rl(e.movedAt)),r.setRemovedAt(rl(e.removedAt)),r}function rC(e){let t=new tp;for(let r of e.nodes)t.insert(rx(r.element));let r=new ty(rl(e.createdAt),t);return r.setMovedAt(rl(e.movedAt)),r.setRemovedAt(rl(e.removedAt)),r}function rw(e){let t=rA(e.nodes);return tj.create(t,rl(e.createdAt))}function rx(e){if("jsonObject"===e.body.case)return rI(e.body.value);if("jsonArray"===e.body.case)return rC(e.body.value);if("primitive"===e.body.case)return function(e){let t=tf.of(tf.valueFromBytes(ru(e.type),e.value),rl(e.createdAt));return t.setMovedAt(rl(e.movedAt)),t.setRemovedAt(rl(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new t0,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tw.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rl(n.updatedAt))});let r=t$.create(rp(e.id),t);return r.remove(rl(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rp(n.insPrevId))),r=e}let n=new tx(t,rl(e.createdAt));return n.setMovedAt(rl(e.movedAt)),n.setRemovedAt(rl(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=t2.create(rg(e.type),t2.valueFromBytes(rg(e.type),e.value),rl(e.createdAt));return t.setMovedAt(rl(e.movedAt)),t.setRemovedAt(rl(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rw(e.body.value);throw new e9(A.ErrUnimplemented,"unimplemented element")}function rk(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rI(eu.fromBinary(e).body.value)}function rE(e){return ro(e).toBinary()}function rb(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rP(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rD={fromPresence:rd,toChangePack:function(e){var t;return new X({documentKey:e.getDocumentKey(),checkpoint:new eN({serverSeq:(t=e.getCheckpoint()).getServerSeqAsString(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new Q({id:t4(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rn(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===T.Put)return new eP({type:eD.PUT,presence:function(e){let t=new eR,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===T.Clear)return new eP({type:eD.CLEAR});throw new e9(A.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:t5(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return tG.create(e.documentKey,(t=e.checkpoint,tH.of(e2.Z.fromString(t.serverSeq,!0),t.clientSeq)),e.isRemoved,rS(e.changes),e.snapshot,rl(e.minSyncedTicket))},fromChanges:rS,toTreeNodes:ri,fromTreeNodes:rA,objectToBytes:rE,bytesToObject:rk,bytesToSnapshot:function(e){if(!e)return{root:tl.create(tn),presences:new Map};let t=Z.fromBinary(e);return{root:rx(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rd(n))}),t}(t.presences)}},bytesToHex:rb,hexToBytes:rP,toHexString:function(e){return rb(e)},toUint8Array:function(e){return rP(e)},toOperation:rn,toChangeID:t4,PbChangeID:$,bytesToChangeID:function(e){return rc($.fromBinary(e))},bytesToOperation:function(e){return rT(ee.fromBinary(e))}};(d=E||(E={}))[d.Trivial=0]="Trivial",d[d.Debug=1]="Debug",d[d.Info=2]="Info",d[d.Warn=3]="Warn",d[d.Error=4]="Error",d[d.Fatal=5]="Fatal";let rR=3;function rN(e){rR=e}let rO={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrR<=e};function rM(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class r_{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==N.RealtimeSyncOff&&(this.syncMode===N.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==N.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rB=()=>{};class rL{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new e9(A.ErrInvalidArgument,"missing observer");if(this.finalized)throw new e9(A.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rB),void 0===n.error&&(n.error=rB),void 0===n.complete&&(n.complete=rB);let i=rM(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rO.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=e4(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class rz{static create(){return new rz(tl.create(tn))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new e9(A.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof to&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof to&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof to&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new rz(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r);n.element.getRemovedAt()&&e.compare(n.element.getRemovedAt())>=0&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();void 0!==n&&e.compare(n)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tx||e instanceof tj)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function rU(e,t){let r=new rJ(e);return new Proxy(t,r.getHandlers())}class rJ{static setInternal(e,t,r,n){if(r.includes("."))throw new e9(A.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=rX(e,n,i),a=t.set(r,s,i);e.registerElement(s,t),a&&e.registerRemovedElement(a),e.push(tA.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new e9(A.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=rX(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),rJ.setInternal(e,t,r,n),!0),get:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():rZ(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]")),rJ.deleteInternal(e,t,r),!0)}}}class rj{static*iteratorInternal(e,t){for(let r of t)yield rY(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=rX(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return rj.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tS.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tS.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tS.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tS.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=rX(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tT.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return rj.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),a=4;a=0?Math.min(r,o):Math.max(o+r,0),c=void 0===n?o:n<0?h:Math.min(h+n,o),l=[];for(let r=h;r=i)return!1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var a;if((null===(a=t.get(e))||void 0===a?void 0:a.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return rY(e,n)}:"getElementByIndex"===r?r=>rY(e,t.get(r)):"getLast"===r?()=>rY(e,t.getLast()):"deleteByID"===r?r=>{let n=rj.deleteInternalByID(e,t,r);return rY(e,n)}:"insertAfter"===r?(r,n)=>{let i=rj.insertAfterInternal(e,t,r,n);return rY(e,i)}:"insertBefore"===r?(r,n)=>{let i=rj.insertBeforeInternal(e,t,r,n);return rY(e,i)}:"moveBefore"===r?(r,n)=>{rj.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{rj.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{rj.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{rj.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?rZ(e,t.get(Number(r))):"push"===r?r=>rj.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),a=2;arj.includes(e,t,r,n):"indexOf"===r?(r,n)=>rj.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>rj.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>rj.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;srZ(e,t));return Array.prototype[r].apply(a,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("array[".concat(r,"]")),rj.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class rq{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rO.isEnabled(E.Debug)&&rO.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?e8(n):void 0,a=this.context.issueTimeTicket(),[o,,h,c]=this.text.edit(i,r,a,s);for(let e of h)this.context.registerGCPair(e);return this.context.push(new tk(this.text.getCreatedAt(),i[0],i[1],o,r,s?new Map(Object.entries(s)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rO.isEnabled(E.Debug)&&rO.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=e8(r),s=this.context.issueTimeTicket(),[a,o]=this.text.setStyle(n,i,s);for(let e of o)this.context.registerGCPair(e);return this.context.push(new tE(this.text.getCreatedAt(),n[0],n[1],a,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([tQ.fromStruct(e[0]),tQ.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class rF{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new e9(A.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tf.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(t3.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new e9(A.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function rV(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tb){rW(e);let{value:r}=e,s=tz.create(tK.of(i,0),n,r);t.append(s)}else{let s;let{children:a=[]}=e,{attributes:o}=e;if("object"==typeof o&&!e5(o)){let e=e8(o);for(let[t,r]of(s=new tC,Object.entries(e)))s.set(t,r,i)}let h=tz.create(tK.of(i,0),n,void 0,s);for(let e of(t.append(h),a))rV(e,h,r)}}function rW(e){if(!e.value.length)throw new e9(A.ErrInvalidArgument,"text node cannot have empty value");return!0}function rG(e){if(!e.length)return!0;if(e[0].type===tb)for(let t of e){let{type:e}=t;if(e!==tb)throw new e9(A.ErrInvalidArgument,"element node and text node cannot be passed together");rW(t)}else for(let t of e){let{type:e}=t;if(e===tb)throw new e9(A.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class rH{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tz.create(tK.of(e.issueTimeTicket(),0),"root");let t=tz.create(tK.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)rV(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?e8(t):void 0,[a]=this.tree.style([r,n],s,i);this.context.push(t9.create(this.tree.getCreatedAt(),r,n,a,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),a=r?e8(r):void 0,[o,h]=this.tree.style([n,i],a,s);for(let e of h)this.context.registerGCPair(e);this.context.push(t9.create(this.tree.getCreatedAt(),n,i,o,a?new Map(Object.entries(a)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[a,o]=this.tree.removeStyle([n,i],r,s);for(let e of o)this.context.registerGCPair(e);this.context.push(t9.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,a,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(rG(r),r[0].type!==tb))for(let e of r){let{children:t=[]}=e;rG(t)}let s=this.context.getLastTimeTicket(),a=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tb){let e="";for(let t of r){let{value:r}=t;e+=r}a.push(tz.create(tK.of(this.context.issueTimeTicket(),0),tb,e))}else a=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tb){let{value:e}=t;r=tz.create(tK.of(i,0),n,e)}else if(t){let s;let{children:a=[]}=t,{attributes:o}=t;if("object"==typeof o&&!e5(o)){let e=e8(o);for(let[t,r]of(s=new tC,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tz.create(tK.of(e.issueTimeTicket(),0),n,void 0,s),a))rV(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,o,h]=this.tree.edit([e,t],a.length?a.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of o)this.context.registerGCPair(e);return this.context.push(tq.create(this.tree.getCreatedAt(),e,t,a.length?a:void 0,i,h,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new e9(A.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new e9(A.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[tL.fromStruct(e[0]),tL.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[tL.fromStruct(e[0]),tL.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function rY(e,t){if(t){if(t instanceof tf)return t;if(t instanceof tl)return rU(e,t);if(t instanceof ty)return function(e,t){let r=new rj(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tx)return new rq(e,t);else if(t instanceof t2){let r=new rF(k.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tj){let r=new rH;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function rZ(e,t){let r=rY(e,t);return r instanceof tf?r.getValue():r}function rX(e,t,r){let n;if(tf.isSupport(t))n=tf.of(t,r);else if(Array.isArray(t))n=ty.create(r,rj.buildArrayElements(e,t));else if("object"==typeof t)t instanceof rq?(n=tx.create(t0.create(),r),t.initialize(e,n)):t instanceof rF?(n=t2.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof rH?(n=tj.create(t.buildRoot(e),r),t.initialize(e,n)):n=tl.create(r,rJ.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class rQ{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let r$="disconnected",r0=new Map,r1=new Map;function r2(e,t){((null==t?void 0:t.force)||"disconnected"!==r$)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=r1,(u=b||(b={})).Detached="detached",u.Attached="attached",u.Removed="removed",(g=P||(P={})).StatusChanged="status-changed",g.ConnectionChanged="connection-changed",g.SyncStatusChanged="sync-status-changed",g.Snapshot="snapshot",g.LocalChange="local-change",g.RemoteChange="remote-change",g.Initialized="initialized",g.Watched="watched",g.Unwatched="unwatched",g.PresenceChanged="presence-changed",g.Broadcast="broadcast",g.LocalBroadcast="local-broadcast",(f=D||(D={})).Connected="connected",f.Disconnected="disconnected",(m=R||(R={})).Synced="synced",m.SyncFailed="sync-failed";class r3{update(e,t){if("removed"===this.getStatus())throw new e9(A.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),rU(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new e7(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rO.isEnabled(E.Trivial)&&rO.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,S.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let a=[];t.length>0&&a.push({type:"local-change",source:S.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&a.push({type:"presence-changed",source:S.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(a),rO.isEnabled(E.Trivial)&&rO.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new e9(A.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new e9(A.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),S.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,S.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),rO.isEnabled(E.Trivial)&&rO.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:e4(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return tG.create(this.key,t,!1,e)}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),rU(rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){let{root:r,presences:n}=rD.bytesToSnapshot(t);this.root=new rz(r),this.presences=n,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:S.Remote,value:{snapshot:this.isEnableDevtools()?rD.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){for(let r of(rO.isEnabled(E.Debug)&&rO.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rO.isEnabled(E.Trivial)&&rO.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rO.isEnabled(E.Debug)&&rO.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case T.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:S.Remote,value:{clientID:n,presence:i.presence}});break;case T.Clear:r.push({type:"unwatched",source:S.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===S.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:S.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===Y.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:S.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===Y.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:S.Remote,value:{clientID:r,presence:e}})}else if(t===Y.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(te),this.publish([{source:"removed"===e?S.Remote:S.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r}=e.value;if(!t)return;this.applySnapshot(e2.Z.fromString(r),rD.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=tW.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new e9(A.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?e4(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?e4(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?e4(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:e4(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:e4(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new e9(A.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new e9(A.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof td)){new e7(t,e4(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,S.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,S.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let a=this.changeID.getActorID(),o=[];n.length>0&&o.push({type:"local-change",source:S.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&o.push({type:"presence-changed",source:S.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(o)}redo(){if(this.isUpdating)throw new e9(A.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new e9(A.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof td)){new e7(t,e4(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,S.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,S.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let a=this.changeID.getActorID(),o=[];n.length>0&&o.push({type:"local-change",source:S.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&o.push({type:"presence-changed",source:S.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(o)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=rz.create(),this.changeID=tV,this.checkpoint=tY,this.localChanges=[],this.eventStream=function(e){let t=new rL(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new rQ,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||r0.has(e.getKey()))return;r1.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==P.StatusChanged&&e.type!==P.Snapshot&&e.type!==P.LocalChange&&e.type!==P.RemoteChange&&e.type!==P.Initialized&&e.type!==P.Watched&&e.type!==P.Unwatched&&e.type!==P.PresenceChanged)||(r1.get(e.getKey()).push(t),"synced"===r$&&r2({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});r0.set(e.getKey(),[t]),r2({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==r$)break;r$="connected",r2({msg:"doc::available",docKey:e.getKey()}),rO.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":r$="disconnected",rO.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":r$="synced",r2({msg:"doc::sync::full",docKey:e.getKey(),events:r1.get(e.getKey())}),rO.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var r9=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.0"}');let r4=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(p=N||(N={})).Manual="manual",p.Realtime="realtime",p.RealtimePushOnly="realtime-pushonly",p.RealtimeSyncOff="realtime-syncoff",(y=O||(O={})).Deactivated="deactivated",y.Activated="activated",(v=M||(M={})).SyncLoop="SyncLoop",v.WatchLoop="WatchLoop";let r5={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},r8={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class r6{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rO.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rO.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rO.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rO.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==b.Detached)throw new e9(A.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,a=t.options;try{await this.broadcast(e.getKey(),n,i,a)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rD.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let r=rD.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()===b.Removed||(e.applyStatus(b.Attached),this.attachmentMap.set(e.getKey(),new r_(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rO.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'))),e}).catch(e=>{throw rO.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rD.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rD.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==b.Removed&&e.applyStatus(b.Detached),this.detachInternal(e.getKey()),rO.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rO.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rO.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rO.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rD.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rD.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rO.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rO.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new e9(A.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!r4(r))throw new e9(A.ErrInvalidArgument,"payload is not serializable");let a=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:r8.maxRetries,o=r8.maxBackoff,h=0,c=e=>Math.min(r8.initialRetryInterval*2**e,o),l=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rO.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rO.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(hl(),c(++h-1)),rO.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(h,"/").concat(a));else throw rO.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return l()}runSyncLoop(){let e=()=>{if(!this.isActive()){rO.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rO.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rO.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new e9(A.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:P.ConnectionChanged,value:D.Connected}]),rO.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:P.Initialized,source:S.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:P.ConnectionChanged,value:D.Disconnected}]),rO.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===Y.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(b.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rD.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rD.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:P.SyncStatusChanged,value:R.Synced}]),r.getStatus()===b.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),a=n.getChangeSize();return rO.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(a," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:P.SyncStatusChanged,value:R.SyncFailed}]),rO.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof J.K&&(e.code===j.E.Canceled||e.code===j.E.Unknown||e.code===j.E.ResourceExhausted||e.code===j.E.Unavailable||((rh(e)===A.ErrClientNotActivated||rh(e)===A.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rO.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||r5,this.key=t.key?t.key:rM(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||r5.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||r5.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||r5.retrySyncLoopDelay,this.rpcClient=(0,q.Hb)(e1,(0,F.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",r9.u2+"/"+r9.i8),await e(t))]})),this.taskQueue=[]}}var r7={Client:r6,Document:r3,Primitive:tf,Text:rq,Counter:rF,Tree:rH,LogLevel:E,setLogLevel:rN,IntType:k.IntegerCnt,LongType:k.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:r6,Document:r3,Primitive:tf,Text:rq,Counter:rF,Tree:rH,LogLevel:E,setLogLevel:rN,IntType:k.IntegerCnt,LongType:k.LongCnt}),r(109);var ne=r(6182);function nt(e){let{content:t,actions:r}=e,[n,i]=(0,K.useState)(new Date),[s,a]=(0,K.useState)("Enter text here!"),o=n?U(new Date(n.toString())):"",h=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===o)return n=!n,0}),n?r.updateContent(o,s):r.addContent(o,s),a("Enter text here!");break;case"DELETE":r.deleteContent(o)}};return(0,_.jsx)("article",{children:(0,_.jsxs)("div",{children:[(0,_.jsx)(ne.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===U(r))?"highlight":""}}),(0,_.jsxs)("p",{children:["selected day : ",o]}),(0,_.jsx)("div",{className:L().memo,children:t.map((e,t)=>{if(e.date===o)return(0,_.jsx)("p",{children:e.text},t)})}),(0,_.jsxs)("div",{className:L().inputForm_editor,children:[(0,_.jsx)("h3",{children:"input form"}),(0,_.jsx)("textarea",{className:L().textArea,value:s,onChange:e=>a(e.target.value)})]}),(0,_.jsx)("button",{className:"button",onClick:()=>h("PUSH"),children:"push"}),(0,_.jsx)("button",{className:"button",onClick:()=>h("DELETE"),children:"pop"})]})})}let nr=[{date:U(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:U(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],nn="next.js-Scheduler-".concat(U(new Date));function ni(){let[e,t]=(0,K.useState)([]),[r,n]=(0,K.useState)(nr),[i]=(0,K.useState)(()=>new r7.Document(nn));return(0,K.useEffect)(()=>{let e=new r7.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==P.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*z.length);return z[e]}()}}),t.update(e=>{e.content||(e.content=nr)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,_.jsxs)("main",{className:L().main,children:[(0,_.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,_.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,_.jsx)(nt,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/examples/nextjs-scheduler/_next/static/chunks/app/page-c800df1f391ad564.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-c800df1f391ad564.js deleted file mode 100644 index a3e2c2069..000000000 --- a/examples/nextjs-scheduler/_next/static/chunks/app/page-c800df1f391ad564.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,6464))},6464:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return ni}});var n,i,s,a,o,h,c,l,d,u,g,f,m,p,y,v,A,T,S,I,C,w,x,k,E,b,P,D,R,N,O,M,_=r(3165),L=r(7397),B=r.n(L),K=r(6189);let z=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function U(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var J=r(8358),j=r(6390),q=r(4715),F=r(1582),V=r(601),W=r(6731),G=r(9782);let H=V.w.makeEnum("yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL",localName:"NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN",localName:"BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER",localName:"INTEGER"},{no:3,name:"VALUE_TYPE_LONG",localName:"LONG"},{no:4,name:"VALUE_TYPE_DOUBLE",localName:"DOUBLE"},{no:5,name:"VALUE_TYPE_STRING",localName:"STRING"},{no:6,name:"VALUE_TYPE_BYTES",localName:"BYTES"},{no:7,name:"VALUE_TYPE_DATE",localName:"DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT",localName:"JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY",localName:"JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT",localName:"TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT",localName:"INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT",localName:"LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE",localName:"TREE"}]),Y=V.w.makeEnum("yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED",localName:"DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED",localName:"DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED",localName:"DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST",localName:"DOCUMENT_BROADCAST"}]),Z=V.w.makeMessageType("yorkie.v1.Snapshot",()=>[{no:1,name:"root",kind:"message",T:eu},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eR}}]),X=V.w.makeMessageType("yorkie.v1.ChangePack",()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eN},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:Q,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:eM},{no:6,name:"is_removed",kind:"scalar",T:8}]),Q=V.w.makeMessageType("yorkie.v1.Change",()=>[{no:1,name:"id",kind:"message",T:$},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ee,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eP}]),$=V.w.makeMessageType("yorkie.v1.ChangeID",()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3,L:1},{no:3,name:"lamport",kind:"scalar",T:3,L:1},{no:4,name:"actor_id",kind:"scalar",T:12}]),ee=V.w.makeMessageType("yorkie.v1.Operation",()=>[{no:1,name:"set",kind:"message",T:et,oneof:"body"},{no:2,name:"add",kind:"message",T:er,oneof:"body"},{no:3,name:"move",kind:"message",T:en,oneof:"body"},{no:4,name:"remove",kind:"message",T:ei,oneof:"body"},{no:5,name:"edit",kind:"message",T:es,oneof:"body"},{no:6,name:"select",kind:"message",T:ea,oneof:"body"},{no:7,name:"style",kind:"message",T:eo,oneof:"body"},{no:8,name:"increase",kind:"message",T:eh,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ec,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:el,oneof:"body"}]),et=V.w.makeMessageType("yorkie.v1.Operation.Set",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ed},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Set"}),er=V.w.makeMessageType("yorkie.v1.Operation.Add",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"prev_created_at",kind:"message",T:eM},{no:3,name:"value",kind:"message",T:ed},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Add"}),en=V.w.makeMessageType("yorkie.v1.Operation.Move",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"prev_created_at",kind:"message",T:eM},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Move"}),ei=V.w.makeMessageType("yorkie.v1.Operation.Remove",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Remove"}),es=V.w.makeMessageType("yorkie.v1.Operation.Edit",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:eM},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"Operation_Edit"}),ea=V.w.makeMessageType("yorkie.v1.Operation.Select",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Select"}),eo=V.w.makeMessageType("yorkie.v1.Operation.Style",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eO},{no:3,name:"to",kind:"message",T:eO},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:eM},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}}],{localName:"Operation_Style"}),eh=V.w.makeMessageType("yorkie.v1.Operation.Increase",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"value",kind:"message",T:ed},{no:3,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_Increase"}),ec=V.w.makeMessageType("yorkie.v1.Operation.TreeEdit",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eE},{no:3,name:"to",kind:"message",T:eE},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}},{no:5,name:"contents",kind:"message",T:ex,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:eM}],{localName:"Operation_TreeEdit"}),el=V.w.makeMessageType("yorkie.v1.Operation.TreeStyle",()=>[{no:1,name:"parent_created_at",kind:"message",T:eM},{no:2,name:"from",kind:"message",T:eE},{no:3,name:"to",kind:"message",T:eE},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:eM},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:eM}}],{localName:"Operation_TreeStyle"}),ed=V.w.makeMessageType("yorkie.v1.JSONElementSimple",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"moved_at",kind:"message",T:eM},{no:3,name:"removed_at",kind:"message",T:eM},{no:4,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:5,name:"value",kind:"scalar",T:12}]),eu=V.w.makeMessageType("yorkie.v1.JSONElement",()=>[{no:1,name:"json_object",kind:"message",T:eg,oneof:"body"},{no:2,name:"json_array",kind:"message",T:ef,oneof:"body"},{no:3,name:"primitive",kind:"message",T:em,oneof:"body"},{no:5,name:"text",kind:"message",T:ep,oneof:"body"},{no:6,name:"counter",kind:"message",T:ey,oneof:"body"},{no:7,name:"tree",kind:"message",T:ev,oneof:"body"}]),eg=V.w.makeMessageType("yorkie.v1.JSONElement.JSONObject",()=>[{no:1,name:"nodes",kind:"message",T:eA,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_JSONObject"}),ef=V.w.makeMessageType("yorkie.v1.JSONElement.JSONArray",()=>[{no:1,name:"nodes",kind:"message",T:eT,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_JSONArray"}),em=V.w.makeMessageType("yorkie.v1.JSONElement.Primitive",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"moved_at",kind:"message",T:eM},{no:5,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Primitive"}),ep=V.w.makeMessageType("yorkie.v1.JSONElement.Text",()=>[{no:1,name:"nodes",kind:"message",T:eI,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Text"}),ey=V.w.makeMessageType("yorkie.v1.JSONElement.Counter",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(H)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:eM},{no:4,name:"moved_at",kind:"message",T:eM},{no:5,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Counter"}),ev=V.w.makeMessageType("yorkie.v1.JSONElement.Tree",()=>[{no:1,name:"nodes",kind:"message",T:ew,repeated:!0},{no:2,name:"created_at",kind:"message",T:eM},{no:3,name:"moved_at",kind:"message",T:eM},{no:4,name:"removed_at",kind:"message",T:eM}],{localName:"JSONElement_Tree"}),eA=V.w.makeMessageType("yorkie.v1.RHTNode",()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eu}]),eT=V.w.makeMessageType("yorkie.v1.RGANode",()=>[{no:1,name:"next",kind:"message",T:eT},{no:2,name:"element",kind:"message",T:eu}]),eS=V.w.makeMessageType("yorkie.v1.NodeAttr",()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:eM},{no:3,name:"is_removed",kind:"scalar",T:8}]),eI=V.w.makeMessageType("yorkie.v1.TextNode",()=>[{no:1,name:"id",kind:"message",T:eC},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:eM},{no:4,name:"ins_prev_id",kind:"message",T:eC},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eS}}]),eC=V.w.makeMessageType("yorkie.v1.TextNodeID",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5}]),ew=V.w.makeMessageType("yorkie.v1.TreeNode",()=>[{no:1,name:"id",kind:"message",T:ek},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:eM},{no:5,name:"ins_prev_id",kind:"message",T:ek},{no:6,name:"ins_next_id",kind:"message",T:ek},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eS}}]),ex=V.w.makeMessageType("yorkie.v1.TreeNodes",()=>[{no:1,name:"content",kind:"message",T:ew,repeated:!0}]),ek=V.w.makeMessageType("yorkie.v1.TreeNodeID",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5}]),eE=V.w.makeMessageType("yorkie.v1.TreePos",()=>[{no:1,name:"parent_id",kind:"message",T:ek},{no:2,name:"left_sibling_id",kind:"message",T:ek}]);V.w.makeMessageType("yorkie.v1.User",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:W.E}]),V.w.makeMessageType("yorkie.v1.Project",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:W.E},{no:9,name:"updated_at",kind:"message",T:W.E}]),V.w.makeMessageType("yorkie.v1.UpdatableProjectFields",()=>[{no:1,name:"name",kind:"message",T:G.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:G.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eb},{no:4,name:"client_deactivate_threshold",kind:"message",T:G.Gm}]);let eb=V.w.makeMessageType("yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}],{localName:"UpdatableProjectFields_AuthWebhookMethods"});V.w.makeMessageType("yorkie.v1.DocumentSummary",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:W.E},{no:5,name:"accessed_at",kind:"message",T:W.E},{no:6,name:"updated_at",kind:"message",T:W.E}]);let eP=V.w.makeMessageType("yorkie.v1.PresenceChange",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(eD)},{no:2,name:"presence",kind:"message",T:eR}]),eD=V.w.makeEnum("yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT",localName:"PUT"},{no:2,name:"CHANGE_TYPE_DELETE",localName:"DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR",localName:"CLEAR"}]),eR=V.w.makeMessageType("yorkie.v1.Presence",()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]),eN=V.w.makeMessageType("yorkie.v1.Checkpoint",()=>[{no:1,name:"server_seq",kind:"scalar",T:3,L:1},{no:2,name:"client_seq",kind:"scalar",T:13}]),eO=V.w.makeMessageType("yorkie.v1.TextNodePos",()=>[{no:1,name:"created_at",kind:"message",T:eM},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]),eM=V.w.makeMessageType("yorkie.v1.TimeTicket",()=>[{no:1,name:"lamport",kind:"scalar",T:3,L:1},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]),e_=V.w.makeMessageType("yorkie.v1.DocEventBody",()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]),eL=V.w.makeMessageType("yorkie.v1.DocEvent",()=>[{no:1,name:"type",kind:"enum",T:V.w.getEnumType(Y)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:e_}]),eB=V.w.makeMessageType("yorkie.v1.ActivateClientRequest",()=>[{no:1,name:"client_key",kind:"scalar",T:9}]),eK=V.w.makeMessageType("yorkie.v1.ActivateClientResponse",()=>[{no:1,name:"client_id",kind:"scalar",T:9}]),ez=V.w.makeMessageType("yorkie.v1.DeactivateClientRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9}]),eU=V.w.makeMessageType("yorkie.v1.DeactivateClientResponse",[]),eJ=V.w.makeMessageType("yorkie.v1.AttachDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:X}]),ej=V.w.makeMessageType("yorkie.v1.AttachDocumentResponse",()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:X}]),eq=V.w.makeMessageType("yorkie.v1.DetachDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]),eF=V.w.makeMessageType("yorkie.v1.DetachDocumentResponse",()=>[{no:2,name:"change_pack",kind:"message",T:X}]),eV=V.w.makeMessageType("yorkie.v1.WatchDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]),eW=V.w.makeMessageType("yorkie.v1.WatchDocumentResponse",()=>[{no:1,name:"initialization",kind:"message",T:eG,oneof:"body"},{no:2,name:"event",kind:"message",T:eL,oneof:"body"}]),eG=V.w.makeMessageType("yorkie.v1.WatchDocumentResponse.Initialization",()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}],{localName:"WatchDocumentResponse_Initialization"}),eH=V.w.makeMessageType("yorkie.v1.RemoveDocumentRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X}]),eY=V.w.makeMessageType("yorkie.v1.RemoveDocumentResponse",()=>[{no:1,name:"change_pack",kind:"message",T:X}]),eZ=V.w.makeMessageType("yorkie.v1.PushPullChangesRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:X},{no:4,name:"push_only",kind:"scalar",T:8}]),eX=V.w.makeMessageType("yorkie.v1.PushPullChangesResponse",()=>[{no:1,name:"change_pack",kind:"message",T:X}]),eQ=V.w.makeMessageType("yorkie.v1.BroadcastRequest",()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]),e$=V.w.makeMessageType("yorkie.v1.BroadcastResponse",[]);var e0=r(6438);let e1={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eB,O:eK,kind:e0.t.Unary},deactivateClient:{name:"DeactivateClient",I:ez,O:eU,kind:e0.t.Unary},attachDocument:{name:"AttachDocument",I:eJ,O:ej,kind:e0.t.Unary},detachDocument:{name:"DetachDocument",I:eq,O:eF,kind:e0.t.Unary},removeDocument:{name:"RemoveDocument",I:eH,O:eY,kind:e0.t.Unary},pushPullChanges:{name:"PushPullChanges",I:eZ,O:eX,kind:e0.t.Unary},watchDocument:{name:"WatchDocument",I:eV,O:eW,kind:e0.t.ServerStreaming},broadcast:{name:"Broadcast",I:eQ,O:e$,kind:e0.t.Unary}}};var e2=r(7319),e3=r(624);(n=A||(A={})).Ok="ok",n.ErrClientNotActivated="ErrClientNotActivated",n.ErrClientNotFound="ErrClientNotFound",n.ErrUnimplemented="ErrUnimplemented",n.ErrInvalidType="ErrInvalidType",n.ErrDummy="ErrDummy",n.ErrDocumentNotAttached="ErrDocumentNotAttached",n.ErrDocumentNotDetached="ErrDocumentNotDetached",n.ErrDocumentRemoved="ErrDocumentRemoved",n.ErrInvalidObjectKey="ErrInvalidObjectKey",n.ErrInvalidArgument="ErrInvalidArgument",n.ErrNotInitialized="ErrNotInitialized",n.ErrNotReady="ErrNotReady",n.ErrRefused="ErrRefused",n.ErrContextNotProvided="ErrContextNotProvided";class e9 extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function e4(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let e5=e=>!e||0===Object.entries(e).length,e8=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},e6=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(i=T||(T={})).Put="put",i.Clear="clear";class e7{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:e4(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let te="000000000000000000000000";class tt{static of(e,t,r){return new tt(e,t,r)}static fromStruct(e){return tt.of(e2.Z.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new tt(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tr=e2.Z.MAX_VALUE,tn=new tt(e2.Z.fromNumber(0),0,te);new tt(e2.Z.fromNumber(1),1,te);let ti=new tt(tr,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function ts(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ta{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class to extends ta{constructor(e){super(e)}}class th{static of(e,t){return new th(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tc{static create(){return new tc}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=th.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new e9(A.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tl extends to{static create(e,t){if(!t)return new tl(e,tc.create());let r=tc.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tl(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(ts(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(ts(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tl.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof to&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(s=S||(S={})).Local="local",s.Remote="remote",s.UndoRedo="undoredo";class td{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new e9(A.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tu{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tg{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new e9(A.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return[t,e]}indexOf(e){let t;if(!e||e!==this.root&&!e.hasLinks())return -1;let r=0,n=e;for(;n;)t&&t!==n.getRight()||(r+=n.getLength()+(n.hasLeft()?n.getLeftWeight():0)),t=n,n=n.getParent();return r-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tg(e.getLeft());t.root&&t.root.setParent();let r=new tg(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}(a=I||(I={}))[a.Null=0]="Null",a[a.Boolean=1]="Boolean",a[a.Integer=2]="Integer",a[a.Long=3]="Long",a[a.Double=4]="Double",a[a.String=5]="String",a[a.Bytes=6]="Bytes",a[a.Date=7]="Date";class tf extends ta{static of(e,t){return new tf(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return e2.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(e2.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(ts(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tf.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof e2.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tf.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=e2.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tf.getPrimitiveType(e),this.value=void 0===e?null:e}}class tm extends tu{static createAfter(e,t){let r=new tm(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tp{static create(){return new tp}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tm.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new e9(A.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tf.of(0,tn);e.setRemovedAt(tn),this.dummyHead=new tm(e),this.last=this.dummyHead,this.nodeMapByIndex=new tg,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class ty extends to{static create(e,t){if(!t)return new ty(e,tp.create());let r=tp.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new ty(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof to&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:e6(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),h,[a,a]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),a=[],o=this.rgaTreeSplit.findBetween(s,i),h=new Map,c=[];for(let e of o){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tn:ti;if(e.canStyle(r,i)){let r=h.get(t),n=e.getCreatedAt();(!r||n.after(r))&&h.set(t,n),c.push(e)}}let l=[];for(let e of c){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,o]of(a.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:e6(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,o,r);void 0!==t&&l.push({parent:e.getValue(),child:t})}}return[h,l,a]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:e6(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tx(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tk extends td{static create(e,t,r,n,i,s,a){return new tk(e,t,r,n,i,s,a)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tx))throw new e9(A.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class tE extends td{static create(e,t,r,n,i,s){return new tE(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tx))throw new e9(A.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tb="text";function tP(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new e9(A.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new e9(A.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new e9(A.ErrRefused,"Text node cannot have children")}}function tR(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tR(n,t,r+1);t(e,r)}(h=w||(w={})).Start="Start",h.End="End",h.Text="Text";class tN{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new e9(A.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new e9(A.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new e9(A.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let a of t.children){if(r-a.paddedSizea.size;(a.isText||h)&&i([a,a.isText?"Text":"Start"],c),e(a,Math.max(0,t),Math.min(o,a.size),i),c&&i([a,"End"],c)}s+=a.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tR(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new e9(A.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let a of t.children){if(n&&a.isText&&a.size>=r-s)return e(a,r-s,n);if(r===s)break;if(!n&&a.paddedSize===r-s)return{node:t,offset:i+1};if(a.paddedSize>r-s)return e(a,r-s-1,n);s+=a.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new e9(A.ErrInvalidArgument,"invalid treePos");let i=tP(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tP(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new e9(A.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new e9(A.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tM(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tO,this.counter=0}}(c=x||(x={})).Content="content",c.Style="style",c.RemoveStyle="removeStyle";class tB{static of(e,t){return new tB(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tB.of(n.id,tK.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tB.of(tK.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),tK.of(tt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new e9(A.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tK{static of(e,t){return new tK(e,t)}static fromStruct(e){return tK.of(tt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new e9(A.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new e9(A.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tz(tK.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tz(tK.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tC);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tU(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tU)};if(e.attrs){var r;t.attributes=e6(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tJ(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(ts(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tJ(e)).join(""),"")}class tj extends ta{static create(e,t){return new tj(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,a=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=a.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),a=n?n.has(s)?n.get(s):tn:ti;if(i.canStyle(r,a)&&t){let e=l.get(s),n=i.getCreatedAt();(!e||n.after(e))&&l.set(s,n);let a=i.setAttrs(t,r),o=a.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=c[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(o).length>0&&h.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:o}),a))e&&d.push({parent:i,child:e})}}),[l,d,h]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[a,o]=this.findNodesAndSplitText(e[1],r),h=[],c=new Map,l=[];return this.traverseInPosRange(i,s,a,o,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),a=n?n.has(s)?n.get(s):tn:ti;if(i.canStyle(r,a)&&t){let e=c.get(s),n=i.getCreatedAt();for(let a of((!e||n.after(e))&&c.set(s,n),i.attrs||(i.attrs=new tC),t))for(let e of i.attrs.remove(a,r))l.push({parent:i,child:e});let a=i.parent,o=i.prevSibling||i.parent;h.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(a,o),to:this.toIndex(i,i),fromPath:this.toPath(a,o),toPath:this.toPath(i,i),value:t})}}),[c,l,h]}edit(e,t,r,n,i,s){let[a,o]=this.findNodesAndSplitText(e[0],n),[h,c]=this.findNodesAndSplitText(e[1],n),l=this.toIndex(a,o),d=this.toPath(a,o),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(a,o,h,c,(e,t)=>{let[r,i]=e;if(i===w.Start&&!t)for(let e of r.children)f.push(e);let a=r.getCreatedAt().getActorID(),o=s?s.has(a)?s.get(a):tn:ti;if(r.canDelete(n,o)||u.includes(r.parent)){let e=m.get(a),t=r.getCreatedAt();(!e||t.after(e))&&m.set(a,t),(i===w.Text||i===w.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||a.append(e);if(r>0){let e=0,t=a,s=o;for(;e{a.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tU(e));p.length&&p[p.length-1].from===l?p[p.length-1].value=t:p.push({type:"content",from:l,to:l,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),a=this.findPos(e[1]);this.edit([s,a],t,r,n,i)}move(e,t,r){throw new e9(A.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tB.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tJ(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,a;let o,h,c,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:l&&d?e.toTreePos(l,d):null;g&&(o=e.indexTree.indexOf(g),h=e.indexTree.treePosToPath(g),c=tB.fromTreePos(g).toStruct());let f={type:t.type,parent:null==l?void 0:l.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?e6(null===(a=t.attrs)||void 0===a?void 0:a.toObject()):void 0,index:o,path:h,pos:c};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(l,o)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(c,s),toPath:this.toPath(l,o),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===w.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?w.Text:w.Start]:[t,w.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,w.End];let a=i[s+1];return[a,a.isText?w.Text:w.Start]}findLeftToken(e){let[t,r]=e;if(r===w.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?w.Text:w.End]}return[t,w.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,w.Start];let a=i[s-1];return[a,a.isText?w.Text:w.End]}constructor(e,t){super(t),this.indexTree=new tN(e),this.nodeMapByID=new tL(tK.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class tq extends td{static create(e,t,r,n,i,s,a){return new tq(e,t,r,n,i,s,a)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tj))throw new e9(A.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>tt.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:a,toPath:o}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:a,toPath:o}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tJ(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class tF{static of(e,t,r,n){return new tF(e,t,r,n)}next(){return new tF(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new tF(this.clientSeq,e,this.actor):new tF(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new tF(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n){this.clientSeq=e,this.serverSeq=n,this.lamport=t,this.actor=r}}let tV=new tF(0,e2.Z.fromInt(0,!0),te);class tW{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new tW({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:a,reverseOp:o}=s;n.push(...a),o&&i.unshift(o)}return this.presenceChange&&(this.presenceChange.type===T.Put?t.set(this.id.getActorID(),e4(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rD.bytesToHex(rD.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rD.bytesToHex(rD.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return tW.create({id:rD.bytesToChangeID(rD.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rD.bytesToOperation(rD.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class tG{static create(e,t,r,n,i,s){return new tG(e,t,r,n,i,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}constructor(e,t,r,n,i,s){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=i,this.minSyncedTicket=s}}class tH{static of(e,t){return new tH(e,t)}increaseClientSeq(e){return 0===e?this:new tH(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return tH.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let tY=new tH(e2.Z.fromInt(0,!0),0);class tZ{static of(e,t){return new tZ(e,t)}static fromStruct(e){return tZ.of(tt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new tZ(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let tX=tZ.of(tn,0);class tQ{static of(e,t){return new tQ(e,t)}static fromStruct(e){let t=tZ.fromStruct(e.id);return tQ.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return tZ.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class t$ extends tu{static create(e,t){return new t$(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new e9(A.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,a=new Map,o=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),a.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[o,s,a]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[a,o]=this.findEdgesOfCandidates(e);for(let o of(s.push(a),e)){let e=o.getCreatedAt().getActorID(),a=n?r.has(e)?r.get(e):tn:ti;o.canDelete(t,a)?i.push(o):s.push(o)}return s.push(o),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(l=k||(k={}))[l.IntegerCnt=0]="IntegerCnt",l[l.LongCnt=1]="LongCnt";class t2 extends ta{static create(e,t,r){return new t2(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return e2.Z.fromBytesLE(Array.from(t));default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=t2.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof e2.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!t2.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===I.Long?this.value=this.value+e.getValue().toInt():this.value=e2.Z.fromNumber(this.value+t1(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=e2.Z.fromNumber(t).toInt():this.value=t1(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=e2.Z.fromNumber(t):this.value=t;break;default:throw new e9(A.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class t3 extends td{static create(e,t,r){return new t3(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof t2))throw new e9(A.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===I.Long?e.getValue().multiply(-1):-1*e.getValue();return t3.create(this.getParentCreatedAt(),tf.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class t9 extends td{static create(e,t,r,n,i,s){return new t9(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new t9(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new e9(A.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tj))throw new e9(A.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:a}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:a,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,a){super(e,a),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function t4(e){return new $({clientSeq:e.getClientSeq(),lamport:e.getLamportAsString(),actorId:rP(e.getActorID())})}function t5(e){if(e)return new eM({lamport:e.getLamportAsString(),delimiter:e.getDelimiter(),actorId:rP(e.getActorID())})}function t8(e){switch(e){case I.Null:return H.NULL;case I.Boolean:return H.BOOLEAN;case I.Integer:return H.INTEGER;case I.Long:return H.LONG;case I.Double:return H.DOUBLE;case I.String:return H.STRING;case I.Bytes:return H.BYTES;case I.Date:return H.DATE;default:throw new e9(A.ErrInvalidType,"unsupported type: ".concat(e))}}function t6(e){switch(e){case k.IntegerCnt:return H.INTEGER_CNT;case k.LongCnt:return H.LONG_CNT;default:throw new e9(A.ErrInvalidType,"unsupported type: ".concat(e))}}function t7(e){if(e instanceof tl)return new ed({type:H.JSON_OBJECT,createdAt:t5(e.getCreatedAt()),value:rE(e)});if(e instanceof ty)return new ed({type:H.JSON_ARRAY,createdAt:t5(e.getCreatedAt()),value:rs(e).toBinary()});if(e instanceof tx)return new ed({type:H.TEXT,createdAt:t5(e.getCreatedAt())});if(e instanceof tf)return new ed({type:t8(e.getType()),createdAt:t5(e.getCreatedAt()),value:e.toBytes()});if(e instanceof t2)return new ed({type:t6(e.getType()),createdAt:t5(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tj)return new ed({type:H.TREE,createdAt:t5(e.getCreatedAt()),value:ra(e).toBinary()});throw new e9(A.ErrUnimplemented,"unimplemented element")}function re(e){return new eO({createdAt:t5(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rt(e){return new eE({parentId:rr(e.getParentID()),leftSiblingId:rr(e.getLeftSiblingID())})}function rr(e){return new ek({createdAt:t5(e.getCreatedAt()),offset:e.getOffset()})}function rn(e){let t=new ee;if(e instanceof tA){let r=new et;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.key=e.getKey(),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tT){let r=new er;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.prevCreatedAt=t5(e.getPrevCreatedAt()),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tS){let r=new en;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.prevCreatedAt=t5(e.getPrevCreatedAt()),r.createdAt=t5(e.getCreatedAt()),r.executedAt=t5(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tv){let r=new ei;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.createdAt=t5(e.getCreatedAt()),r.executedAt=t5(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tk){let r=new es;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=re(e.getFromPos()),r.to=re(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=t5(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tE){let r=new eo;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=re(e.getFromPos()),r.to=re(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=t5(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof t3){let r=new eh;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.value=t7(e.getValue()),r.executedAt=t5(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tq){let r=new ec,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=rt(e.getFromPos()),r.to=rt(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new ex({content:ri(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=t5(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof t9){let r=new el;r.parentCreatedAt=t5(e.getParentCreatedAt()),r.from=rt(e.getFromPos()),r.to=rt(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=t5(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=t5(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new e9(A.ErrUnimplemented,"unimplemented operation");return t}function ri(e){if(!e)return[];let t=[];return tR(e,(e,r)=>{let n=new ew({id:rr(e.id),type:e.type,removedAt:t5(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rr(e.insPrevID)),e.insNextID&&(n.insNextId=rr(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new eS({value:r.getValue(),updatedAt:t5(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rs(e){let t=new eu;return t.body.case="jsonArray",t.body.value=new ef({nodes:function(e){let t=[];for(let r of e)t.push(new eT({element:ro(r.getValue())}));return t}(e.getElements()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}function ra(e){let t=new eu;return t.body.case="tree",t.body.value=new ev({nodes:ri(e.getRoot()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}function ro(e){if(e instanceof tl)return function(e){let t=new eu;return t.body.case="jsonObject",t.body.value=new eg({nodes:function(e){let t=[];for(let r of e)t.push(new eA({key:r.getStrKey(),element:ro(r.getValue())}));return t}(e.getRHT()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof ty)return rs(e);if(e instanceof tf)return function(e){let t=new eu;return t.body.case="primitive",t.body.value=new em({type:t8(e.getType()),value:e.toBytes(),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof tx)return function(e){let t=new eu;return t.body.case="text",t.body.value=new ep({nodes:function(e){let t=[];for(let n of e){var r;let e=new eI;e.id=new eC({createdAt:t5((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=t5(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new eS;t.value=e.getValue(),t.updatedAt=t5(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof t2)return function(e){let t=new eu;return t.body.case="counter",t.body.value=new ey({type:t6(e.getType()),value:e.toBytes(),createdAt:t5(e.getCreatedAt()),movedAt:t5(e.getMovedAt()),removedAt:t5(e.getRemovedAt())}),t}(e);if(e instanceof tj)return ra(e);throw new e9(A.ErrUnimplemented,"unimplemented element")}function rh(e){for(let t of e.findDetails(e3.Qf))if(t.metadata.code)return t.metadata.code;return""}function rc(e){let t;return e.serverSeq&&(t=e2.Z.fromString(e.serverSeq,!0)),tF.of(e.clientSeq,e2.Z.fromString(e.lamport,!0),rb(e.actorId),t)}function rl(e){if(e)return tt.of(e2.Z.fromString(e.lamport,!0),e.delimiter,rb(e.actorId))}function rd(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function ru(e){switch(e){case H.NULL:return I.Null;case H.BOOLEAN:return I.Boolean;case H.INTEGER:return I.Integer;case H.LONG:return I.Long;case H.DOUBLE:return I.Double;case H.STRING:return I.String;case H.BYTES:return I.Bytes;case H.DATE:return I.Date}throw new e9(A.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rg(e){switch(e){case H.INTEGER_CNT:return k.IntegerCnt;case H.LONG_CNT:return k.LongCnt}throw new e9(A.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rf(e){switch(e.type){case H.JSON_OBJECT:if(!e.value)return tl.create(rl(e.createdAt));return rk(e.value);case H.JSON_ARRAY:if(!e.value)return ty.create(rl(e.createdAt));return function(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rC(eu.fromBinary(e).body.value)}(e.value);case H.TEXT:return tx.create(t0.create(),rl(e.createdAt));case H.TREE:return function(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rw(eu.fromBinary(e).body.value)}(e.value);case H.NULL:case H.BOOLEAN:case H.INTEGER:case H.LONG:case H.DOUBLE:case H.STRING:case H.BYTES:case H.DATE:return tf.of(tf.valueFromBytes(ru(e.type),e.value),rl(e.createdAt));case H.INTEGER_CNT:case H.LONG_CNT:return t2.create(rg(e.type),t2.valueFromBytes(rg(e.type),e.value),rl(e.createdAt))}}function rm(e){return tQ.of(tZ.of(rl(e.createdAt),e.offset),e.relativeOffset)}function rp(e){return tZ.of(rl(e.createdAt),e.offset)}function ry(e){return tB.of(rv(e.parentId),rv(e.leftSiblingId))}function rv(e){return tK.of(rl(e.createdAt),e.offset)}function rA(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rv(e.id),r=tz.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tC.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rl(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rv(e.insPrevId)),e.insNextId&&(r.insNextID=rv(e.insNextId)),r.removedAt=rl(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tj.create(r,tn).getRoot()}function rT(e){if("set"===e.body.case){let t=e.body.value;return tA.create(t.key,rf(t.value),rl(t.parentCreatedAt),rl(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tT.create(rl(t.parentCreatedAt),rl(t.prevCreatedAt),rf(t.value),rl(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tS.create(rl(t.parentCreatedAt),rl(t.prevCreatedAt),rl(t.createdAt),rl(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tv.create(rl(t.parentCreatedAt),rl(t.createdAt),rl(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tk.create(rl(t.parentCreatedAt),rm(t.from),rm(t.to),r,t.content,n,rl(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tE.create(rl(t.parentCreatedAt),rm(t.from),rm(t.to),r,n,rl(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return t3.create(rl(t.parentCreatedAt),rf(t.value),rl(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rl(n))}),tq.create(rl(t.parentCreatedAt),ry(t.from),ry(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rA(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rl(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rl(r))}),(null==n?void 0:n.length)>0)?t9.createTreeRemoveStyleOperation(rl(t.parentCreatedAt),ry(t.from),ry(t.to),i,n,rl(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),t9.create(rl(t.parentCreatedAt),ry(t.from),ry(t.to),i,r,rl(t.executedAt)))}else throw new e9(A.ErrUnimplemented,"unimplemented operation")}function rS(e){let t=[];for(let r of e)t.push(tW.create({id:rc(r.id),operations:function(e){let t=[];for(let r of e){let e=rT(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===eD.PUT){let t=rd(e.presence);return{type:T.Put,presence:t}}if(t===eD.CLEAR)return{type:T.Clear};throw new e9(A.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rI(e){let t=new tc;for(let r of e.nodes){let e=rx(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tl(rl(e.createdAt),t);return r.setMovedAt(rl(e.movedAt)),r.setRemovedAt(rl(e.removedAt)),r}function rC(e){let t=new tp;for(let r of e.nodes)t.insert(rx(r.element));let r=new ty(rl(e.createdAt),t);return r.setMovedAt(rl(e.movedAt)),r.setRemovedAt(rl(e.removedAt)),r}function rw(e){let t=rA(e.nodes);return tj.create(t,rl(e.createdAt))}function rx(e){if("jsonObject"===e.body.case)return rI(e.body.value);if("jsonArray"===e.body.case)return rC(e.body.value);if("primitive"===e.body.case)return function(e){let t=tf.of(tf.valueFromBytes(ru(e.type),e.value),rl(e.createdAt));return t.setMovedAt(rl(e.movedAt)),t.setRemovedAt(rl(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new t0,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tw.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rl(n.updatedAt))});let r=t$.create(rp(e.id),t);return r.remove(rl(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rp(n.insPrevId))),r=e}let n=new tx(t,rl(e.createdAt));return n.setMovedAt(rl(e.movedAt)),n.setRemovedAt(rl(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=t2.create(rg(e.type),t2.valueFromBytes(rg(e.type),e.value),rl(e.createdAt));return t.setMovedAt(rl(e.movedAt)),t.setRemovedAt(rl(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rw(e.body.value);throw new e9(A.ErrUnimplemented,"unimplemented element")}function rk(e){if(!e)throw new e9(A.ErrInvalidArgument,"bytes is empty");return rI(eu.fromBinary(e).body.value)}function rE(e){return ro(e).toBinary()}function rb(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rP(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rD={fromPresence:rd,toChangePack:function(e){var t;return new X({documentKey:e.getDocumentKey(),checkpoint:new eN({serverSeq:(t=e.getCheckpoint()).getServerSeqAsString(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new Q({id:t4(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rn(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===T.Put)return new eP({type:eD.PUT,presence:function(e){let t=new eR,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===T.Clear)return new eP({type:eD.CLEAR});throw new e9(A.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:t5(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return tG.create(e.documentKey,(t=e.checkpoint,tH.of(e2.Z.fromString(t.serverSeq,!0),t.clientSeq)),e.isRemoved,rS(e.changes),e.snapshot,rl(e.minSyncedTicket))},fromChanges:rS,toTreeNodes:ri,fromTreeNodes:rA,objectToBytes:rE,bytesToObject:rk,bytesToSnapshot:function(e){if(!e)return{root:tl.create(tn),presences:new Map};let t=Z.fromBinary(e);return{root:rx(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rd(n))}),t}(t.presences)}},bytesToHex:rb,hexToBytes:rP,toHexString:function(e){return rb(e)},toUint8Array:function(e){return rP(e)},toOperation:rn,toChangeID:t4,PbChangeID:$,bytesToChangeID:function(e){return rc($.fromBinary(e))},bytesToOperation:function(e){return rT(ee.fromBinary(e))}};(d=E||(E={}))[d.Trivial=0]="Trivial",d[d.Debug=1]="Debug",d[d.Info=2]="Info",d[d.Warn=3]="Warn",d[d.Error=4]="Error",d[d.Fatal=5]="Fatal";let rR=3;function rN(e){rR=e}let rO={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrR<=e};function rM(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class r_{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==N.RealtimeSyncOff&&(this.syncMode===N.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==N.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rL=()=>{};class rB{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new e9(A.ErrInvalidArgument,"missing observer");if(this.finalized)throw new e9(A.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rL),void 0===n.error&&(n.error=rL),void 0===n.complete&&(n.complete=rL);let i=rM(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rO.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=e4(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class rz{static create(){return new rz(tl.create(tn))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new e9(A.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof to&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof to&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof to&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new rz(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r);n.element.getRemovedAt()&&e.compare(n.element.getRemovedAt())>=0&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();void 0!==n&&e.compare(n)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tx||e instanceof tj)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function rU(e,t){let r=new rJ(e);return new Proxy(t,r.getHandlers())}class rJ{static setInternal(e,t,r,n){if(r.includes("."))throw new e9(A.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=rX(e,n,i),a=t.set(r,s,i);e.registerElement(s,t),a&&e.registerRemovedElement(a),e.push(tA.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new e9(A.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=rX(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),rJ.setInternal(e,t,r,n),!0),get:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():rZ(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("obj[".concat(r,"]")),rJ.deleteInternal(e,t,r),!0)}}}class rj{static*iteratorInternal(e,t){for(let r of t)yield rY(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=rX(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return rj.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tS.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tS.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tS.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tS.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=rX(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tT.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return rj.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tv.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),a=4;a=0?Math.min(r,o):Math.max(o+r,0),c=void 0===n?o:n<0?h:Math.min(h+n,o),l=[];for(let r=h;r=i)return!1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tf.isSupport(r))return Array.from(t).map(t=>rZ(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var a;if((null===(a=t.get(e))||void 0===a?void 0:a.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return rY(e,n)}:"getElementByIndex"===r?r=>rY(e,t.get(r)):"getLast"===r?()=>rY(e,t.getLast()):"deleteByID"===r?r=>{let n=rj.deleteInternalByID(e,t,r);return rY(e,n)}:"insertAfter"===r?(r,n)=>{let i=rj.insertAfterInternal(e,t,r,n);return rY(e,i)}:"insertBefore"===r?(r,n)=>{let i=rj.insertBeforeInternal(e,t,r,n);return rY(e,i)}:"moveBefore"===r?(r,n)=>{rj.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{rj.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{rj.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{rj.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?rZ(e,t.get(Number(r))):"push"===r?r=>rj.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),a=2;arj.includes(e,t,r,n):"indexOf"===r?(r,n)=>rj.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>rj.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>rj.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;srZ(e,t));return Array.prototype[r].apply(a,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rO.isEnabled(E.Trivial)&&rO.trivial("array[".concat(r,"]")),rj.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class rq{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rO.isEnabled(E.Debug)&&rO.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?e8(n):void 0,a=this.context.issueTimeTicket(),[o,,h,c]=this.text.edit(i,r,a,s);for(let e of h)this.context.registerGCPair(e);return this.context.push(new tk(this.text.getCreatedAt(),i[0],i[1],o,r,s?new Map(Object.entries(s)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rO.isEnabled(E.Debug)&&rO.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=e8(r),s=this.context.issueTimeTicket(),[a,o]=this.text.setStyle(n,i,s);for(let e of o)this.context.registerGCPair(e);return this.context.push(new tE(this.text.getCreatedAt(),n[0],n[1],a,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([tQ.fromStruct(e[0]),tQ.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new e9(A.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class rF{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new e9(A.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tf.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(t3.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new e9(A.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function rV(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tb){rW(e);let{value:r}=e,s=tz.create(tK.of(i,0),n,r);t.append(s)}else{let s;let{children:a=[]}=e,{attributes:o}=e;if("object"==typeof o&&!e5(o)){let e=e8(o);for(let[t,r]of(s=new tC,Object.entries(e)))s.set(t,r,i)}let h=tz.create(tK.of(i,0),n,void 0,s);for(let e of(t.append(h),a))rV(e,h,r)}}function rW(e){if(!e.value.length)throw new e9(A.ErrInvalidArgument,"text node cannot have empty value");return!0}function rG(e){if(!e.length)return!0;if(e[0].type===tb)for(let t of e){let{type:e}=t;if(e!==tb)throw new e9(A.ErrInvalidArgument,"element node and text node cannot be passed together");rW(t)}else for(let t of e){let{type:e}=t;if(e===tb)throw new e9(A.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class rH{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tz.create(tK.of(e.issueTimeTicket(),0),"root");let t=tz.create(tK.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)rV(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?e8(t):void 0,[a]=this.tree.style([r,n],s,i);this.context.push(t9.create(this.tree.getCreatedAt(),r,n,a,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),a=r?e8(r):void 0,[o,h]=this.tree.style([n,i],a,s);for(let e of h)this.context.registerGCPair(e);this.context.push(t9.create(this.tree.getCreatedAt(),n,i,o,a?new Map(Object.entries(a)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[a,o]=this.tree.removeStyle([n,i],r,s);for(let e of o)this.context.registerGCPair(e);this.context.push(t9.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,a,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(rG(r),r[0].type!==tb))for(let e of r){let{children:t=[]}=e;rG(t)}let s=this.context.getLastTimeTicket(),a=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tb){let e="";for(let t of r){let{value:r}=t;e+=r}a.push(tz.create(tK.of(this.context.issueTimeTicket(),0),tb,e))}else a=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tb){let{value:e}=t;r=tz.create(tK.of(i,0),n,e)}else if(t){let s;let{children:a=[]}=t,{attributes:o}=t;if("object"==typeof o&&!e5(o)){let e=e8(o);for(let[t,r]of(s=new tC,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tz.create(tK.of(e.issueTimeTicket(),0),n,void 0,s),a))rV(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,o,h]=this.tree.edit([e,t],a.length?a.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of o)this.context.registerGCPair(e);return this.context.push(tq.create(this.tree.getCreatedAt(),e,t,a.length?a:void 0,i,h,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new e9(A.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new e9(A.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new e9(A.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new e9(A.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[tB.fromStruct(e[0]),tB.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new e9(A.ErrNotInitialized,"Tree is not initialized yet");let t=[tB.fromStruct(e[0]),tB.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function rY(e,t){if(t){if(t instanceof tf)return t;if(t instanceof tl)return rU(e,t);if(t instanceof ty)return function(e,t){let r=new rj(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tx)return new rq(e,t);else if(t instanceof t2){let r=new rF(k.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tj){let r=new rH;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function rZ(e,t){let r=rY(e,t);return r instanceof tf?r.getValue():r}function rX(e,t,r){let n;if(tf.isSupport(t))n=tf.of(t,r);else if(Array.isArray(t))n=ty.create(r,rj.buildArrayElements(e,t));else if("object"==typeof t)t instanceof rq?(n=tx.create(t0.create(),r),t.initialize(e,n)):t instanceof rF?(n=t2.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof rH?(n=tj.create(t.buildRoot(e),r),t.initialize(e,n)):n=tl.create(r,rJ.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class rQ{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let r$="disconnected",r0=new Map,r1=new Map;function r2(e,t){((null==t?void 0:t.force)||"disconnected"!==r$)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=r1,(u=b||(b={})).Detached="detached",u.Attached="attached",u.Removed="removed",(g=P||(P={})).StatusChanged="status-changed",g.ConnectionChanged="connection-changed",g.SyncStatusChanged="sync-status-changed",g.Snapshot="snapshot",g.LocalChange="local-change",g.RemoteChange="remote-change",g.Initialized="initialized",g.Watched="watched",g.Unwatched="unwatched",g.PresenceChanged="presence-changed",g.Broadcast="broadcast",g.LocalBroadcast="local-broadcast",(f=D||(D={})).Connected="connected",f.Disconnected="disconnected",(m=R||(R={})).Synced="synced",m.SyncFailed="sync-failed";class r3{update(e,t){if("removed"===this.getStatus())throw new e9(A.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),rU(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new e7(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rO.isEnabled(E.Trivial)&&rO.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,S.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let a=[];t.length>0&&a.push({type:"local-change",source:S.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&a.push({type:"presence-changed",source:S.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(a),rO.isEnabled(E.Trivial)&&rO.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new e9(A.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new e9(A.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),S.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,S.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),rO.isEnabled(E.Trivial)&&rO.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:e4(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return tG.create(this.key,t,!1,e)}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),rU(rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){let{root:r,presences:n}=rD.bytesToSnapshot(t);this.root=new rz(r),this.presences=n,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:S.Remote,value:{snapshot:this.isEnableDevtools()?rD.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){for(let r of(rO.isEnabled(E.Debug)&&rO.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rO.isEnabled(E.Trivial)&&rO.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rO.isEnabled(E.Debug)&&rO.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case T.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:S.Remote,value:{clientID:n,presence:i.presence}});break;case T.Clear:r.push({type:"unwatched",source:S.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===S.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:S.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===Y.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:S.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===Y.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:S.Remote,value:{clientID:r,presence:e}})}else if(t===Y.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(te),this.publish([{source:"removed"===e?S.Remote:S.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r}=e.value;if(!t)return;this.applySnapshot(e2.Z.fromString(r),rD.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=tW.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new e9(A.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?e4(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?e4(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?e4(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:e4(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:e4(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new e9(A.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new e9(A.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof td)){new e7(t,e4(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,S.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,S.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let a=this.changeID.getActorID(),o=[];n.length>0&&o.push({type:"local-change",source:S.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&o.push({type:"presence-changed",source:S.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(o)}redo(){if(this.isUpdating)throw new e9(A.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new e9(A.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rK.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof td)){new e7(t,e4(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,S.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,S.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let a=this.changeID.getActorID(),o=[];n.length>0&&o.push({type:"local-change",source:S.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&o.push({type:"presence-changed",source:S.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(o)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=rz.create(),this.changeID=tV,this.checkpoint=tY,this.localChanges=[],this.eventStream=function(e){let t=new rB(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new rQ,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||r0.has(e.getKey()))return;r1.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==P.StatusChanged&&e.type!==P.Snapshot&&e.type!==P.LocalChange&&e.type!==P.RemoteChange&&e.type!==P.Initialized&&e.type!==P.Watched&&e.type!==P.Unwatched&&e.type!==P.PresenceChanged)||(r1.get(e.getKey()).push(t),"synced"===r$&&r2({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});r0.set(e.getKey(),[t]),r2({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==r$)break;r$="connected",r2({msg:"doc::available",docKey:e.getKey()}),rO.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":r$="disconnected",rO.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":r$="synced",r2({msg:"doc::sync::full",docKey:e.getKey(),events:r1.get(e.getKey())}),rO.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var r9=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.0"}');let r4=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(p=N||(N={})).Manual="manual",p.Realtime="realtime",p.RealtimePushOnly="realtime-pushonly",p.RealtimeSyncOff="realtime-syncoff",(y=O||(O={})).Deactivated="deactivated",y.Activated="activated",(v=M||(M={})).SyncLoop="SyncLoop",v.WatchLoop="WatchLoop";let r5={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},r8={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class r6{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rO.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rO.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rO.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rO.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==b.Detached)throw new e9(A.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,a=t.options;try{await this.broadcast(e.getKey(),n,i,a)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rD.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let r=rD.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()===b.Removed||(e.applyStatus(b.Attached),this.attachmentMap.set(e.getKey(),new r_(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rO.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'))),e}).catch(e=>{throw rO.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rD.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rD.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==b.Removed&&e.applyStatus(b.Detached),this.detachInternal(e.getKey()),rO.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rO.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rO.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rO.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rD.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rD.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rO.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rO.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new e9(A.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new e9(A.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!r4(r))throw new e9(A.ErrInvalidArgument,"payload is not serializable");let a=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:r8.maxRetries,o=r8.maxBackoff,h=0,c=e=>Math.min(r8.initialRetryInterval*2**e,o),l=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rO.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rO.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(hl(),c(++h-1)),rO.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(h,"/").concat(a));else throw rO.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return l()}runSyncLoop(){let e=()=>{if(!this.isActive()){rO.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rO.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rO.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new e9(A.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new e9(A.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:P.ConnectionChanged,value:D.Connected}]),rO.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:P.Initialized,source:S.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:P.ConnectionChanged,value:D.Disconnected}]),rO.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===Y.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(b.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rD.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rD.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:P.SyncStatusChanged,value:R.Synced}]),r.getStatus()===b.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),a=n.getChangeSize();return rO.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(a," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:P.SyncStatusChanged,value:R.SyncFailed}]),rO.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof J.K&&(e.code===j.E.Canceled||e.code===j.E.Unknown||e.code===j.E.ResourceExhausted||e.code===j.E.Unavailable||((rh(e)===A.ErrClientNotActivated||rh(e)===A.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rO.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||r5,this.key=t.key?t.key:rM(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||r5.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||r5.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||r5.retrySyncLoopDelay,this.rpcClient=(0,q.Hb)(e1,(0,F.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",r9.u2+"/"+r9.i8),await e(t))]})),this.taskQueue=[]}}var r7={Client:r6,Document:r3,Primitive:tf,Text:rq,Counter:rF,Tree:rH,LogLevel:E,setLogLevel:rN,IntType:k.IntegerCnt,LongType:k.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:r6,Document:r3,Primitive:tf,Text:rq,Counter:rF,Tree:rH,LogLevel:E,setLogLevel:rN,IntType:k.IntegerCnt,LongType:k.LongCnt}),r(109);var ne=r(6182);function nt(e){let{content:t,actions:r}=e,[n,i]=(0,K.useState)(new Date),[s,a]=(0,K.useState)("Enter text here!"),o=n?U(new Date(n.toString())):"",h=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===o)return n=!n,0}),n?r.updateContent(o,s):r.addContent(o,s),a("Enter text here!");break;case"DELETE":r.deleteContent(o)}};return(0,_.jsx)("article",{children:(0,_.jsxs)("div",{children:[(0,_.jsx)(ne.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===U(r))?"highlight":""}}),(0,_.jsxs)("p",{children:["selected day : ",o]}),(0,_.jsx)("div",{className:B().memo,children:t.map((e,t)=>{if(e.date===o)return(0,_.jsx)("p",{children:e.text},t)})}),(0,_.jsxs)("div",{className:B().inputForm_editor,children:[(0,_.jsx)("h3",{children:"input form"}),(0,_.jsx)("textarea",{className:B().textArea,value:s,onChange:e=>a(e.target.value)})]}),(0,_.jsx)("button",{className:"button",onClick:()=>h("PUSH"),children:"push"}),(0,_.jsx)("button",{className:"button",onClick:()=>h("DELETE"),children:"pop"})]})})}let nr=[{date:U(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:U(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],nn="next.js-Scheduler-".concat(U(new Date));function ni(){let[e,t]=(0,K.useState)([]),[r,n]=(0,K.useState)(nr),[i]=(0,K.useState)(()=>new r7.Document(nn));return(0,K.useEffect)(()=>{let e=new r7.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==P.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*z.length);return z[e]}()}}),t.update(e=>{e.content||(e.content=nr)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,_.jsxs)("main",{className:B().main,children:[(0,_.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,_.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,_.jsx)(nt,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.html b/examples/nextjs-scheduler/index.html index e3c52968c..beb3f3858 100644 --- a/examples/nextjs-scheduler/index.html +++ b/examples/nextjs-scheduler/index.html @@ -1 +1 @@ -Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 30-09-24

    input form

    \ No newline at end of file +Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 30-09-24

    input form

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.txt b/examples/nextjs-scheduler/index.txt index 2e25cfecb..8cf33d975 100644 --- a/examples/nextjs-scheduler/index.txt +++ b/examples/nextjs-scheduler/index.txt @@ -1,7 +1,7 @@ 2:I[9974,[],""] -3:I[6464,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-c800df1f391ad564.js"],""] +3:I[6464,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-0a8828fab7d2ebab.js"],""] 4:I[4926,[],""] 5:I[4582,[],""] -0:["kQt9G5eCknYR1Jo9JAzZb",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] +0:["BrIaRMbmS6x-HiSUkVY_9",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"Next.js react-calendar example"}],["$","meta","3",{"name":"description","content":"example of yorkie-js-sdk with next.js & react-calendar"}],["$","link","4",{"rel":"icon","href":"/yorkie-js-sdk/examples/nextjs-scheduler/favicon.ico","type":"image/x-icon","sizes":"64x64"}]] 1:null diff --git a/examples/profile-stack/assets/index-C62PBOd3.js b/examples/profile-stack/assets/index-hw_3d2tm.js similarity index 53% rename from examples/profile-stack/assets/index-C62PBOd3.js rename to examples/profile-stack/assets/index-hw_3d2tm.js index 7388346d1..68e67117b 100644 --- a/examples/profile-stack/assets/index-C62PBOd3.js +++ b/examples/profile-stack/assets/index-hw_3d2tm.js @@ -19,7 +19,7 @@ var bi=Object.defineProperty;var Ai=(r,e,t)=>e in r?bi(r,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var ce=null;try{ce=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function N(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}N.prototype.__isLong__;Object.defineProperty(N.prototype,"__isLong__",{value:!0});function Y(r){return(r&&r.__isLong__)===!0}function Pr(r){var e=Math.clz32(r&-r);return r?31-e:e}N.isLong=Y;var Dr={},Rr={};function at(r,e){var t,n,s;return e?(r>>>=0,(s=0<=r&&r<256)&&(n=Rr[r],n)?n:(t=D(r,0,!0),s&&(Rr[r]=t),t)):(r|=0,(s=-128<=r&&r<128)&&(n=Dr[r],n)?n:(t=D(r,r<0?-1:0,!1),s&&(Dr[r]=t),t))}N.fromInt=at;function ue(r,e){if(isNaN(r))return e?Le:ge;if(e){if(r<0)return Le;if(r>=_s)return zs}else{if(r<=-Mr)return te;if(r+1>=Mr)return Js}return r<0?ue(-r,e).neg():D(r%vt|0,r/vt|0,e)}N.fromNumber=ue;function D(r,e,t){return new N(r,e,t)}N.fromBits=D;var cn=Math.pow;function jn(r,e,t){if(r.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return e?Le:ge;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return jn(r.substring(1),e,t).neg();for(var s=ue(cn(t,8)),i=ge,o=0;o>>0:this.low};w.toNumber=function(){return this.unsigned?(this.high>>>0)*vt+(this.low>>>0):this.high*vt+(this.low>>>0)};w.toString=function(e){if(e=e||10,e<2||36>>0,h=u.toString(e);if(o=c,o.isZero())return h+a;for(;h.length<6;)h="0"+h;a=""+h+a}};w.getHighBits=function(){return this.high};w.getHighBitsUnsigned=function(){return this.high>>>0};w.getLowBits=function(){return this.low};w.getLowBitsUnsigned=function(){return this.low>>>0};w.getNumBitsAbs=function(){if(this.isNegative())return this.eq(te)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};w.isOdd=function(){return(this.low&1)===1};w.isEven=function(){return(this.low&1)===0};w.equals=function(e){return Y(e)||(e=Te(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};w.eq=w.equals;w.notEquals=function(e){return!this.eq(e)};w.neq=w.notEquals;w.ne=w.notEquals;w.lessThan=function(e){return this.comp(e)<0};w.lt=w.lessThan;w.lessThanOrEqual=function(e){return this.comp(e)<=0};w.lte=w.lessThanOrEqual;w.le=w.lessThanOrEqual;w.greaterThan=function(e){return this.comp(e)>0};w.gt=w.greaterThan;w.greaterThanOrEqual=function(e){return this.comp(e)>=0};w.gte=w.greaterThanOrEqual;w.ge=w.greaterThanOrEqual;w.compare=function(e){if(Y(e)||(e=Te(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};w.comp=w.compare;w.negate=function(){return!this.unsigned&&this.eq(te)?te:this.not().add(lt)};w.neg=w.negate;w.add=function(e){Y(e)||(e=Te(e));var t=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,c=e.low>>>16,u=e.low&65535,h=0,p=0,v=0,m=0;return m+=i+u,v+=m>>>16,m&=65535,v+=s+c,p+=v>>>16,v&=65535,p+=n+a,h+=p>>>16,p&=65535,h+=t+o,h&=65535,D(v<<16|m,h<<16|p,this.unsigned)};w.subtract=function(e){return Y(e)||(e=Te(e)),this.add(e.neg())};w.sub=w.subtract;w.multiply=function(e){if(this.isZero())return this;if(Y(e)||(e=Te(e)),ce){var t=ce.mul(this.low,this.high,e.low,e.high);return D(t,ce.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Le:ge;if(this.eq(te))return e.isOdd()?te:ge;if(e.eq(te))return this.isOdd()?te:ge;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Fr)&&e.lt(Fr))return ue(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,c=e.high&65535,u=e.low>>>16,h=e.low&65535,p=0,v=0,m=0,T=0;return T+=o*h,m+=T>>>16,T&=65535,m+=i*h,v+=m>>>16,m&=65535,m+=o*u,v+=m>>>16,m&=65535,v+=s*h,p+=v>>>16,v&=65535,v+=i*u,p+=v>>>16,v&=65535,v+=o*c,p+=v>>>16,v&=65535,p+=n*h+s*u+i*c+o*a,p&=65535,D(m<<16|T,p<<16|v,this.unsigned)};w.mul=w.multiply;w.divide=function(e){if(Y(e)||(e=Te(e)),e.isZero())throw Error("division by zero");if(ce){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?ce.div_u:ce.div_s)(this.low,this.high,e.low,e.high);return D(t,ce.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Le:ge;var n,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Le;if(e.gt(this.shru(1)))return Us;i=Le}else{if(this.eq(te)){if(e.eq(lt)||e.eq(Mn))return te;if(e.eq(te))return lt;var o=this.shr(1);return n=o.div(e).shl(1),n.eq(ge)?e.isNegative()?lt:Mn:(s=this.sub(e.mul(n)),i=n.add(s.div(e)),i)}else if(e.eq(te))return this.unsigned?Le:ge;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=ge}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),c=a<=48?1:cn(2,a-48),u=ue(n),h=u.mul(e);h.isNegative()||h.gt(s);)n-=c,u=ue(n,this.unsigned),h=u.mul(e);u.isZero()&&(u=lt),i=i.add(u),s=s.sub(h)}return i};w.div=w.divide;w.modulo=function(e){if(Y(e)||(e=Te(e)),ce){var t=(this.unsigned?ce.rem_u:ce.rem_s)(this.low,this.high,e.low,e.high);return D(t,ce.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};w.mod=w.modulo;w.rem=w.modulo;w.not=function(){return D(~this.low,~this.high,this.unsigned)};w.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};w.clz=w.countLeadingZeros;w.countTrailingZeros=function(){return this.low?Pr(this.low):Pr(this.high)+32};w.ctz=w.countTrailingZeros;w.and=function(e){return Y(e)||(e=Te(e)),D(this.low&e.low,this.high&e.high,this.unsigned)};w.or=function(e){return Y(e)||(e=Te(e)),D(this.low|e.low,this.high|e.high,this.unsigned)};w.xor=function(e){return Y(e)||(e=Te(e)),D(this.low^e.low,this.high^e.high,this.unsigned)};w.shiftLeft=function(e){return Y(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?D(this.low<>>32-e,this.unsigned):D(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):D(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};w.shr=w.shiftRight;w.shiftRightUnsigned=function(e){return Y(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?D(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?D(this.high,0,this.unsigned):D(this.high>>>e-32,0,this.unsigned)};w.shru=w.shiftRightUnsigned;w.shr_u=w.shiftRightUnsigned;w.rotateLeft=function(e){var t;return Y(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?D(this.high,this.low,this.unsigned):e<32?(t=32-e,D(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,D(this.high<>>t,this.low<>>t,this.unsigned))};w.rotl=w.rotateLeft;w.rotateRight=function(e){var t;return Y(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?D(this.high,this.low,this.unsigned):e<32?(t=32-e,D(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,D(this.low<>>e,this.high<>>e,this.unsigned))};w.rotr=w.rotateRight;w.toSigned=function(){return this.unsigned?D(this.low,this.high,!1):this};w.toUnsigned=function(){return this.unsigned?this:D(this.low,this.high,!0)};w.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};w.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};w.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};N.fromBytes=function(e,t,n){return n?N.fromBytesLE(e,t):N.fromBytesBE(e,t)};N.fromBytesLE=function(e,t){return new N(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};N.fromBytesBE=function(e,t){return new N(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const ma=d.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);d.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:Me}]);d.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);d.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:pa,repeated:!0}]);const pa=d.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});d.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:ya,repeated:!0}]);const ya=d.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});d.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:va,repeated:!0}]);const va=d.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});d.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);d.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);d.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:Ta,repeated:!0}]);const Ta=d.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});d.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var f=(r=>(r.Ok="ok",r.ErrClientNotActivated="ErrClientNotActivated",r.ErrClientNotFound="ErrClientNotFound",r.ErrUnimplemented="ErrUnimplemented",r.ErrInvalidType="ErrInvalidType",r.ErrDummy="ErrDummy",r.ErrDocumentNotAttached="ErrDocumentNotAttached",r.ErrDocumentNotDetached="ErrDocumentNotDetached",r.ErrDocumentRemoved="ErrDocumentRemoved",r.ErrInvalidObjectKey="ErrInvalidObjectKey",r.ErrInvalidArgument="ErrInvalidArgument",r.ErrNotInitialized="ErrNotInitialized",r.ErrNotReady="ErrNotReady",r.ErrRefused="ErrRefused",r.ErrContextNotProvided="ErrContextNotProvided",r))(f||{});class g extends Error{constructor(t,n){super(n);l(this,"name","YorkieError");l(this,"stack");this.code=t,this.message=n,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function de(r){if(r instanceof Map){const e=Array.from(r);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(r))}const qs=r=>r?Object.entries(r).length===0:!0,Tt=r=>{const e={};for(const[t,n]of Object.entries(r))e[t]=JSON.stringify(n);return e},gt=r=>{const e={};for(const[t,n]of Object.entries(r))e[t]=JSON.parse(n);return e};var Xe=(r=>(r.Put="put",r.Clear="clear",r))(Xe||{});class kn{constructor(e,t){l(this,"context");l(this,"presence");this.context=e,this.presence=t}set(e,t){for(const n of Object.keys(e))this.presence[n]=e[n];this.context.setPresenceChange({type:"put",presence:de(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const mn="000000000000000000000000",wa="FFFFFFFFFFFFFFFFFFFFFFFF";class ne{constructor(e,t,n){l(this,"lamport");l(this,"delimiter");l(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=n}static of(e,t,n){return new ne(e,t,n)}static fromStruct(e){return ne.of(N.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new ne(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Wn=0,ba=4294967295,Aa=N.MAX_VALUE,pe=new ne(N.fromNumber(0),Wn,mn);new ne(N.fromNumber(1),Wn+1,mn);const Ct=new ne(Aa,ba,wa);function Oe(r){return r.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class Ut{constructor(e){l(this,"createdAt");l(this,"movedAt");l(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ge extends Ut{constructor(e){super(e)}}class Gn{constructor(e,t){l(this,"strKey");l(this,"value");this.strKey=e,this.value=t}static of(e,t){return new Gn(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Bt{constructor(){l(this,"nodeMapByKey");l(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Bt}set(e,t,n){let s;const i=this.nodeMapByKey.get(e);i!=null&&!i.isRemoved()&&i.remove(n)&&(s=i.getValue());const o=Gn.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(i==null||n.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(n)),s}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new g(f.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new g(f.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class re extends Ge{constructor(t,n){super(t);l(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new re(t,Bt.create());const s=Bt.create();for(const[i,o]of Object.entries(n))s.set(i,o.deepcopy(),o.getCreatedAt());return new re(t,s)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,s){return this.memberNodes.set(t,n,s)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,s]of this)t.push(`"${Oe(n)}":${s.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,s]of this){const{createdAt:i,value:o,type:a}=s.toJSForTest();t[n]={key:n,createdAt:i,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var s;const t=Array();for(const[i]of this)t.push(i);const n=[];for(const i of t.sort()){const o=(s=this.memberNodes.get(i))==null?void 0:s.getValue();n.push(`"${Oe(i)}":${o.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=re.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const s=n.getValue();if(t(s,this))return;s instanceof Ge&&s.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var M=(r=>(r.Local="local",r.Remote="remote",r.UndoRedo="undoredo",r))(M||{});class ve{constructor(e,t){l(this,"parentCreatedAt");l(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new g(f.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Vs{constructor(e){l(this,"value");l(this,"left");l(this,"right");l(this,"parent");l(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Mt{constructor(e){l(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new g(f.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return[t,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let t=0,n=e,s;for(;n;)(!s||s===n.getRight())&&(t+=n.getLength()+(n.hasLeft()?n.getLeftWeight():0)),s=n,n=n.getParent();return t-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Mt(e.getLeft());t.root&&t.root.setParent();const n=new Mt(e.getRight());if(n.root&&n.root.setParent(),t.root){const s=t.getRightmost();t.splayNode(s),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var K=(r=>(r[r.Null=0]="Null",r[r.Boolean=1]="Boolean",r[r.Integer=2]="Integer",r[r.Long=3]="Long",r[r.Double=4]="Double",r[r.String=5]="String",r[r.Bytes=6]="Bytes",r[r.Date=7]="Date",r))(K||{});class L extends Ut{constructor(t,n){super(n);l(this,"valueType");l(this,"value");this.valueType=L.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new L(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const s=new DataView(n.buffer);return n.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return N.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(N.fromBytesLE(Array.from(n),!0).toNumber());default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${Oe(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=L.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof N)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return L.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=N.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new g(f.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class un extends Vs{constructor(t){super(t);l(this,"prev");l(this,"next");this.value=t}static createAfter(t,n){const s=new un(n),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Ft{constructor(){l(this,"dummyHead");l(this,"last");l(this,"nodeMapByIndex");l(this,"nodeMapByCreatedAt");const e=L.of(0,pe);e.setRemovedAt(pe),this.dummyHead=new un(e),this.last=this.dummyHead,this.nodeMapByIndex=new Mt,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ft}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new g(f.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,n),i=un.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,n){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new g(f.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new g(f.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||n.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),n),i.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new g(f.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||n>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),s=n.isRemoved();return n.remove(t)&&!s&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class oe extends Ge{constructor(t,n){super(t);l(this,"elements");this.elements=n}static create(t,n){if(!n)return new oe(t,Ft.create());const s=Ft.create();for(const i of n)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new oe(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,s){this.elements.moveAfter(t,n,s)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const s=n.getValue();if(t(s,this))return;s instanceof Ge&&s.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...m,value:m.value?{attributes:gt(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,v,h,[c,c]]}setStyle(t,n,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),c=[],u=this.rgaTreeSplit.findBetween(a,o),h=new Map,p=[];for(const m of u){const T=m.getCreatedAt().getActorID(),S=i!=null&&i.size?i.has(T)?i.get(T):pe:Ct;if(m.canStyle(s,S)){const E=h.get(T),x=m.getCreatedAt();(!E||x.after(E))&&h.set(T,x),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[T,S]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());c.push({type:"style",actor:s.getActorID(),from:T,to:S,value:{attributes:gt(n)}});for(const[E,x]of Object.entries(n)){const[O]=m.getValue().setAttr(E,x,s);O!==void 0&&v.push({parent:m.getValue(),child:O})}}return[h,v,c]}indexRangeToPosRange(t,n){const s=this.rgaTreeSplit.indexToPos(t);return t===n?[s,s]:[s,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const s=n.getValue();t.push({attributes:gt(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new he(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const s of n.getValue().getGCPairs())t.push(s)}return t}}class zt extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"content");l(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,n,s,i,o,a,c){return new zt(t,n,s,i,o,a,c)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof he))throw new g(f.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:u})=>({type:"edit",from:a,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${n},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class qt extends ve{constructor(t,n,s,i,o,a){super(t,a);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,n,s,i,o,a){return new qt(t,n,s,i,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof he))throw new g(f.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:c,value:u})=>({type:"style",from:a,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${n},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Ia=2,Sa="root",$e="text";function St(r,e){let t=0;const n=r.children;for(let s=0;s0)throw new g(f.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===$e}get paddedSize(){return this.size+(this.isText?0:Ia)}isAncestorOf(e){return Ea(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=n;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new g(f.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,n._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function Ea(r,e){if(r===e)return!1;for(;e.parent;){if(e.parent===r)return!0;e=e.parent}return!1}var z=(r=>(r.Start="Start",r.End="End",r.Text="Text",r))(z||{});function Ks(r,e,t,n){if(e>t)throw new g(f.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>r.size)throw new g(f.ErrInvalidArgument,`from is out of range: ${e} > ${r.size}`);if(t>r.size)throw new g(f.ErrInvalidArgument,`to is out of range: ${t} > ${r.size}`);if(e===t)return;let s=0;for(const i of r.children){if(e-i.paddedSizei.size;(i.isText||c)&&n([i,i.isText?"Text":"Start"],u),Ks(i,Math.max(0,o),Math.min(a,i.size),n),u&&n([i,"End"],u)}s+=i.paddedSize}}function js(r,e,t=0){for(const n of r.children)js(n,e,t+1);e(r,t)}function pn(r,e,t=0){for(const n of r._children)pn(n,e,t+1);e(r,t)}function Fn(r,e,t=!0){if(e>r.size)throw new g(f.ErrInvalidArgument,`index is out of range: ${e} > ${r.size}`);if(r.isText)return{node:r,offset:e};let n=0,s=0;for(const i of r.children){if(t&&i.isText&&i.size>=e-s)return Fn(i,e-s,t);if(e===s)return{node:r,offset:n};if(!t&&i.paddedSize===e-s)return{node:r,offset:n+1};if(i.paddedSize>e-s)return Fn(i,e-s-1,t);s+=i.paddedSize,n+=1}return{node:r,offset:n}}function Ws(r){return r.isText||r.children.length===0?r:Ws(r.children[0])}function Na(r,e){if(r.sizer===e?0:r0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new Oa(e,t,!0);const s=this.comparator(e,n.key);return s<0?n.left=this.putInternal(e,t,n.left):s>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class me{constructor(e,t){l(this,"parentID");l(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new me(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,s;return n.isText?(n.parent.children[0]===n&&t===0?s=n.parent:s=n,n=n.parent):t===0?s=n:s=n.children[t-1],me.of(n.id,G.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return me.of(G.of(ne.fromStruct(e.parentID.createdAt),e.parentID.offset),G.of(ne.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(n);if(!s||!i)throw new g(f.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class G{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new G(e,t)}static fromStruct(e){return G.of(ne.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new g(f.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new g(f.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ie(G.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ie(G.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,s){const i=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new Ue);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,n));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function Ln(r){var t;if(r.isText){const n=r;return{type:n.type,value:n.value}}const e={type:r.type,children:r.children.map(Ln)};return r.attrs&&(e.attributes=gt((t=r.attrs)==null?void 0:t.toObject())),e}function Hn(r){if(r.isText)return r.value;let e="";return r.attrs&&r.attrs.size()&&(e=" "+Array.from(r.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${Oe(t.getValue())}"`}).join(" ")),`<${r.type}${e}>${r.children.map(t=>Hn(t)).join("")}`}function Hs(r){if(r.isText){const e=r;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:r.type,children:r.children.map(Hs),size:r.size,isRemoved:r.isRemoved}}class le extends Ut{constructor(t,n){super(n);l(this,"indexTree");l(this,"nodeMapByID");this.indexTree=new Ca(t),this.nodeMapByID=new Gs(G.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,n){return new le(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,c=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const u=c.allChildren,h=a?0:u.indexOf(o)+1;for(let p=h;p{const S=T.getCreatedAt().getActorID(),E=i?i.has(S)?i.get(S):pe:Ct;if(T.canStyle(s,E)&&n){const x=v.get(S),O=T.getCreatedAt();(!x||O.after(x))&&v.set(S,O);const W=T.setAttrs(n,s),P=W.reduce((J,[,ze])=>(ze&&(J[ze.getKey()]=p[ze.getKey()]),J),{}),B=T.parent,F=T.prevSibling||T.parent;Object.keys(P).length>0&&h.push({type:"style",from:this.toIndex(B,F),to:this.toIndex(T,T),fromPath:this.toPath(B,F),toPath:this.toPath(T,T),actor:s.getActorID(),value:P});for(const[J]of W)J&&m.push({parent:T,child:J})}}),[v,m,h]}removeStyle(t,n,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),h=[],p=new Map,v=[];return this.traverseInPosRange(o,a,c,u,([m])=>{const T=m.getCreatedAt().getActorID(),S=i?i.has(T)?i.get(T):pe:Ct;if(m.canStyle(s,S)&&n){const E=p.get(T),x=m.getCreatedAt();(!E||x.after(E))&&p.set(T,x),m.attrs||(m.attrs=new Ue);for(const P of n){const B=m.attrs.remove(P,s);for(const F of B)v.push({parent:m,child:F})}const O=m.parent,W=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(O,W),to:this.toIndex(m,m),fromPath:this.toPath(O,W),toPath:this.toPath(m,m),value:n})}}),[p,v,h]}edit(t,n,s,i,o,a){const[c,u]=this.findNodesAndSplitText(t[0],i),[h,p]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(c,u),m=this.toPath(c,u),T=[],S=[],E=[],x=new Map;this.traverseInPosRange(c,u,h,p,([P,B],F)=>{if(B===z.Start&&!F)for(const Qe of P.children)E.push(Qe);const J=P.getCreatedAt().getActorID(),ze=a?a.has(J)?a.get(J):pe:Ct;if(P.canDelete(i,ze)||T.includes(P.parent)){const Qe=x.get(J),Kt=P.getCreatedAt();(!Qe||Kt.after(Qe))&&x.set(J,Kt),(B===z.Text||B===z.Start)&&T.push(P),S.push([P,B])}});const O=this.makeDeletionChanges(S,i),W=[];for(const P of T)P.remove(i),P.isRemoved&&W.push({parent:this,child:P});for(const P of E)P.removedAt||c.append(P);if(s>0){let P=0,B=c,F=u;for(;P{c.isRemoved&&(J.remove(i),W.push({parent:this,child:J})),this.nodeMapByID.put(J.id,J)}),F.isRemoved||P.push(F);if(P.length){const F=P.map(J=>Ln(J));O.length&&O[O.length-1].from===v?O[O.length-1].value=F:O.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[O,W,x]}editT(t,n,s,i,o){const a=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([a,c],n,s,i,o)}move(t,n,s){throw new g(f.ErrUnimplemented,`not implemented: ${t}, ${n}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,s=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const s of n.getGCPairs())t.push(s)}),t}findPos(t,n=!0){const s=this.indexTree.findTreePos(t,n);return me.fromTreePos(s)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Hn(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(s,i=void 0,o=void 0,a=0)=>{var m,T,S,E;let c,u,h;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(c=this.indexTree.indexOf(p),u=this.indexTree.treePosToPath(p),h=me.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(T=s.insPrevID)==null?void 0:T.toTestString(),insNext:(S=s.insNextID)==null?void 0:S.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?gt((E=s.attrs)==null?void 0:E.toObject()):void 0,index:c,path:u,pos:h};for(let x=0;x0&&x===s[s.length-1].to?(s[s.length-1].to=O,s[s.length-1].toPath=this.toPath(E,m)):s.push({type:"content",from:x,to:O,fromPath:this.toPath(S,p),toPath:this.toPath(E,m),actor:n.getActorID()}))}return s.reverse()}findRightToken([t,n]){if(n===z.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?z.Text:z.Start]:[t,z.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,z.End];const a=i[o+1];return[a,a.isText?z.Text:z.Start]}findLeftToken([t,n]){if(n===z.End){const c=t.allChildren;if(c.length>0){const u=c[c.length-1];return[u,u.isText?z.Text:z.End]}return[t,z.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,z.Start];const a=i[o-1];return[a,a.isText?z.Text:z.End]}}class Vt extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"contents");l(this,"splitLevel");l(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,s,i,o,a,c){return new Vt(t,n,s,i,o,a,c)}execute(t){var c;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof le))throw new g(f.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=n,[o,a]=i.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(u=>u.deepcopy()),this.splitLevel,s,(()=>{let u=s.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>ne.of(s.getLamport(),++u,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:h,value:p,splitLevel:v,fromPath:m,toPath:T})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:u,to:h,value:p,splitLevel:v,fromPath:m,toPath:T}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${n},${s},${i.map(o=>Hn(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class je{constructor(e,t,n,s){l(this,"clientSeq");l(this,"serverSeq");l(this,"lamport");l(this,"actor");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.actor=n}static of(e,t,n,s){return new je(e,t,n,s)}next(){return new je(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new je(this.clientSeq,e,this.actor):new je(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return ne.of(this.lamport,e,this.actor)}setActor(e){return new je(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Da=new je(0,N.fromInt(0,!0),mn);class wt{constructor({id:e,operations:t,presenceChange:n,message:s}){l(this,"id");l(this,"operations");l(this,"presenceChange");l(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=s}static create({id:e,operations:t,presenceChange:n,message:s}){return new wt({id:e,operations:t,presenceChange:n,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:c,reverseOp:u}=a;s.push(...c),u&&i.unshift(u)}return this.presenceChange&&(this.presenceChange.type===Xe.Put?t.set(this.id.getActorID(),de(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:j.bytesToHex(j.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>j.bytesToHex(j.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:s,message:i}=e;return wt.create({id:j.bytesToChangeID(j.hexToBytes(t)),operations:n==null?void 0:n.map(o=>j.bytesToOperation(j.hexToBytes(o))),presenceChange:s,message:i})}}class yn{constructor(e,t,n,s,i,o){l(this,"documentKey");l(this,"checkpoint");l(this,"isRemoved");l(this,"changes");l(this,"snapshot");l(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(e,t,n,s,i,o){return new yn(e,t,n,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class mt{constructor(e,t){l(this,"serverSeq");l(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new mt(e,t)}increaseClientSeq(e){return e===0?this:new mt(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return mt.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Ra=new mt(N.fromInt(0,!0),0);class Pe{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Pe(e,t)}static fromStruct(e){return Pe.of(ne.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Pe(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Ba=Pe.of(pe,0);class ye{constructor(e,t){l(this,"id");l(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new ye(e,t)}static fromStruct(e){const t=Pe.fromStruct(e.id);return ye.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Pe.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class He extends Vs{constructor(t,n,s){super(n);l(this,"id");l(this,"removedAt");l(this,"prev");l(this,"next");l(this,"insPrev");l(this,"insNext");this.id=t,this.removedAt=s}static create(t,n){return new He(t,n)}static createComparator(){return(t,n)=>{const s=t.getCreatedAt().compare(n.getCreatedAt());return s!==0?s:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let s=e;for(;s&&s!==t;)n.push(s),s=s.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new g(f.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const s=e.getInsNext();return s&&s.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,n),o=new Map,a=new Map,c=this.makeChanges(i,t);for(const u of s){const h=u.getCreatedAt().getActorID();(!o.has(h)||u.getID().getCreatedAt().after(o.get(h)))&&o.set(h,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(t)}return this.deleteIndexNodes(i),[c,o,a]}filterNodes(e,t,n){const s=!!n,i=[],o=[],[a,c]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const h=u.getCreatedAt().getActorID(),p=s?n.has(h)?n.get(h):pe:Ct;u.canDelete(t,p)?i.push(u):o.push(u)}return o.push(c),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let s,i;for(let o=0;or<0?Math.ceil(r):Math.floor(r);var De=(r=>(r[r.IntegerCnt=0]="IntegerCnt",r[r.LongCnt=1]="LongCnt",r))(De||{});class ae extends Ut{constructor(t,n,s){super(s);l(this,"valueType");l(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=N.fromNumber(n).toInt():this.value=Lr(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=N.fromNumber(n):this.value=n;break;default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,s){return new ae(t,n,s)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return N.fromBytesLE(Array.from(n));default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=ae.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof N?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!ae.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new g(f.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===K.Long?this.value=this.value+t.getValue().toInt():this.value=N.fromNumber(this.value+Lr(t.getValue())).toInt(),this}}class At extends ve{constructor(t,n,s){super(t,s);l(this,"value");this.value=n}static create(t,n,s){return new At(t,n,s)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ae))throw new g(f.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=n,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===K.Long?t.getValue().multiply(-1):t.getValue()*-1;return At.create(this.getParentCreatedAt(),L.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class _e extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");l(this,"attributesToRemove");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,n,s,i,o,a){return new _e(t,n,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,s,i,o,a){return new _e(t,n,s,i,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof le))throw new g(f.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=n;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([c,u])=>a[c]=u),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:u,fromPath:h,toPath:p})=>({type:"tree-style",from:a,to:c,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:h,toPath:p,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Ma(r){const e=new Kn,t=e.data;for(const[n,s]of Object.entries(r))t[n]=JSON.stringify(s);return e}function Fa(r){if(r.type===Xe.Put)return new Bn({type:Rt.PUT,presence:Ma(r.presence)});if(r.type===Xe.Clear)return new Bn({type:Rt.CLEAR});throw new g(f.ErrUnimplemented,"unimplemented type")}function La(r){return new $s({serverSeq:r.getServerSeqAsString(),clientSeq:r.getClientSeq()})}function Ys(r){return new dn({clientSeq:r.getClientSeq(),lamport:r.getLamportAsString(),actorId:nr(r.getActorID())})}function b(r){if(r)return new I({lamport:r.getLamportAsString(),delimiter:r.getDelimiter(),actorId:nr(r.getActorID())})}function Xs(r){switch(r){case K.Null:return C.NULL;case K.Boolean:return C.BOOLEAN;case K.Integer:return C.INTEGER;case K.Long:return C.LONG;case K.Double:return C.DOUBLE;case K.String:return C.STRING;case K.Bytes:return C.BYTES;case K.Date:return C.DATE;default:throw new g(f.ErrInvalidType,`unsupported type: ${r}`)}}function Zs(r){switch(r){case De.IntegerCnt:return C.INTEGER_CNT;case De.LongCnt:return C.LONG_CNT;default:throw new g(f.ErrInvalidType,`unsupported type: ${r}`)}}function En(r){if(r instanceof re)return new Re({type:C.JSON_OBJECT,createdAt:b(r.getCreatedAt()),value:li(r)});if(r instanceof oe)return new Re({type:C.JSON_ARRAY,createdAt:b(r.getCreatedAt()),value:fc(r)});if(r instanceof he)return new Re({type:C.TEXT,createdAt:b(r.getCreatedAt())});if(r instanceof L)return new Re({type:Xs(r.getType()),createdAt:b(r.getCreatedAt()),value:r.toBytes()});if(r instanceof ae)return new Re({type:Zs(r.getType()),createdAt:b(r.getCreatedAt()),value:r.toBytes()});if(r instanceof le)return new Re({type:C.TREE,createdAt:b(r.getCreatedAt()),value:gc(r)});throw new g(f.ErrUnimplemented,"unimplemented element")}function $a(r){return new Rn({createdAt:b(r.getCreatedAt()),offset:r.getOffset()})}function Wt(r){return new it({createdAt:b(r.getID().getCreatedAt()),offset:r.getID().getOffset(),relativeOffset:r.getRelativeOffset()})}function Gt(r){return new Dt({parentId:xt(r.getParentID()),leftSiblingId:xt(r.getLeftSiblingID())})}function xt(r){return new dt({createdAt:b(r.getCreatedAt()),offset:r.getOffset()})}function Qs(r){const e=new zn;if(r instanceof ot){const t=r,n=new ws;n.parentCreatedAt=b(t.getParentCreatedAt()),n.key=t.getKey(),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(r instanceof Jt){const t=r,n=new bs;n.parentCreatedAt=b(t.getParentCreatedAt()),n.prevCreatedAt=b(t.getPrevCreatedAt()),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(r instanceof We){const t=r,n=new As;n.parentCreatedAt=b(t.getParentCreatedAt()),n.prevCreatedAt=b(t.getPrevCreatedAt()),n.createdAt=b(t.getCreatedAt()),n.executedAt=b(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(r instanceof Ze){const t=r,n=new Is;n.parentCreatedAt=b(t.getParentCreatedAt()),n.createdAt=b(t.getCreatedAt()),n.executedAt=b(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(r instanceof zt){const t=r,n=new Ss;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Wt(t.getFromPos()),n.to=Wt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);n.content=t.getContent();const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=b(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(r instanceof qt){const t=r,n=new ks;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Wt(t.getFromPos()),n.to=Wt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=b(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(r instanceof At){const t=r,n=new Es;n.parentCreatedAt=b(t.getParentCreatedAt()),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(r instanceof Vt){const t=r,n=new Ns,s=n.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=b(o);n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Gt(t.getFromPos()),n.to=Gt(t.getToPos()),n.contents=Ka(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=b(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(r instanceof _e){const t=r,n=new Cs;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Gt(t.getFromPos()),n.to=Gt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);const i=t.getAttributesToRemove();if(i.length>0)n.attributesToRemove=i;else{const o=n.attributes;for(const[a,c]of t.getAttributes())o[a]=c}n.executedAt=b(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new g(f.ErrUnimplemented,"unimplemented operation");return e}function _a(r){const e=[];for(const t of r)e.push(Qs(t));return e}function Ua(r){const e=new Ts({id:Ys(r.getID()),message:r.getMessage()});return r.hasOperations()&&(e.operations=_a(r.getOperations())),r.hasPresenceChange()&&(e.presenceChange=Fa(r.getPresenceChange())),e}function Ja(r){const e=[];for(const t of r)e.push(Ua(t));return e}function za(r){const e=[];for(const t of r)e.push(new Ms({key:t.getStrKey(),element:Xn(t.getValue())}));return e}function qa(r){const e=[];for(const t of r)e.push(new qn({element:Xn(t.getValue())}));return e}function Va(r){const e=[];for(const t of r){const n=new Fs;n.id=$a(t.getID()),n.value=t.getValue().getContent(),n.removedAt=b(t.getRemovedAt());const s=n.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new gn;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),s[o.getKey()]=a}e.push(n)}return e}function Ka(r){const e=[];if(!r||!r.length)return e;for(const t of r)e.push(new Ls({content:Yn(t)}));return e}function ja(r){const e={};for(const t of r)e[t.getKey()]=new gn({value:t.getValue(),updatedAt:b(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Yn(r){if(!r)return[];const e=[];return pn(r,(t,n)=>{const s=new Vn({id:xt(t.id),type:t.type,removedAt:b(t.removedAt),depth:n});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=xt(t.insPrevID)),t.insNextID&&(s.insNextId=xt(t.insNextID)),t.attrs&&(s.attributes=ja(t.attrs)),e.push(s)}),e}function Wa(r){const e=new fe;return e.body.case="jsonObject",e.body.value=new xs({nodes:za(r.getRHT()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function ei(r){const e=new fe;return e.body.case="jsonArray",e.body.value=new Os({nodes:qa(r.getElements()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ga(r){const e=new fe;return e.body.case="primitive",e.body.value=new Ps({type:Xs(r.getType()),value:r.toBytes(),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ha(r){const e=new fe;return e.body.case="text",e.body.value=new Ds({nodes:Va(r.getRGATreeSplit()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ya(r){const e=new fe;return e.body.case="counter",e.body.value=new Rs({type:Zs(r.getType()),value:r.toBytes(),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function ti(r){const e=new fe;return e.body.case="tree",e.body.value=new Bs({nodes:Yn(r.getRoot()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Xn(r){if(r instanceof re)return Wa(r);if(r instanceof oe)return ei(r);if(r instanceof L)return Ga(r);if(r instanceof he)return Ha(r);if(r instanceof ae)return Ya(r);if(r instanceof le)return ti(r);throw new g(f.ErrUnimplemented,"unimplemented element")}function Xa(r){return new Je({documentKey:r.getDocumentKey(),checkpoint:La(r.getCheckpoint()),isRemoved:r.getIsRemoved(),changes:Ja(r.getChanges()),snapshot:r.getSnapshot(),minSyncedTicket:b(r.getMinSyncedTicket())})}function $r(r){const e=r.findDetails(ma);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function ni(r){let e;return r.serverSeq&&(e=N.fromString(r.serverSeq,!0)),je.of(r.clientSeq,N.fromString(r.lamport,!0),tr(r.actorId),e)}function A(r){if(r)return ne.of(N.fromString(r.lamport,!0),r.delimiter,tr(r.actorId))}function Zn(r){const e={};return Object.entries(r.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Za(r){const e=r.type;if(e===Rt.PUT){const t=Zn(r.presence);return{type:Xe.Put,presence:t}}if(e===Rt.CLEAR)return{type:Xe.Clear};throw new g(f.ErrInvalidType,`unsupported type: ${e}`)}function Qa(r){const e=new Map;return Object.entries(r).forEach(([t,n])=>{e.set(t,Zn(n))}),e}function ri(r){switch(r){case C.NULL:return K.Null;case C.BOOLEAN:return K.Boolean;case C.INTEGER:return K.Integer;case C.LONG:return K.Long;case C.DOUBLE:return K.Double;case C.STRING:return K.String;case C.BYTES:return K.Bytes;case C.DATE:return K.Date}throw new g(f.ErrUnimplemented,`unimplemented value type: ${r}`)}function hn(r){switch(r){case C.INTEGER_CNT:return De.IntegerCnt;case C.LONG_CNT:return De.LongCnt}throw new g(f.ErrUnimplemented,`unimplemented value type: ${r}`)}function Nn(r){switch(r.type){case C.JSON_OBJECT:return r.value?hi(r.value):re.create(A(r.createdAt));case C.JSON_ARRAY:return r.value?lc(r.value):oe.create(A(r.createdAt));case C.TEXT:return he.create(bt.create(),A(r.createdAt));case C.TREE:return dc(r.value);case C.NULL:case C.BOOLEAN:case C.INTEGER:case C.LONG:case C.DOUBLE:case C.STRING:case C.BYTES:case C.DATE:return L.of(L.valueFromBytes(ri(r.type),r.value),A(r.createdAt));case C.INTEGER_CNT:case C.LONG_CNT:return ae.create(hn(r.type),ae.valueFromBytes(hn(r.type),r.value),A(r.createdAt))}}function Ht(r){return ye.of(Pe.of(A(r.createdAt),r.offset),r.relativeOffset)}function si(r){return Pe.of(A(r.createdAt),r.offset)}function ec(r){const e=Lt.create(r.value);Object.entries(r.attributes).forEach(([n,s])=>{e.setAttr(n,s.value,A(s.updatedAt))});const t=He.create(si(r.id),e);return t.remove(A(r.removedAt)),t}function ut(r){return me.of(Ot(r.parentId),Ot(r.leftSiblingId))}function Ot(r){return G.of(A(r.createdAt),r.offset)}function tc(r){if(!r.length)return;const e=[];return r.forEach(t=>{const n=Qn(t.content);e.push(n)}),e}function Qn(r){if(r.length===0)return;const e=[];for(const s of r)e.push(rc(s));const t=e[e.length-1],n=new Map;n.set(r[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)n.get(r[s].depth-1).prepend(e[s]),n.set(r[s].depth,e[s]);return t.updateDescendantsSize(),le.create(t,pe).getRoot()}function nc(r){const e=Ue.create();for(const[t,n]of Object.entries(r))e.setInternal(t,n.value,A(n.updatedAt),n.isRemoved);return e}function rc(r){const e=Ot(r.id),t=ie.create(e,r.type),n=Object.entries(r.attributes);return t.isText?t.value=r.value:n.length&&(t.attrs=nc(r.attributes)),r.insPrevId&&(t.insPrevID=Ot(r.insPrevId)),r.insNextId&&(t.insNextID=Ot(r.insNextId)),t.removedAt=A(r.removedAt),t}function ii(r){if(r.body.case==="set"){const e=r.body.value;return ot.create(e.key,Nn(e.value),A(e.parentCreatedAt),A(e.executedAt))}else if(r.body.case==="add"){const e=r.body.value;return Jt.create(A(e.parentCreatedAt),A(e.prevCreatedAt),Nn(e.value),A(e.executedAt))}else if(r.body.case==="move"){const e=r.body.value;return We.create(A(e.parentCreatedAt),A(e.prevCreatedAt),A(e.createdAt),A(e.executedAt))}else if(r.body.case==="remove"){const e=r.body.value;return Ze.create(A(e.parentCreatedAt),A(e.createdAt),A(e.executedAt))}else if(r.body.case==="edit"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,A(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),zt.create(A(e.parentCreatedAt),Ht(e.from),Ht(e.to),t,e.content,n,A(e.executedAt))}else if(r.body.case==="style"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,A(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),qt.create(A(e.parentCreatedAt),Ht(e.from),Ht(e.to),t,n,A(e.executedAt))}else{if(r.body.case==="select")return;if(r.body.case==="increase"){const e=r.body.value;return At.create(A(e.parentCreatedAt),Nn(e.value),A(e.executedAt))}else if(r.body.case==="treeEdit"){const e=r.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,s])=>{t.set(n,A(s))}),Vt.create(A(e.parentCreatedAt),ut(e.from),ut(e.to),tc(e.contents),e.splitLevel,t,A(e.executedAt))}else if(r.body.case==="treeStyle"){const e=r.body.value,t=new Map,n=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,A(o))}),(n==null?void 0:n.length)>0?_e.createTreeRemoveStyleOperation(A(e.parentCreatedAt),ut(e.from),ut(e.to),s,n,A(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),_e.create(A(e.parentCreatedAt),ut(e.from),ut(e.to),s,t,A(e.executedAt)))}else throw new g(f.ErrUnimplemented,"unimplemented operation")}}function sc(r){const e=[];for(const t of r){const n=ii(t);n&&e.push(n)}return e}function oi(r){const e=[];for(const t of r)e.push(wt.create({id:ni(t.id),operations:sc(t.operations),presenceChange:t.presenceChange?Za(t.presenceChange):void 0,message:t.message}));return e}function ic(r){return mt.of(N.fromString(r.serverSeq,!0),r.clientSeq)}function oc(r){return yn.create(r.documentKey,ic(r.checkpoint),r.isRemoved,oi(r.changes),r.snapshot,A(r.minSyncedTicket))}function ai(r){const e=new Bt;for(const n of r.nodes){const s=er(n.element);e.set(n.key,s,s.getPositionedAt())}const t=new re(A(r.createdAt),e);return t.setMovedAt(A(r.movedAt)),t.setRemovedAt(A(r.removedAt)),t}function ci(r){const e=new Ft;for(const n of r.nodes)e.insert(er(n.element));const t=new oe(A(r.createdAt),e);return t.setMovedAt(A(r.movedAt)),t.setRemovedAt(A(r.removedAt)),t}function ac(r){const e=L.of(L.valueFromBytes(ri(r.type),r.value),A(r.createdAt));return e.setMovedAt(A(r.movedAt)),e.setRemovedAt(A(r.removedAt)),e}function cc(r){const e=new bt;let t=e.getHead();for(const s of r.nodes){const i=e.insertAfter(t,ec(s));s.insPrevId&&i.setInsPrev(e.findNode(si(s.insPrevId))),t=i}const n=new he(e,A(r.createdAt));return n.setMovedAt(A(r.movedAt)),n.setRemovedAt(A(r.removedAt)),n}function uc(r){const e=ae.create(hn(r.type),ae.valueFromBytes(hn(r.type),r.value),A(r.createdAt));return e.setMovedAt(A(r.movedAt)),e.setRemovedAt(A(r.removedAt)),e}function ui(r){const e=Qn(r.nodes);return le.create(e,A(r.createdAt))}function er(r){if(r.body.case==="jsonObject")return ai(r.body.value);if(r.body.case==="jsonArray")return ci(r.body.value);if(r.body.case==="primitive")return ac(r.body.value);if(r.body.case==="text")return cc(r.body.value);if(r.body.case==="counter")return uc(r.body.value);if(r.body.case==="tree")return ui(r.body.value);throw new g(f.ErrUnimplemented,"unimplemented element")}function hc(r){if(!r)return{root:re.create(pe),presences:new Map};const e=Ko.fromBinary(r);return{root:er(e.root),presences:Qa(e.presences)}}function hi(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ai(e.body.value)}function li(r){return Xn(r).toBinary()}function lc(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ci(e.body.value)}function fc(r){return ei(r).toBinary()}function dc(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ui(e.body.value)}function gc(r){return ti(r).toBinary()}function fi(r){return r?Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function tr(r){return fi(r)}function di(r){return new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function nr(r){return di(r)}function mc(r){const e=dn.fromBinary(r);return ni(e)}function pc(r){const e=zn.fromBinary(r);return ii(e)}const j={fromPresence:Zn,toChangePack:Xa,fromChangePack:oc,fromChanges:oi,toTreeNodes:Yn,fromTreeNodes:Qn,objectToBytes:li,bytesToObject:hi,bytesToSnapshot:hc,bytesToHex:fi,hexToBytes:di,toHexString:tr,toUint8Array:nr,toOperation:Qs,toChangeID:Ys,PbChangeID:dn,bytesToChangeID:mc,bytesToOperation:pc};var Q=(r=>(r[r.Trivial=0]="Trivial",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warn=3]="Warn",r[r.Error=4]="Error",r[r.Fatal=5]="Fatal",r))(Q||{});let et=3;function gi(r){et=r}const k={trivial:(...r)=>{et>0||typeof console<"u"&&console.log("YORKIE T:",...r)},debug:(...r)=>{et>1||typeof console<"u"&&console.log("YORKIE D:",...r)},info:(...r)=>{et>2||typeof console<"u"&&console.log("YORKIE I:",...r)},warn:(...r)=>{et>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...r):console.log("YORKIE W:",...r))},error:(...r)=>{et>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...r):console.log("YORKIE E:",...r))},fatal:(...r)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...r):console.log("YORKIE F:",...r))},isEnabled:r=>et<=r};function mi(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}class yc{constructor(e,t,n,s,i){l(this,"reconnectStreamDelay");l(this,"doc");l(this,"docID");l(this,"syncMode");l(this,"remoteChangeEventReceived");l(this,"watchStream");l(this,"watchLoopTimerID");l(this,"watchAbortController");l(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===sn.RealtimeSyncOff?!1:this.syncMode===sn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==sn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Cn=()=>{};class vc{constructor(e){l(this,"finalized",!1);l(this,"observers",[]);l(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let s;if(!e)throw new g(f.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(f.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:n},s.next===void 0&&(s.next=Cn),s.error===void 0&&(s.error=Cn),s.complete===void 0&&(s.complete=Cn);const i=mi(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){k.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class ft{constructor(e,t,n,s){l(this,"id");l(this,"delimiter");l(this,"message");l(this,"root");l(this,"operations");l(this,"presenceChange");l(this,"previousPresence");l(this,"reversePresenceKeys");this.id=e,this.delimiter=Wn,this.root=t,this.operations=[],this.previousPresence=de(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,n,s){return new ft(e,t,n,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return wt.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class $t{constructor(e){l(this,"rootObject");l(this,"elementPairMapByCreatedAt");l(this,"gcElementSetByCreatedAt");l(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof he||t instanceof le)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new $t(re.create(pe))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new g(f.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);n.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Ge&&e.getDescendants((n,s)=>(this.registerElement(n,s),!1))}deregisterElement(e){let t=0;const n=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return n(e),e instanceof Ge&&e.getDescendants(s=>(n(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof Ge&&n.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new $t(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(n);s.element.getRemovedAt()&&e.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,n]of this.gcPairMap){const s=n.child.getRemovedAt();s!==void 0&&e.compare(s)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function pi(r,e){const t=new _t(r);return new Proxy(e,t.getHandlers())}class _t{constructor(e){l(this,"context");l(this,"handlers");this.context=e,this.handlers={set:(t,n,s)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]=${JSON.stringify(s)}`),_t.setInternal(e,t,n,s),!0),get:(t,n)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():tt(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]`),_t.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,s){if(n.includes("."))throw new g(f.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=ln(e,s,i),a=t.set(n,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(ot.create(n,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const n={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new g(f.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=ln(e,i,o);n[s]=a}return n}static deleteInternal(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByKey(n,s);i&&(e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function wc(r,e){const t=new $(r,e);return new Proxy(e,t.getHandlers())}function bc(r){return typeof r=="string"||r instanceof String?!isNaN(r):!1}function Ac(r){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)}class ${constructor(e,t){l(this,"context");l(this,"handlers");l(this,"array");this.context=e,this.array=t,this.handlers={get:(n,s,i)=>s==="getID"?()=>n.getCreatedAt():s==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return Ve(e,a)}:s==="getElementByIndex"?o=>{const a=n.get(o);return Ve(e,a)}:s==="getLast"?()=>Ve(e,n.getLast()):s==="deleteByID"?o=>{const a=$.deleteInternalByID(e,n,o);return Ve(e,a)}:s==="insertAfter"?(o,a)=>{const c=$.insertAfterInternal(e,n,o,a);return Ve(e,c)}:s==="insertBefore"?(o,a)=>{const c=$.insertBeforeInternal(e,n,o,a);return Ve(e,c)}:s==="moveBefore"?(o,a)=>{$.moveBeforeInternal(e,n,o,a)}:s==="moveAfter"?(o,a)=>{$.moveAfterInternal(e,n,o,a)}:s==="moveFront"?o=>{$.moveFrontInternal(e,n,o)}:s==="moveLast"?o=>{$.moveLastInternal(e,n,o)}:bc(s)?tt(e,n.get(Number(s))):s==="push"?o=>$.pushInternal(e,n,o):s==="splice"?(o,a,...c)=>$.splice(e,n,o,a,...c):s==="length"?n.length:typeof s=="symbol"&&s===Symbol.iterator?$.iteratorInternal.bind(this,e,n):s==="includes"?(o,a)=>$.includes(e,n,o,a):s==="indexOf"?(o,a)=>$.indexOf(e,n,o,a):s==="lastIndexOf"?(o,a)=>$.lastIndexOf(e,n,o,a):s==="toJSForTest"?()=>n.toJSForTest():s==="toTestString"?()=>$.toTestString(n):typeof s=="string"&&Ac(s)?(...o)=>{const a=Array.from(n).map(c=>tt(e,c));return Array.prototype[s].apply(a,o)}:Reflect.get(n,s,i),deleteProperty:(n,s)=>(k.isEnabled(Q.Trivial)&&k.trivial(`array[${s}]`),$.deleteInternalByIndex(e,n,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield Ve(e,n)}static buildArrayElements(e,t){const n=[];for(const s of t){const i=e.issueTimeTicket(),o=ln(e,s,i);n.push(o)}return n}static pushInternal(e,t,n){return $.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,s,i),e.push(We.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,n,s){const i=e.issueTimeTicket();t.moveAfter(n,s,i),e.push(We.create(t.getCreatedAt(),n,s,i))}static moveFrontInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),n,s),e.push(We.create(t.getCreatedAt(),i.getCreatedAt(),n,s))}static moveLastInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,n,s),e.push(We.create(t.getCreatedAt(),i,n,s))}static insertAfterInternal(e,t,n,s){const i=e.issueTimeTicket(),o=ln(e,s,i);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Jt.create(t.getCreatedAt(),n,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,n,s){return $.insertAfterInternal(e,t,t.getPrevCreatedAt(n),s)}static deleteInternalByIndex(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByIndex(n,s);if(i)return e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,n){const s=e.issueTimeTicket(),i=t.delete(n,s);return e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,n,s,...i){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),c=s===void 0?o:s<0?a:Math.min(a+s,o),u=[];for(let h=a;h=i)return!1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).includes(n,o);for(let c=o;c=i)return-1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).indexOf(n,o);for(let c=o;c=i?i-1:s<0?s+i:s;if(o<0)return-1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).lastIndexOf(n,o);for(let c=o;c>0;c--)if(((a=t.get(c))==null?void 0:a.getID())===n.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class vn{constructor(e,t){l(this,"context");l(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,s){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);k.isEnabled(Q.Debug)&&k.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${n}`);const o=s?Tt(s):void 0,a=this.context.issueTimeTicket(),[c,,u,h]=this.text.edit(i,n,a,o);for(const p of u)this.context.registerGCPair(p);return this.context.push(new zt(this.text.getCreatedAt(),i[0],i[1],c,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(h)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);k.isEnabled(Q.Debug)&&k.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(n)}`);const i=Tt(n),o=this.context.issueTimeTicket(),[a,c]=this.text.setStyle(s,i,o);for(const u of c)this.context.registerGCPair(u);return this.context.push(new qt(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([ye.fromStruct(e[0]),ye.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class Tn{constructor(e,t){l(this,"valueType");l(this,"value");l(this,"context");l(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new g(f.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=L.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(At.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(f.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function rr(r,e,t){const{type:n}=r,s=t.issueTimeTicket();if(n===$e){yi(r);const{value:i}=r,o=ie.create(G.of(s,0),n,i);e.append(o)}else{const{children:i=[]}=r,{attributes:o}=r;let a;if(typeof o=="object"&&!qs(o)){const u=Tt(o);a=new Ue;for(const[h,p]of Object.entries(u))a.set(h,p,s)}const c=ie.create(G.of(s,0),n,void 0,a);e.append(c);for(const u of i)rr(u,c,t)}}function Ic(r,e){const{type:t}=e,n=r.issueTimeTicket();let s;if(e.type===$e){const{value:i}=e;s=ie.create(G.of(n,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!qs(o)){const c=Tt(o);a=new Ue;for(const[u,h]of Object.entries(c))a.set(u,h,n)}s=ie.create(G.of(r.issueTimeTicket(),0),t,void 0,a);for(const c of i)rr(c,s,r)}return s}function yi(r){if(!r.value.length)throw new g(f.ErrInvalidArgument,"text node cannot have empty value");return!0}function _r(r){if(!r.length)return!0;if(r[0].type===$e)for(const t of r){const{type:n}=t;if(n!==$e)throw new g(f.ErrInvalidArgument,"element node and text node cannot be passed together");yi(t)}else for(const t of r){const{type:n}=t;if(n===$e)throw new g(f.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class wn{constructor(e){l(this,"initialRoot");l(this,"context");l(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ie.create(G.of(e.issueTimeTicket(),0),Sa);const t=ie.create(G.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)rr(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const[n,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?Tt(t):void 0,[a]=this.tree.style([n,s],o,i);this.context.push(_e.create(this.tree.getCreatedAt(),n,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,n){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?Tt(n):void 0,[c,u]=this.tree.style([s,i],a,o);for(const h of u)this.context.registerGCPair(h);this.context.push(_e.create(this.tree.getCreatedAt(),s,i,c,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,c]=this.tree.removeStyle([s,i],n,o);for(const u of c)this.context.registerGCPair(u);this.context.push(_e.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,n,o))}editInternal(e,t,n,s=0){var u;if(n.length!==0&&n[0]&&(_r(n),n[0].type!==$e))for(const h of n){const{children:p=[]}=h;_r(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((u=n[0])==null?void 0:u.type)===$e){let h="";for(const p of n){const{value:v}=p;h+=v}o.push(ie.create(G.of(this.context.issueTimeTicket(),0),$e,h))}else o=n.map(h=>h&&Ic(this.context,h)).filter(h=>h);const[,a,c]=this.tree.edit([e,t],o.length?o.map(h=>h==null?void 0:h.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const h of a)this.context.registerGCPair(h);return this.context.push(Vt.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,c,i)),!0}editByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new g(f.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulkByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new g(f.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n,s)}edit(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulk(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n,s)}toXML(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[me.fromStruct(e[0]),me.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[me.fromStruct(e[0]),me.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Ur(r,e){return pi(r,e)}function Ve(r,e){if(e){if(e instanceof L)return e;if(e instanceof re)return pi(r,e);if(e instanceof oe)return wc(r,e);if(e instanceof he)return new vn(r,e);if(e instanceof ae){const t=new Tn(De.IntegerCnt,0);return t.initialize(r,e),t}else if(e instanceof le){const t=new wn;return t.initialize(r,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function tt(r,e){const t=Ve(r,e);return t instanceof L?t.getValue():t}function ln(r,e,t){let n;if(L.isSupport(e))n=L.of(e,t);else if(Array.isArray(e))n=oe.create(t,$.buildArrayElements(r,e));else if(typeof e=="object")e instanceof vn?(n=he.create(bt.create(),t),e.initialize(r,n)):e instanceof Tn?(n=ae.create(e.getValueType(),e.getValue(),t),e.initialize(r,n)):e instanceof wn?(n=le.create(e.buildRoot(r),t),e.initialize(r,n)):n=re.create(t,_t.buildObjectMembers(r,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Jr=50;class Sc{constructor(){l(this,"undoStack",[]);l(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Jr&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Jr&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const kc="yorkie-devtools-panel",Ec="yorkie-devtools-sdk";let ht="disconnected";const zr=new Map,rn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=rn);function Yt(r,e){(e!=null&&e.force||ht!=="disconnected")&&window.postMessage({source:Ec,...r},"*")}function Nc(r){if(!r.isEnableDevtools()||typeof window>"u"||zr.has(r.getKey()))return;rn.set(r.getKey(),[]);const e=r.subscribe("all",t=>{t.some(n=>n.type!==Z.StatusChanged&&n.type!==Z.Snapshot&&n.type!==Z.LocalChange&&n.type!==Z.RemoteChange&&n.type!==Z.Initialized&&n.type!==Z.Watched&&n.type!==Z.Unwatched&&n.type!==Z.PresenceChanged)||(rn.get(r.getKey()).push(t),ht==="synced"&&Yt({msg:"doc::sync::partial",docKey:r.getKey(),event:t}))});zr.set(r.getKey(),[e]),Yt({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==kc)return;switch(t.data.msg){case"devtools::connect":if(ht!=="disconnected")break;ht="connected",Yt({msg:"doc::available",docKey:r.getKey()}),k.info(`[YD] Devtools connected. Doc: ${r.getKey()}`);break;case"devtools::disconnect":ht="disconnected",k.info(`[YD] Devtools disconnected. Doc: ${r.getKey()}`);break;case"devtools::subscribe":ht="synced",Yt({msg:"doc::sync::full",docKey:r.getKey(),events:rn.get(r.getKey())}),k.info(`[YD] Devtools subscribed. Doc: ${r.getKey()}`);break}})}var Ke=(r=>(r.Detached="detached",r.Attached="attached",r.Removed="removed",r))(Ke||{}),Z=(r=>(r.StatusChanged="status-changed",r.ConnectionChanged="connection-changed",r.SyncStatusChanged="sync-status-changed",r.Snapshot="snapshot",r.LocalChange="local-change",r.RemoteChange="remote-change",r.Initialized="initialized",r.Watched="watched",r.Unwatched="unwatched",r.PresenceChanged="presence-changed",r.Broadcast="broadcast",r.LocalBroadcast="local-broadcast",r))(Z||{}),$n=(r=>(r.Connected="connected",r.Disconnected="disconnected",r))($n||{}),_n=(r=>(r.Synced="synced",r.SyncFailed="sync-failed",r))(_n||{});class vi{constructor(e,t){l(this,"key");l(this,"status");l(this,"opts");l(this,"changeID");l(this,"checkpoint");l(this,"localChanges");l(this,"root");l(this,"clone");l(this,"eventStream");l(this,"eventStreamObserver");l(this,"onlineClients");l(this,"presences");l(this,"history");l(this,"internalHistory");l(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=$t.create(),this.changeID=Da,this.checkpoint=Ra,this.localChanges=[],this.eventStream=Tc(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Sc,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Nc(this)}update(e,t){if(this.getStatus()==="removed")throw new g(f.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),s=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const i=Ur(s,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(i,new kn(s,this.clone.presences.get(n)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){k.isEnabled(Q.Trivial)&&k.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,M.Local),c=s.getReversePresence();c&&a.push({type:"presence",value:c}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const u=[];o.length>0&&u.push({type:"local-change",source:M.Local,value:{message:i.getMessage()||"",operations:o,actor:n,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&u.push({type:"presence-changed",source:M.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(u),k.isEnabled(Q.Trivial)&&k.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,s){if(typeof e=="string"){if(typeof t!="function")throw new g(f.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},n,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},n,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},n,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="connection-changed"&&a(u)},n,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="status-changed"&&a(u)},n,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="sync-status-changed"&&a(u)},n,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="local-broadcast"&&a(u)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="broadcast"&&a(u)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const c of a){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const u=[];for(const h of c.value.operations)this.isSameElementOrChildOf(h.path,i)&&u.push(h);u.length&&o({...c,value:{...c.value,operations:u}})}},n,s)}if(typeof e=="function"){const i=e,o=t,a=n;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||i(u)},o,a)}throw new g(f.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((i,o)=>i===n[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),M.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,M.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),k.isEnabled(Q.Trivial)&&k.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:de(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return yn.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ur(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:s}=j.bytesToSnapshot(t);this.root=new $t(n),this.presences=s,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:M.Remote,value:{snapshot:this.isEnableDevtools()?j.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){k.isEnabled(Q.Debug)&&k.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),k.isEnabled(Q.Trivial)&&k.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class Ut{constructor(e){l(this,"createdAt");l(this,"movedAt");l(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ge extends Ut{constructor(e){super(e)}}class Gn{constructor(e,t){l(this,"strKey");l(this,"value");this.strKey=e,this.value=t}static of(e,t){return new Gn(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Bt{constructor(){l(this,"nodeMapByKey");l(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Bt}set(e,t,n){let s;const i=this.nodeMapByKey.get(e);i!=null&&!i.isRemoved()&&i.remove(n)&&(s=i.getValue());const o=Gn.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(i==null||n.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(n)),s}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new g(f.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new g(f.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class re extends Ge{constructor(t,n){super(t);l(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new re(t,Bt.create());const s=Bt.create();for(const[i,o]of Object.entries(n))s.set(i,o.deepcopy(),o.getCreatedAt());return new re(t,s)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,s){return this.memberNodes.set(t,n,s)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,s]of this)t.push(`"${Oe(n)}":${s.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,s]of this){const{createdAt:i,value:o,type:a}=s.toJSForTest();t[n]={key:n,createdAt:i,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var s;const t=Array();for(const[i]of this)t.push(i);const n=[];for(const i of t.sort()){const o=(s=this.memberNodes.get(i))==null?void 0:s.getValue();n.push(`"${Oe(i)}":${o.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=re.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const s=n.getValue();if(t(s,this))return;s instanceof Ge&&s.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var M=(r=>(r.Local="local",r.Remote="remote",r.UndoRedo="undoredo",r))(M||{});class ve{constructor(e,t){l(this,"parentCreatedAt");l(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new g(f.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Vs{constructor(e){l(this,"value");l(this,"left");l(this,"right");l(this,"parent");l(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Mt{constructor(e){l(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new g(f.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return this.splayNode(t),[t,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Mt(e.getLeft());t.root&&t.root.setParent();const n=new Mt(e.getRight());if(n.root&&n.root.setParent(),t.root){const s=t.getRightmost();t.splayNode(s),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var K=(r=>(r[r.Null=0]="Null",r[r.Boolean=1]="Boolean",r[r.Integer=2]="Integer",r[r.Long=3]="Long",r[r.Double=4]="Double",r[r.String=5]="String",r[r.Bytes=6]="Bytes",r[r.Date=7]="Date",r))(K||{});class L extends Ut{constructor(t,n){super(n);l(this,"valueType");l(this,"value");this.valueType=L.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new L(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const s=new DataView(n.buffer);return n.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return N.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(N.fromBytesLE(Array.from(n),!0).toNumber());default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${Oe(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=L.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof N)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return L.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=N.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new g(f.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class un extends Vs{constructor(t){super(t);l(this,"prev");l(this,"next");this.value=t}static createAfter(t,n){const s=new un(n),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Ft{constructor(){l(this,"dummyHead");l(this,"last");l(this,"nodeMapByIndex");l(this,"nodeMapByCreatedAt");const e=L.of(0,pe);e.setRemovedAt(pe),this.dummyHead=new un(e),this.last=this.dummyHead,this.nodeMapByIndex=new Mt,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ft}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new g(f.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,n),i=un.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,n){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new g(f.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new g(f.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||n.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),n),i.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new g(f.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||n>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),s=n.isRemoved();return n.remove(t)&&!s&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class oe extends Ge{constructor(t,n){super(t);l(this,"elements");this.elements=n}static create(t,n){if(!n)return new oe(t,Ft.create());const s=Ft.create();for(const i of n)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new oe(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,s){this.elements.moveAfter(t,n,s)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const s=n.getValue();if(t(s,this))return;s instanceof Ge&&s.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...m,value:m.value?{attributes:gt(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,v,h,[c,c]]}setStyle(t,n,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),c=[],u=this.rgaTreeSplit.findBetween(a,o),h=new Map,p=[];for(const m of u){const T=m.getCreatedAt().getActorID(),S=i!=null&&i.size?i.has(T)?i.get(T):pe:Ct;if(m.canStyle(s,S)){const E=h.get(T),x=m.getCreatedAt();(!E||x.after(E))&&h.set(T,x),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[T,S]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());c.push({type:"style",actor:s.getActorID(),from:T,to:S,value:{attributes:gt(n)}});for(const[E,x]of Object.entries(n)){const[O]=m.getValue().setAttr(E,x,s);O!==void 0&&v.push({parent:m.getValue(),child:O})}}return[h,v,c]}indexRangeToPosRange(t,n){const s=this.rgaTreeSplit.indexToPos(t);return t===n?[s,s]:[s,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const s=n.getValue();t.push({attributes:gt(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new he(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const s of n.getValue().getGCPairs())t.push(s)}return t}}class zt extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"content");l(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,n,s,i,o,a,c){return new zt(t,n,s,i,o,a,c)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof he))throw new g(f.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:u})=>({type:"edit",from:a,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${n},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class qt extends ve{constructor(t,n,s,i,o,a){super(t,a);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,n,s,i,o,a){return new qt(t,n,s,i,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof he))throw new g(f.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:c,value:u})=>({type:"style",from:a,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${n},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Ia=2,Sa="root",$e="text";function St(r,e){let t=0;const n=r.children;for(let s=0;s0)throw new g(f.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===$e}get paddedSize(){return this.size+(this.isText?0:Ia)}isAncestorOf(e){return Ea(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=n;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new g(f.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,n._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new g(f.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new g(f.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function Ea(r,e){if(r===e)return!1;for(;e.parent;){if(e.parent===r)return!0;e=e.parent}return!1}var z=(r=>(r.Start="Start",r.End="End",r.Text="Text",r))(z||{});function Ks(r,e,t,n){if(e>t)throw new g(f.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>r.size)throw new g(f.ErrInvalidArgument,`from is out of range: ${e} > ${r.size}`);if(t>r.size)throw new g(f.ErrInvalidArgument,`to is out of range: ${t} > ${r.size}`);if(e===t)return;let s=0;for(const i of r.children){if(e-i.paddedSizei.size;(i.isText||c)&&n([i,i.isText?"Text":"Start"],u),Ks(i,Math.max(0,o),Math.min(a,i.size),n),u&&n([i,"End"],u)}s+=i.paddedSize}}function js(r,e,t=0){for(const n of r.children)js(n,e,t+1);e(r,t)}function pn(r,e,t=0){for(const n of r._children)pn(n,e,t+1);e(r,t)}function Fn(r,e,t=!0){if(e>r.size)throw new g(f.ErrInvalidArgument,`index is out of range: ${e} > ${r.size}`);if(r.isText)return{node:r,offset:e};let n=0,s=0;for(const i of r.children){if(t&&i.isText&&i.size>=e-s)return Fn(i,e-s,t);if(e===s)return{node:r,offset:n};if(!t&&i.paddedSize===e-s)return{node:r,offset:n+1};if(i.paddedSize>e-s)return Fn(i,e-s-1,t);s+=i.paddedSize,n+=1}return{node:r,offset:n}}function Ws(r){return r.isText||r.children.length===0?r:Ws(r.children[0])}function Na(r,e){if(r.sizer===e?0:r0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new Oa(e,t,!0);const s=this.comparator(e,n.key);return s<0?n.left=this.putInternal(e,t,n.left):s>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class me{constructor(e,t){l(this,"parentID");l(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new me(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,s;return n.isText?(n.parent.children[0]===n&&t===0?s=n.parent:s=n,n=n.parent):t===0?s=n:s=n.children[t-1],me.of(n.id,G.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return me.of(G.of(ne.fromStruct(e.parentID.createdAt),e.parentID.offset),G.of(ne.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(n);if(!s||!i)throw new g(f.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class G{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new G(e,t)}static fromStruct(e){return G.of(ne.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new g(f.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new g(f.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ie(G.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ie(G.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,s){const i=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new Ue);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,n));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function Ln(r){var t;if(r.isText){const n=r;return{type:n.type,value:n.value}}const e={type:r.type,children:r.children.map(Ln)};return r.attrs&&(e.attributes=gt((t=r.attrs)==null?void 0:t.toObject())),e}function Hn(r){if(r.isText)return r.value;let e="";return r.attrs&&r.attrs.size()&&(e=" "+Array.from(r.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${Oe(t.getValue())}"`}).join(" ")),`<${r.type}${e}>${r.children.map(t=>Hn(t)).join("")}`}function Hs(r){if(r.isText){const e=r;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:r.type,children:r.children.map(Hs),size:r.size,isRemoved:r.isRemoved}}class le extends Ut{constructor(t,n){super(n);l(this,"indexTree");l(this,"nodeMapByID");this.indexTree=new Ca(t),this.nodeMapByID=new Gs(G.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,n){return new le(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,c=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const u=c.allChildren,h=a?0:u.indexOf(o)+1;for(let p=h;p{const S=T.getCreatedAt().getActorID(),E=i?i.has(S)?i.get(S):pe:Ct;if(T.canStyle(s,E)&&n){const x=v.get(S),O=T.getCreatedAt();(!x||O.after(x))&&v.set(S,O);const W=T.setAttrs(n,s),P=W.reduce((J,[,ze])=>(ze&&(J[ze.getKey()]=p[ze.getKey()]),J),{}),B=T.parent,F=T.prevSibling||T.parent;Object.keys(P).length>0&&h.push({type:"style",from:this.toIndex(B,F),to:this.toIndex(T,T),fromPath:this.toPath(B,F),toPath:this.toPath(T,T),actor:s.getActorID(),value:P});for(const[J]of W)J&&m.push({parent:T,child:J})}}),[v,m,h]}removeStyle(t,n,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),h=[],p=new Map,v=[];return this.traverseInPosRange(o,a,c,u,([m])=>{const T=m.getCreatedAt().getActorID(),S=i?i.has(T)?i.get(T):pe:Ct;if(m.canStyle(s,S)&&n){const E=p.get(T),x=m.getCreatedAt();(!E||x.after(E))&&p.set(T,x),m.attrs||(m.attrs=new Ue);for(const P of n){const B=m.attrs.remove(P,s);for(const F of B)v.push({parent:m,child:F})}const O=m.parent,W=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(O,W),to:this.toIndex(m,m),fromPath:this.toPath(O,W),toPath:this.toPath(m,m),value:n})}}),[p,v,h]}edit(t,n,s,i,o,a){const[c,u]=this.findNodesAndSplitText(t[0],i),[h,p]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(c,u),m=this.toPath(c,u),T=[],S=[],E=[],x=new Map;this.traverseInPosRange(c,u,h,p,([P,B],F)=>{if(B===z.Start&&!F)for(const Qe of P.children)E.push(Qe);const J=P.getCreatedAt().getActorID(),ze=a?a.has(J)?a.get(J):pe:Ct;if(P.canDelete(i,ze)||T.includes(P.parent)){const Qe=x.get(J),Kt=P.getCreatedAt();(!Qe||Kt.after(Qe))&&x.set(J,Kt),(B===z.Text||B===z.Start)&&T.push(P),S.push([P,B])}});const O=this.makeDeletionChanges(S,i),W=[];for(const P of T)P.remove(i),P.isRemoved&&W.push({parent:this,child:P});for(const P of E)P.removedAt||c.append(P);if(s>0){let P=0,B=c,F=u;for(;P{c.isRemoved&&(J.remove(i),W.push({parent:this,child:J})),this.nodeMapByID.put(J.id,J)}),F.isRemoved||P.push(F);if(P.length){const F=P.map(J=>Ln(J));O.length&&O[O.length-1].from===v?O[O.length-1].value=F:O.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[O,W,x]}editT(t,n,s,i,o){const a=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([a,c],n,s,i,o)}move(t,n,s){throw new g(f.ErrUnimplemented,`not implemented: ${t}, ${n}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,s=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const s of n.getGCPairs())t.push(s)}),t}findPos(t,n=!0){const s=this.indexTree.findTreePos(t,n);return me.fromTreePos(s)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Hn(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(s,i=void 0,o=void 0,a=0)=>{var m,T,S,E;let c,u,h;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(c=this.indexTree.indexOf(p),u=this.indexTree.treePosToPath(p),h=me.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(T=s.insPrevID)==null?void 0:T.toTestString(),insNext:(S=s.insNextID)==null?void 0:S.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?gt((E=s.attrs)==null?void 0:E.toObject()):void 0,index:c,path:u,pos:h};for(let x=0;x0&&x===s[s.length-1].to?(s[s.length-1].to=O,s[s.length-1].toPath=this.toPath(E,m)):s.push({type:"content",from:x,to:O,fromPath:this.toPath(S,p),toPath:this.toPath(E,m),actor:n.getActorID()}))}return s.reverse()}findRightToken([t,n]){if(n===z.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?z.Text:z.Start]:[t,z.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,z.End];const a=i[o+1];return[a,a.isText?z.Text:z.Start]}findLeftToken([t,n]){if(n===z.End){const c=t.allChildren;if(c.length>0){const u=c[c.length-1];return[u,u.isText?z.Text:z.End]}return[t,z.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,z.Start];const a=i[o-1];return[a,a.isText?z.Text:z.End]}}class Vt extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"contents");l(this,"splitLevel");l(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,s,i,o,a,c){return new Vt(t,n,s,i,o,a,c)}execute(t){var c;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof le))throw new g(f.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=n,[o,a]=i.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(u=>u.deepcopy()),this.splitLevel,s,(()=>{let u=s.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>ne.of(s.getLamport(),++u,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:h,value:p,splitLevel:v,fromPath:m,toPath:T})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:u,to:h,value:p,splitLevel:v,fromPath:m,toPath:T}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${n},${s},${i.map(o=>Hn(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class je{constructor(e,t,n,s){l(this,"clientSeq");l(this,"serverSeq");l(this,"lamport");l(this,"actor");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.actor=n}static of(e,t,n,s){return new je(e,t,n,s)}next(){return new je(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new je(this.clientSeq,e,this.actor):new je(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return ne.of(this.lamport,e,this.actor)}setActor(e){return new je(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Da=new je(0,N.fromInt(0,!0),mn);class wt{constructor({id:e,operations:t,presenceChange:n,message:s}){l(this,"id");l(this,"operations");l(this,"presenceChange");l(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=s}static create({id:e,operations:t,presenceChange:n,message:s}){return new wt({id:e,operations:t,presenceChange:n,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:c,reverseOp:u}=a;s.push(...c),u&&i.unshift(u)}return this.presenceChange&&(this.presenceChange.type===Xe.Put?t.set(this.id.getActorID(),de(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:j.bytesToHex(j.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>j.bytesToHex(j.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:s,message:i}=e;return wt.create({id:j.bytesToChangeID(j.hexToBytes(t)),operations:n==null?void 0:n.map(o=>j.bytesToOperation(j.hexToBytes(o))),presenceChange:s,message:i})}}class yn{constructor(e,t,n,s,i,o){l(this,"documentKey");l(this,"checkpoint");l(this,"isRemoved");l(this,"changes");l(this,"snapshot");l(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(e,t,n,s,i,o){return new yn(e,t,n,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class mt{constructor(e,t){l(this,"serverSeq");l(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new mt(e,t)}increaseClientSeq(e){return e===0?this:new mt(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return mt.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Ra=new mt(N.fromInt(0,!0),0);class Pe{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Pe(e,t)}static fromStruct(e){return Pe.of(ne.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Pe(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Ba=Pe.of(pe,0);class ye{constructor(e,t){l(this,"id");l(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new ye(e,t)}static fromStruct(e){const t=Pe.fromStruct(e.id);return ye.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Pe.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class He extends Vs{constructor(t,n,s){super(n);l(this,"id");l(this,"removedAt");l(this,"prev");l(this,"next");l(this,"insPrev");l(this,"insNext");this.id=t,this.removedAt=s}static create(t,n){return new He(t,n)}static createComparator(){return(t,n)=>{const s=t.getCreatedAt().compare(n.getCreatedAt());return s!==0?s:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let s=e;for(;s&&s!==t;)n.push(s),s=s.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new g(f.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const s=e.getInsNext();return s&&s.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,n),o=new Map,a=new Map,c=this.makeChanges(i,t);for(const u of s){const h=u.getCreatedAt().getActorID();(!o.has(h)||u.getID().getCreatedAt().after(o.get(h)))&&o.set(h,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(t)}return this.deleteIndexNodes(i),[c,o,a]}filterNodes(e,t,n){const s=!!n,i=[],o=[],[a,c]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const h=u.getCreatedAt().getActorID(),p=s?n.has(h)?n.get(h):pe:Ct;u.canDelete(t,p)?i.push(u):o.push(u)}return o.push(c),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let s,i;for(let o=0;or<0?Math.ceil(r):Math.floor(r);var De=(r=>(r[r.IntegerCnt=0]="IntegerCnt",r[r.LongCnt=1]="LongCnt",r))(De||{});class ae extends Ut{constructor(t,n,s){super(s);l(this,"valueType");l(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=N.fromNumber(n).toInt():this.value=Lr(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=N.fromNumber(n):this.value=n;break;default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,s){return new ae(t,n,s)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return N.fromBytesLE(Array.from(n));default:throw new g(f.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=ae.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof N?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!ae.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new g(f.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===K.Long?this.value=this.value+t.getValue().toInt():this.value=N.fromNumber(this.value+Lr(t.getValue())).toInt(),this}}class At extends ve{constructor(t,n,s){super(t,s);l(this,"value");this.value=n}static create(t,n,s){return new At(t,n,s)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ae))throw new g(f.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=n,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===K.Long?t.getValue().multiply(-1):t.getValue()*-1;return At.create(this.getParentCreatedAt(),L.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class _e extends ve{constructor(t,n,s,i,o,a,c){super(t,c);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");l(this,"attributesToRemove");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,n,s,i,o,a){return new _e(t,n,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,s,i,o,a){return new _e(t,n,s,i,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new g(f.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof le))throw new g(f.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=n;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([c,u])=>a[c]=u),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:u,fromPath:h,toPath:p})=>({type:"tree-style",from:a,to:c,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:h,toPath:p,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Ma(r){const e=new Kn,t=e.data;for(const[n,s]of Object.entries(r))t[n]=JSON.stringify(s);return e}function Fa(r){if(r.type===Xe.Put)return new Bn({type:Rt.PUT,presence:Ma(r.presence)});if(r.type===Xe.Clear)return new Bn({type:Rt.CLEAR});throw new g(f.ErrUnimplemented,"unimplemented type")}function La(r){return new $s({serverSeq:r.getServerSeqAsString(),clientSeq:r.getClientSeq()})}function Ys(r){return new dn({clientSeq:r.getClientSeq(),lamport:r.getLamportAsString(),actorId:nr(r.getActorID())})}function b(r){if(r)return new I({lamport:r.getLamportAsString(),delimiter:r.getDelimiter(),actorId:nr(r.getActorID())})}function Xs(r){switch(r){case K.Null:return C.NULL;case K.Boolean:return C.BOOLEAN;case K.Integer:return C.INTEGER;case K.Long:return C.LONG;case K.Double:return C.DOUBLE;case K.String:return C.STRING;case K.Bytes:return C.BYTES;case K.Date:return C.DATE;default:throw new g(f.ErrInvalidType,`unsupported type: ${r}`)}}function Zs(r){switch(r){case De.IntegerCnt:return C.INTEGER_CNT;case De.LongCnt:return C.LONG_CNT;default:throw new g(f.ErrInvalidType,`unsupported type: ${r}`)}}function En(r){if(r instanceof re)return new Re({type:C.JSON_OBJECT,createdAt:b(r.getCreatedAt()),value:li(r)});if(r instanceof oe)return new Re({type:C.JSON_ARRAY,createdAt:b(r.getCreatedAt()),value:fc(r)});if(r instanceof he)return new Re({type:C.TEXT,createdAt:b(r.getCreatedAt())});if(r instanceof L)return new Re({type:Xs(r.getType()),createdAt:b(r.getCreatedAt()),value:r.toBytes()});if(r instanceof ae)return new Re({type:Zs(r.getType()),createdAt:b(r.getCreatedAt()),value:r.toBytes()});if(r instanceof le)return new Re({type:C.TREE,createdAt:b(r.getCreatedAt()),value:gc(r)});throw new g(f.ErrUnimplemented,"unimplemented element")}function $a(r){return new Rn({createdAt:b(r.getCreatedAt()),offset:r.getOffset()})}function Wt(r){return new it({createdAt:b(r.getID().getCreatedAt()),offset:r.getID().getOffset(),relativeOffset:r.getRelativeOffset()})}function Gt(r){return new Dt({parentId:xt(r.getParentID()),leftSiblingId:xt(r.getLeftSiblingID())})}function xt(r){return new dt({createdAt:b(r.getCreatedAt()),offset:r.getOffset()})}function Qs(r){const e=new zn;if(r instanceof ot){const t=r,n=new ws;n.parentCreatedAt=b(t.getParentCreatedAt()),n.key=t.getKey(),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(r instanceof Jt){const t=r,n=new bs;n.parentCreatedAt=b(t.getParentCreatedAt()),n.prevCreatedAt=b(t.getPrevCreatedAt()),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(r instanceof We){const t=r,n=new As;n.parentCreatedAt=b(t.getParentCreatedAt()),n.prevCreatedAt=b(t.getPrevCreatedAt()),n.createdAt=b(t.getCreatedAt()),n.executedAt=b(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(r instanceof Ze){const t=r,n=new Is;n.parentCreatedAt=b(t.getParentCreatedAt()),n.createdAt=b(t.getCreatedAt()),n.executedAt=b(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(r instanceof zt){const t=r,n=new Ss;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Wt(t.getFromPos()),n.to=Wt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);n.content=t.getContent();const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=b(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(r instanceof qt){const t=r,n=new ks;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Wt(t.getFromPos()),n.to=Wt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=b(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(r instanceof At){const t=r,n=new Es;n.parentCreatedAt=b(t.getParentCreatedAt()),n.value=En(t.getValue()),n.executedAt=b(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(r instanceof Vt){const t=r,n=new Ns,s=n.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=b(o);n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Gt(t.getFromPos()),n.to=Gt(t.getToPos()),n.contents=Ka(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=b(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(r instanceof _e){const t=r,n=new Cs;n.parentCreatedAt=b(t.getParentCreatedAt()),n.from=Gt(t.getFromPos()),n.to=Gt(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=b(a);const i=t.getAttributesToRemove();if(i.length>0)n.attributesToRemove=i;else{const o=n.attributes;for(const[a,c]of t.getAttributes())o[a]=c}n.executedAt=b(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new g(f.ErrUnimplemented,"unimplemented operation");return e}function _a(r){const e=[];for(const t of r)e.push(Qs(t));return e}function Ua(r){const e=new Ts({id:Ys(r.getID()),message:r.getMessage()});return r.hasOperations()&&(e.operations=_a(r.getOperations())),r.hasPresenceChange()&&(e.presenceChange=Fa(r.getPresenceChange())),e}function Ja(r){const e=[];for(const t of r)e.push(Ua(t));return e}function za(r){const e=[];for(const t of r)e.push(new Ms({key:t.getStrKey(),element:Xn(t.getValue())}));return e}function qa(r){const e=[];for(const t of r)e.push(new qn({element:Xn(t.getValue())}));return e}function Va(r){const e=[];for(const t of r){const n=new Fs;n.id=$a(t.getID()),n.value=t.getValue().getContent(),n.removedAt=b(t.getRemovedAt());const s=n.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new gn;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),s[o.getKey()]=a}e.push(n)}return e}function Ka(r){const e=[];if(!r||!r.length)return e;for(const t of r)e.push(new Ls({content:Yn(t)}));return e}function ja(r){const e={};for(const t of r)e[t.getKey()]=new gn({value:t.getValue(),updatedAt:b(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Yn(r){if(!r)return[];const e=[];return pn(r,(t,n)=>{const s=new Vn({id:xt(t.id),type:t.type,removedAt:b(t.removedAt),depth:n});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=xt(t.insPrevID)),t.insNextID&&(s.insNextId=xt(t.insNextID)),t.attrs&&(s.attributes=ja(t.attrs)),e.push(s)}),e}function Wa(r){const e=new fe;return e.body.case="jsonObject",e.body.value=new xs({nodes:za(r.getRHT()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function ei(r){const e=new fe;return e.body.case="jsonArray",e.body.value=new Os({nodes:qa(r.getElements()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ga(r){const e=new fe;return e.body.case="primitive",e.body.value=new Ps({type:Xs(r.getType()),value:r.toBytes(),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ha(r){const e=new fe;return e.body.case="text",e.body.value=new Ds({nodes:Va(r.getRGATreeSplit()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Ya(r){const e=new fe;return e.body.case="counter",e.body.value=new Rs({type:Zs(r.getType()),value:r.toBytes(),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function ti(r){const e=new fe;return e.body.case="tree",e.body.value=new Bs({nodes:Yn(r.getRoot()),createdAt:b(r.getCreatedAt()),movedAt:b(r.getMovedAt()),removedAt:b(r.getRemovedAt())}),e}function Xn(r){if(r instanceof re)return Wa(r);if(r instanceof oe)return ei(r);if(r instanceof L)return Ga(r);if(r instanceof he)return Ha(r);if(r instanceof ae)return Ya(r);if(r instanceof le)return ti(r);throw new g(f.ErrUnimplemented,"unimplemented element")}function Xa(r){return new Je({documentKey:r.getDocumentKey(),checkpoint:La(r.getCheckpoint()),isRemoved:r.getIsRemoved(),changes:Ja(r.getChanges()),snapshot:r.getSnapshot(),minSyncedTicket:b(r.getMinSyncedTicket())})}function $r(r){const e=r.findDetails(ma);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function ni(r){let e;return r.serverSeq&&(e=N.fromString(r.serverSeq,!0)),je.of(r.clientSeq,N.fromString(r.lamport,!0),tr(r.actorId),e)}function A(r){if(r)return ne.of(N.fromString(r.lamport,!0),r.delimiter,tr(r.actorId))}function Zn(r){const e={};return Object.entries(r.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Za(r){const e=r.type;if(e===Rt.PUT){const t=Zn(r.presence);return{type:Xe.Put,presence:t}}if(e===Rt.CLEAR)return{type:Xe.Clear};throw new g(f.ErrInvalidType,`unsupported type: ${e}`)}function Qa(r){const e=new Map;return Object.entries(r).forEach(([t,n])=>{e.set(t,Zn(n))}),e}function ri(r){switch(r){case C.NULL:return K.Null;case C.BOOLEAN:return K.Boolean;case C.INTEGER:return K.Integer;case C.LONG:return K.Long;case C.DOUBLE:return K.Double;case C.STRING:return K.String;case C.BYTES:return K.Bytes;case C.DATE:return K.Date}throw new g(f.ErrUnimplemented,`unimplemented value type: ${r}`)}function hn(r){switch(r){case C.INTEGER_CNT:return De.IntegerCnt;case C.LONG_CNT:return De.LongCnt}throw new g(f.ErrUnimplemented,`unimplemented value type: ${r}`)}function Nn(r){switch(r.type){case C.JSON_OBJECT:return r.value?hi(r.value):re.create(A(r.createdAt));case C.JSON_ARRAY:return r.value?lc(r.value):oe.create(A(r.createdAt));case C.TEXT:return he.create(bt.create(),A(r.createdAt));case C.TREE:return dc(r.value);case C.NULL:case C.BOOLEAN:case C.INTEGER:case C.LONG:case C.DOUBLE:case C.STRING:case C.BYTES:case C.DATE:return L.of(L.valueFromBytes(ri(r.type),r.value),A(r.createdAt));case C.INTEGER_CNT:case C.LONG_CNT:return ae.create(hn(r.type),ae.valueFromBytes(hn(r.type),r.value),A(r.createdAt))}}function Ht(r){return ye.of(Pe.of(A(r.createdAt),r.offset),r.relativeOffset)}function si(r){return Pe.of(A(r.createdAt),r.offset)}function ec(r){const e=Lt.create(r.value);Object.entries(r.attributes).forEach(([n,s])=>{e.setAttr(n,s.value,A(s.updatedAt))});const t=He.create(si(r.id),e);return t.remove(A(r.removedAt)),t}function ut(r){return me.of(Ot(r.parentId),Ot(r.leftSiblingId))}function Ot(r){return G.of(A(r.createdAt),r.offset)}function tc(r){if(!r.length)return;const e=[];return r.forEach(t=>{const n=Qn(t.content);e.push(n)}),e}function Qn(r){if(r.length===0)return;const e=[];for(const s of r)e.push(rc(s));const t=e[e.length-1],n=new Map;n.set(r[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)n.get(r[s].depth-1).prepend(e[s]),n.set(r[s].depth,e[s]);return t.updateDescendantsSize(),le.create(t,pe).getRoot()}function nc(r){const e=Ue.create();for(const[t,n]of Object.entries(r))e.setInternal(t,n.value,A(n.updatedAt),n.isRemoved);return e}function rc(r){const e=Ot(r.id),t=ie.create(e,r.type),n=Object.entries(r.attributes);return t.isText?t.value=r.value:n.length&&(t.attrs=nc(r.attributes)),r.insPrevId&&(t.insPrevID=Ot(r.insPrevId)),r.insNextId&&(t.insNextID=Ot(r.insNextId)),t.removedAt=A(r.removedAt),t}function ii(r){if(r.body.case==="set"){const e=r.body.value;return ot.create(e.key,Nn(e.value),A(e.parentCreatedAt),A(e.executedAt))}else if(r.body.case==="add"){const e=r.body.value;return Jt.create(A(e.parentCreatedAt),A(e.prevCreatedAt),Nn(e.value),A(e.executedAt))}else if(r.body.case==="move"){const e=r.body.value;return We.create(A(e.parentCreatedAt),A(e.prevCreatedAt),A(e.createdAt),A(e.executedAt))}else if(r.body.case==="remove"){const e=r.body.value;return Ze.create(A(e.parentCreatedAt),A(e.createdAt),A(e.executedAt))}else if(r.body.case==="edit"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,A(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),zt.create(A(e.parentCreatedAt),Ht(e.from),Ht(e.to),t,e.content,n,A(e.executedAt))}else if(r.body.case==="style"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,A(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),qt.create(A(e.parentCreatedAt),Ht(e.from),Ht(e.to),t,n,A(e.executedAt))}else{if(r.body.case==="select")return;if(r.body.case==="increase"){const e=r.body.value;return At.create(A(e.parentCreatedAt),Nn(e.value),A(e.executedAt))}else if(r.body.case==="treeEdit"){const e=r.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,s])=>{t.set(n,A(s))}),Vt.create(A(e.parentCreatedAt),ut(e.from),ut(e.to),tc(e.contents),e.splitLevel,t,A(e.executedAt))}else if(r.body.case==="treeStyle"){const e=r.body.value,t=new Map,n=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,A(o))}),(n==null?void 0:n.length)>0?_e.createTreeRemoveStyleOperation(A(e.parentCreatedAt),ut(e.from),ut(e.to),s,n,A(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),_e.create(A(e.parentCreatedAt),ut(e.from),ut(e.to),s,t,A(e.executedAt)))}else throw new g(f.ErrUnimplemented,"unimplemented operation")}}function sc(r){const e=[];for(const t of r){const n=ii(t);n&&e.push(n)}return e}function oi(r){const e=[];for(const t of r)e.push(wt.create({id:ni(t.id),operations:sc(t.operations),presenceChange:t.presenceChange?Za(t.presenceChange):void 0,message:t.message}));return e}function ic(r){return mt.of(N.fromString(r.serverSeq,!0),r.clientSeq)}function oc(r){return yn.create(r.documentKey,ic(r.checkpoint),r.isRemoved,oi(r.changes),r.snapshot,A(r.minSyncedTicket))}function ai(r){const e=new Bt;for(const n of r.nodes){const s=er(n.element);e.set(n.key,s,s.getPositionedAt())}const t=new re(A(r.createdAt),e);return t.setMovedAt(A(r.movedAt)),t.setRemovedAt(A(r.removedAt)),t}function ci(r){const e=new Ft;for(const n of r.nodes)e.insert(er(n.element));const t=new oe(A(r.createdAt),e);return t.setMovedAt(A(r.movedAt)),t.setRemovedAt(A(r.removedAt)),t}function ac(r){const e=L.of(L.valueFromBytes(ri(r.type),r.value),A(r.createdAt));return e.setMovedAt(A(r.movedAt)),e.setRemovedAt(A(r.removedAt)),e}function cc(r){const e=new bt;let t=e.getHead();for(const s of r.nodes){const i=e.insertAfter(t,ec(s));s.insPrevId&&i.setInsPrev(e.findNode(si(s.insPrevId))),t=i}const n=new he(e,A(r.createdAt));return n.setMovedAt(A(r.movedAt)),n.setRemovedAt(A(r.removedAt)),n}function uc(r){const e=ae.create(hn(r.type),ae.valueFromBytes(hn(r.type),r.value),A(r.createdAt));return e.setMovedAt(A(r.movedAt)),e.setRemovedAt(A(r.removedAt)),e}function ui(r){const e=Qn(r.nodes);return le.create(e,A(r.createdAt))}function er(r){if(r.body.case==="jsonObject")return ai(r.body.value);if(r.body.case==="jsonArray")return ci(r.body.value);if(r.body.case==="primitive")return ac(r.body.value);if(r.body.case==="text")return cc(r.body.value);if(r.body.case==="counter")return uc(r.body.value);if(r.body.case==="tree")return ui(r.body.value);throw new g(f.ErrUnimplemented,"unimplemented element")}function hc(r){if(!r)return{root:re.create(pe),presences:new Map};const e=Ko.fromBinary(r);return{root:er(e.root),presences:Qa(e.presences)}}function hi(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ai(e.body.value)}function li(r){return Xn(r).toBinary()}function lc(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ci(e.body.value)}function fc(r){return ei(r).toBinary()}function dc(r){if(!r)throw new g(f.ErrInvalidArgument,"bytes is empty");const e=fe.fromBinary(r);return ui(e.body.value)}function gc(r){return ti(r).toBinary()}function fi(r){return r?Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function tr(r){return fi(r)}function di(r){return new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function nr(r){return di(r)}function mc(r){const e=dn.fromBinary(r);return ni(e)}function pc(r){const e=zn.fromBinary(r);return ii(e)}const j={fromPresence:Zn,toChangePack:Xa,fromChangePack:oc,fromChanges:oi,toTreeNodes:Yn,fromTreeNodes:Qn,objectToBytes:li,bytesToObject:hi,bytesToSnapshot:hc,bytesToHex:fi,hexToBytes:di,toHexString:tr,toUint8Array:nr,toOperation:Qs,toChangeID:Ys,PbChangeID:dn,bytesToChangeID:mc,bytesToOperation:pc};var Q=(r=>(r[r.Trivial=0]="Trivial",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warn=3]="Warn",r[r.Error=4]="Error",r[r.Fatal=5]="Fatal",r))(Q||{});let et=3;function gi(r){et=r}const k={trivial:(...r)=>{et>0||typeof console<"u"&&console.log("YORKIE T:",...r)},debug:(...r)=>{et>1||typeof console<"u"&&console.log("YORKIE D:",...r)},info:(...r)=>{et>2||typeof console<"u"&&console.log("YORKIE I:",...r)},warn:(...r)=>{et>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...r):console.log("YORKIE W:",...r))},error:(...r)=>{et>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...r):console.log("YORKIE E:",...r))},fatal:(...r)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...r):console.log("YORKIE F:",...r))},isEnabled:r=>et<=r};function mi(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}class yc{constructor(e,t,n,s,i){l(this,"reconnectStreamDelay");l(this,"doc");l(this,"docID");l(this,"syncMode");l(this,"remoteChangeEventReceived");l(this,"watchStream");l(this,"watchLoopTimerID");l(this,"watchAbortController");l(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===sn.RealtimeSyncOff?!1:this.syncMode===sn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==sn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Cn=()=>{};class vc{constructor(e){l(this,"finalized",!1);l(this,"observers",[]);l(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let s;if(!e)throw new g(f.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(f.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:n},s.next===void 0&&(s.next=Cn),s.error===void 0&&(s.error=Cn),s.complete===void 0&&(s.complete=Cn);const i=mi(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){k.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class ft{constructor(e,t,n,s){l(this,"id");l(this,"delimiter");l(this,"message");l(this,"root");l(this,"operations");l(this,"presenceChange");l(this,"previousPresence");l(this,"reversePresenceKeys");this.id=e,this.delimiter=Wn,this.root=t,this.operations=[],this.previousPresence=de(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,n,s){return new ft(e,t,n,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return wt.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class $t{constructor(e){l(this,"rootObject");l(this,"elementPairMapByCreatedAt");l(this,"gcElementSetByCreatedAt");l(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof he||t instanceof le)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new $t(re.create(pe))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new g(f.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);n.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Ge&&e.getDescendants((n,s)=>(this.registerElement(n,s),!1))}deregisterElement(e){let t=0;const n=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return n(e),e instanceof Ge&&e.getDescendants(s=>(n(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof Ge&&n.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new $t(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(n);s.element.getRemovedAt()&&e.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,n]of this.gcPairMap){const s=n.child.getRemovedAt();s!==void 0&&e.compare(s)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function pi(r,e){const t=new _t(r);return new Proxy(e,t.getHandlers())}class _t{constructor(e){l(this,"context");l(this,"handlers");this.context=e,this.handlers={set:(t,n,s)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]=${JSON.stringify(s)}`),_t.setInternal(e,t,n,s),!0),get:(t,n)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():tt(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(k.isEnabled(Q.Trivial)&&k.trivial(`obj[${n}]`),_t.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,s){if(n.includes("."))throw new g(f.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=ln(e,s,i),a=t.set(n,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(ot.create(n,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const n={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new g(f.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=ln(e,i,o);n[s]=a}return n}static deleteInternal(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByKey(n,s);i&&(e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function wc(r,e){const t=new $(r,e);return new Proxy(e,t.getHandlers())}function bc(r){return typeof r=="string"||r instanceof String?!isNaN(r):!1}function Ac(r){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)}class ${constructor(e,t){l(this,"context");l(this,"handlers");l(this,"array");this.context=e,this.array=t,this.handlers={get:(n,s,i)=>s==="getID"?()=>n.getCreatedAt():s==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return Ve(e,a)}:s==="getElementByIndex"?o=>{const a=n.get(o);return Ve(e,a)}:s==="getLast"?()=>Ve(e,n.getLast()):s==="deleteByID"?o=>{const a=$.deleteInternalByID(e,n,o);return Ve(e,a)}:s==="insertAfter"?(o,a)=>{const c=$.insertAfterInternal(e,n,o,a);return Ve(e,c)}:s==="insertBefore"?(o,a)=>{const c=$.insertBeforeInternal(e,n,o,a);return Ve(e,c)}:s==="moveBefore"?(o,a)=>{$.moveBeforeInternal(e,n,o,a)}:s==="moveAfter"?(o,a)=>{$.moveAfterInternal(e,n,o,a)}:s==="moveFront"?o=>{$.moveFrontInternal(e,n,o)}:s==="moveLast"?o=>{$.moveLastInternal(e,n,o)}:bc(s)?tt(e,n.get(Number(s))):s==="push"?o=>$.pushInternal(e,n,o):s==="splice"?(o,a,...c)=>$.splice(e,n,o,a,...c):s==="length"?n.length:typeof s=="symbol"&&s===Symbol.iterator?$.iteratorInternal.bind(this,e,n):s==="includes"?(o,a)=>$.includes(e,n,o,a):s==="indexOf"?(o,a)=>$.indexOf(e,n,o,a):s==="lastIndexOf"?(o,a)=>$.lastIndexOf(e,n,o,a):s==="toJSForTest"?()=>n.toJSForTest():s==="toTestString"?()=>$.toTestString(n):typeof s=="string"&&Ac(s)?(...o)=>{const a=Array.from(n).map(c=>tt(e,c));return Array.prototype[s].apply(a,o)}:Reflect.get(n,s,i),deleteProperty:(n,s)=>(k.isEnabled(Q.Trivial)&&k.trivial(`array[${s}]`),$.deleteInternalByIndex(e,n,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield Ve(e,n)}static buildArrayElements(e,t){const n=[];for(const s of t){const i=e.issueTimeTicket(),o=ln(e,s,i);n.push(o)}return n}static pushInternal(e,t,n){return $.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,s,i),e.push(We.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,n,s){const i=e.issueTimeTicket();t.moveAfter(n,s,i),e.push(We.create(t.getCreatedAt(),n,s,i))}static moveFrontInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),n,s),e.push(We.create(t.getCreatedAt(),i.getCreatedAt(),n,s))}static moveLastInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,n,s),e.push(We.create(t.getCreatedAt(),i,n,s))}static insertAfterInternal(e,t,n,s){const i=e.issueTimeTicket(),o=ln(e,s,i);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Jt.create(t.getCreatedAt(),n,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,n,s){return $.insertAfterInternal(e,t,t.getPrevCreatedAt(n),s)}static deleteInternalByIndex(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByIndex(n,s);if(i)return e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,n){const s=e.issueTimeTicket(),i=t.delete(n,s);return e.push(Ze.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,n,s,...i){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),c=s===void 0?o:s<0?a:Math.min(a+s,o),u=[];for(let h=a;h=i)return!1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).includes(n,o);for(let c=o;c=i)return-1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).indexOf(n,o);for(let c=o;c=i?i-1:s<0?s+i:s;if(o<0)return-1;if(L.isSupport(n))return Array.from(t).map(u=>tt(e,u)).lastIndexOf(n,o);for(let c=o;c>0;c--)if(((a=t.get(c))==null?void 0:a.getID())===n.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class vn{constructor(e,t){l(this,"context");l(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,s){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);k.isEnabled(Q.Debug)&&k.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${n}`);const o=s?Tt(s):void 0,a=this.context.issueTimeTicket(),[c,,u,h]=this.text.edit(i,n,a,o);for(const p of u)this.context.registerGCPair(p);return this.context.push(new zt(this.text.getCreatedAt(),i[0],i[1],c,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(h)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);k.isEnabled(Q.Debug)&&k.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(n)}`);const i=Tt(n),o=this.context.issueTimeTicket(),[a,c]=this.text.setStyle(s,i,o);for(const u of c)this.context.registerGCPair(u);return this.context.push(new qt(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([ye.fromStruct(e[0]),ye.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new g(f.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class Tn{constructor(e,t){l(this,"valueType");l(this,"value");l(this,"context");l(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new g(f.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=L.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(At.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(f.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function rr(r,e,t){const{type:n}=r,s=t.issueTimeTicket();if(n===$e){yi(r);const{value:i}=r,o=ie.create(G.of(s,0),n,i);e.append(o)}else{const{children:i=[]}=r,{attributes:o}=r;let a;if(typeof o=="object"&&!qs(o)){const u=Tt(o);a=new Ue;for(const[h,p]of Object.entries(u))a.set(h,p,s)}const c=ie.create(G.of(s,0),n,void 0,a);e.append(c);for(const u of i)rr(u,c,t)}}function Ic(r,e){const{type:t}=e,n=r.issueTimeTicket();let s;if(e.type===$e){const{value:i}=e;s=ie.create(G.of(n,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!qs(o)){const c=Tt(o);a=new Ue;for(const[u,h]of Object.entries(c))a.set(u,h,n)}s=ie.create(G.of(r.issueTimeTicket(),0),t,void 0,a);for(const c of i)rr(c,s,r)}return s}function yi(r){if(!r.value.length)throw new g(f.ErrInvalidArgument,"text node cannot have empty value");return!0}function _r(r){if(!r.length)return!0;if(r[0].type===$e)for(const t of r){const{type:n}=t;if(n!==$e)throw new g(f.ErrInvalidArgument,"element node and text node cannot be passed together");yi(t)}else for(const t of r){const{type:n}=t;if(n===$e)throw new g(f.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class wn{constructor(e){l(this,"initialRoot");l(this,"context");l(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ie.create(G.of(e.issueTimeTicket(),0),Sa);const t=ie.create(G.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)rr(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const[n,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?Tt(t):void 0,[a]=this.tree.style([n,s],o,i);this.context.push(_e.create(this.tree.getCreatedAt(),n,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,n){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?Tt(n):void 0,[c,u]=this.tree.style([s,i],a,o);for(const h of u)this.context.registerGCPair(h);this.context.push(_e.create(this.tree.getCreatedAt(),s,i,c,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,c]=this.tree.removeStyle([s,i],n,o);for(const u of c)this.context.registerGCPair(u);this.context.push(_e.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,n,o))}editInternal(e,t,n,s=0){var u;if(n.length!==0&&n[0]&&(_r(n),n[0].type!==$e))for(const h of n){const{children:p=[]}=h;_r(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((u=n[0])==null?void 0:u.type)===$e){let h="";for(const p of n){const{value:v}=p;h+=v}o.push(ie.create(G.of(this.context.issueTimeTicket(),0),$e,h))}else o=n.map(h=>h&&Ic(this.context,h)).filter(h=>h);const[,a,c]=this.tree.edit([e,t],o.length?o.map(h=>h==null?void 0:h.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const h of a)this.context.registerGCPair(h);return this.context.push(Vt.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,c,i)),!0}editByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new g(f.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulkByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new g(f.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new g(f.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n,s)}edit(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulk(e,t,n,s=0){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new g(f.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n,s)}toXML(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[me.fromStruct(e[0]),me.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new g(f.ErrNotInitialized,"Tree is not initialized yet");const t=[me.fromStruct(e[0]),me.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Ur(r,e){return pi(r,e)}function Ve(r,e){if(e){if(e instanceof L)return e;if(e instanceof re)return pi(r,e);if(e instanceof oe)return wc(r,e);if(e instanceof he)return new vn(r,e);if(e instanceof ae){const t=new Tn(De.IntegerCnt,0);return t.initialize(r,e),t}else if(e instanceof le){const t=new wn;return t.initialize(r,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function tt(r,e){const t=Ve(r,e);return t instanceof L?t.getValue():t}function ln(r,e,t){let n;if(L.isSupport(e))n=L.of(e,t);else if(Array.isArray(e))n=oe.create(t,$.buildArrayElements(r,e));else if(typeof e=="object")e instanceof vn?(n=he.create(bt.create(),t),e.initialize(r,n)):e instanceof Tn?(n=ae.create(e.getValueType(),e.getValue(),t),e.initialize(r,n)):e instanceof wn?(n=le.create(e.buildRoot(r),t),e.initialize(r,n)):n=re.create(t,_t.buildObjectMembers(r,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Jr=50;class Sc{constructor(){l(this,"undoStack",[]);l(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Jr&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Jr&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const kc="yorkie-devtools-panel",Ec="yorkie-devtools-sdk";let ht="disconnected";const zr=new Map,rn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=rn);function Yt(r,e){(e!=null&&e.force||ht!=="disconnected")&&window.postMessage({source:Ec,...r},"*")}function Nc(r){if(!r.isEnableDevtools()||typeof window>"u"||zr.has(r.getKey()))return;rn.set(r.getKey(),[]);const e=r.subscribe("all",t=>{t.some(n=>n.type!==Z.StatusChanged&&n.type!==Z.Snapshot&&n.type!==Z.LocalChange&&n.type!==Z.RemoteChange&&n.type!==Z.Initialized&&n.type!==Z.Watched&&n.type!==Z.Unwatched&&n.type!==Z.PresenceChanged)||(rn.get(r.getKey()).push(t),ht==="synced"&&Yt({msg:"doc::sync::partial",docKey:r.getKey(),event:t}))});zr.set(r.getKey(),[e]),Yt({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==kc)return;switch(t.data.msg){case"devtools::connect":if(ht!=="disconnected")break;ht="connected",Yt({msg:"doc::available",docKey:r.getKey()}),k.info(`[YD] Devtools connected. Doc: ${r.getKey()}`);break;case"devtools::disconnect":ht="disconnected",k.info(`[YD] Devtools disconnected. Doc: ${r.getKey()}`);break;case"devtools::subscribe":ht="synced",Yt({msg:"doc::sync::full",docKey:r.getKey(),events:rn.get(r.getKey())}),k.info(`[YD] Devtools subscribed. Doc: ${r.getKey()}`);break}})}var Ke=(r=>(r.Detached="detached",r.Attached="attached",r.Removed="removed",r))(Ke||{}),Z=(r=>(r.StatusChanged="status-changed",r.ConnectionChanged="connection-changed",r.SyncStatusChanged="sync-status-changed",r.Snapshot="snapshot",r.LocalChange="local-change",r.RemoteChange="remote-change",r.Initialized="initialized",r.Watched="watched",r.Unwatched="unwatched",r.PresenceChanged="presence-changed",r.Broadcast="broadcast",r.LocalBroadcast="local-broadcast",r))(Z||{}),$n=(r=>(r.Connected="connected",r.Disconnected="disconnected",r))($n||{}),_n=(r=>(r.Synced="synced",r.SyncFailed="sync-failed",r))(_n||{});class vi{constructor(e,t){l(this,"key");l(this,"status");l(this,"opts");l(this,"changeID");l(this,"checkpoint");l(this,"localChanges");l(this,"root");l(this,"clone");l(this,"eventStream");l(this,"eventStreamObserver");l(this,"onlineClients");l(this,"presences");l(this,"history");l(this,"internalHistory");l(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=$t.create(),this.changeID=Da,this.checkpoint=Ra,this.localChanges=[],this.eventStream=Tc(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Sc,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Nc(this)}update(e,t){if(this.getStatus()==="removed")throw new g(f.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),s=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const i=Ur(s,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(i,new kn(s,this.clone.presences.get(n)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){k.isEnabled(Q.Trivial)&&k.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,M.Local),c=s.getReversePresence();c&&a.push({type:"presence",value:c}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const u=[];o.length>0&&u.push({type:"local-change",source:M.Local,value:{message:i.getMessage()||"",operations:o,actor:n,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&u.push({type:"presence-changed",source:M.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(u),k.isEnabled(Q.Trivial)&&k.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,s){if(typeof e=="string"){if(typeof t!="function")throw new g(f.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},n,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},n,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},n,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="connection-changed"&&a(u)},n,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="status-changed"&&a(u)},n,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="sync-status-changed"&&a(u)},n,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="local-broadcast"&&a(u)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const u of c)u.type==="broadcast"&&a(u)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const c of a){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const u=[];for(const h of c.value.operations)this.isSameElementOrChildOf(h.path,i)&&u.push(h);u.length&&o({...c,value:{...c.value,operations:u}})}},n,s)}if(typeof e=="function"){const i=e,o=t,a=n;return this.eventStream.subscribe(c=>{for(const u of c)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||i(u)},o,a)}throw new g(f.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((i,o)=>i===n[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),M.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,M.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),k.isEnabled(Q.Trivial)&&k.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:de(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return yn.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ur(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:s}=j.bytesToSnapshot(t);this.root=new $t(n),this.presences=s,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:M.Remote,value:{snapshot:this.isEnableDevtools()?j.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){k.isEnabled(Q.Debug)&&k.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),k.isEnabled(Q.Trivial)&&k.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` `));for(const n of e)this.applyChange(n,t);k.isEnabled(Q.Debug)&&k.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case Xe.Put:n.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:M.Remote,value:{clientID:s,presence:o.presence}});break;case Xe.Clear:n.push({type:"unwatched",source:M.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===M.Remote?{type:"remote-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const s of t)s!==this.changeID.getActorID()&&n.add(s);this.setOnlineClients(n),this.publish([{type:"initialized",source:M.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,s=[];if(t===Nt.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&s.push({type:"watched",source:M.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(t===Nt.DOCUMENT_UNWATCHED){const i=this.getPresence(n);this.removeOnlineClient(n),i&&s.push({type:"unwatched",source:M.Remote,value:{clientID:n,presence:i}})}else if(t===Nt.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:i,payload:o}=e.body.value.body,a=new TextDecoder;s.push({type:"broadcast",value:{clientID:n,topic:i,payload:JSON.parse(a.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(mn),this.publish([{source:e==="removed"?M.Remote:M.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n}=e.value;if(!t)return;this.applySnapshot(N.fromString(n),j.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=wt.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:s}of e.value)t.add(n),this.presences.set(n,s);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new g(f.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const s of t)if(n=n[s],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?de(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?de(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?de(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:de(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:de(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(f.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new g(f.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof ve)){new kn(t,de(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();u.setExecutedAt(h),t.push(u)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,M.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,M.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),c=[];s.length>0&&c.push({type:"local-change",source:M.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:M.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(c)}redo(){if(this.isUpdating)throw new g(f.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new g(f.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=ft.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof ve)){new kn(t,de(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();u.setExecutedAt(h),t.push(u)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,M.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,M.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),c=[];s.length>0&&c.push({type:"local-change",source:M.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:M.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const s={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([s])}}function Cc(r,e){return t=>async n=>(r&&n.header.set("x-api-key",r),e&&n.header.set("authorization",e),await t(n))}const xc="yorkie-js-sdk",Oc="0.5.0",Pc="Yorkie JS SDK",Dc="./src/yorkie.ts",Rc={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Bc=["dist"],Mc={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},Fc={node:">=18.0.0",npm:">=7.1.0"},Lc={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},$c={name:"hackerwins",email:"susukang98@gmail.com"},_c="Apache-2.0",Uc={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Jc="https://github.com/yorkie-team/yorkie-js-sdk#readme",zc={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},qc={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},qr={name:xc,version:Oc,description:Pc,main:Dc,publishConfig:Rc,files:Bc,scripts:Mc,engines:Fc,repository:Lc,author:$c,license:_c,bugs:Uc,homepage:Jc,devDependencies:zc,dependencies:qc};function Vc(){return r=>async e=>(e.header.set("x-yorkie-user-agent",qr.name+"/"+qr.version),await r(e))}const Kc=r=>{try{if(JSON.stringify(r)===void 0)return!1}catch{return!1}return!0};var sn=(r=>(r.Manual="manual",r.Realtime="realtime",r.RealtimePushOnly="realtime-pushonly",r.RealtimeSyncOff="realtime-syncoff",r))(sn||{});const Xt={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},xn={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ti{constructor(e,t){l(this,"id");l(this,"key");l(this,"status");l(this,"attachmentMap");l(this,"apiKey");l(this,"conditions");l(this,"syncLoopDuration");l(this,"reconnectStreamDelay");l(this,"retrySyncLoopDelay");l(this,"rpcClient");l(this,"taskQueue");l(this,"processing",!1);t=t||Xt,this.key=t.key?t.key:mi(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||Xt.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||Xt.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||Xt.retrySyncLoopDelay,this.rpcClient=Ao(da,Vo({baseUrl:e,interceptors:[Cc(t.apiKey,t.token),Vc()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),k.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw k.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),k.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw k.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Ke.Detached)throw new g(f.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((i,o)=>o.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async i=>{var h;const{topic:o,payload:a}=i.value,c=(h=i.options)==null?void 0:h.error,u=i.options;try{await this.broadcast(e.getKey(),o,a,u)}catch(p){p instanceof Error&&(c==null||c(p))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:j.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=j.fromChangePack(i.changePack);return e.applyChangePack(o),e.getStatus()===Ke.Removed||(e.applyStatus(Ke.Attached),this.attachmentMap.set(e.getKey(),new yc(this.reconnectStreamDelay,e,i.documentId,s,n)),s!=="manual"&&await this.runWatchLoop(e.getKey()),k.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(i=>{throw k.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new g(f.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:j.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==Ke.Removed&&e.applyStatus(Ke.Detached),this.detachInternal(e.getKey()),k.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw k.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new g(f.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const s=n.syncMode;return s===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new g(f.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw k.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw k.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new g(f.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=j.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),k.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw k.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,s){if(!this.isActive())throw new g(f.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new g(f.ErrDocumentNotAttached,`${e} is not attached`);if(!Kc(n))throw new g(f.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??xn.maxRetries,a=xn.maxBackoff;let c=0;const u=p=>Math.min(xn.initialRetryInterval*2**p,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{k.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(p=>{if(k.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(ch(),u(c-1)),k.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${o}`);else throw k.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const e=()=>{if(!this.isActive()){k.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{k.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};k.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new g(f.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new g(f.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:s.signal});return t.doc.publish([{type:Z.ConnectionChanged,value:$n.Connected}]),k.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const u of i)this.handleWatchDocumentsResponse(t,u),u.body.case==="initialization"&&o([i,s])}catch(u){t.doc.resetOnlineClients(),t.doc.publish([{type:Z.Initialized,source:M.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Z.ConnectionChanged,value:$n.Disconnected}]),k.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(u)?n():this.conditions.WatchLoop=!1,a(u)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Nt.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Ke.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:s}=e,i=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:j.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(o=>{const a=j.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(a),e.doc.publish([{type:Z.SyncStatusChanged,value:_n.Synced}]),n.getStatus()===Ke.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),u=a.getChangeSize();return k.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${i.getChangeSize()} pull:${u} cp:${a.getCheckpoint().toTestString()}`),n}).catch(o=>{throw n.publish([{type:Z.SyncStatusChanged,value:_n.SyncFailed}]),k.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof q?e.code===R.Canceled||e.code===R.Unknown||e.code===R.ResourceExhausted||e.code===R.Unavailable?!0:(($r(e)===f.ErrClientNotActivated||$r(e)===f.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{k.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Vr={Client:Ti,Document:vi,Primitive:L,Text:vn,Counter:Tn,Tree:wn,LogLevel:Q,setLogLevel:gi,IntType:De.IntegerCnt,LongType:De.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ti,Document:vi,Primitive:L,Text:vn,Counter:Tn,Tree:wn,LogLevel:Q,setLogLevel:gi,IntType:De.IntegerCnt,LongType:De.LongCnt});const Kr=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],jc=()=>{const r=Math.floor(Math.random()*Kr.length);return Kr[r]},jr=["red","yellow","orange","green","blue","purple"],Wc=()=>{const r=Math.floor(Math.random()*jr.length);return jr[r]};async function Gc(){const r=new Vr.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await r.activate();const e=new Vr.Document("profile-stack",{enableDevtools:!0});e.subscribe("presence",t=>{t.type!==Z.PresenceChanged&&Hc(e.getPresences(),r.getID())}),await r.attach(e,{initialPresence:{name:jc(),color:Wc()}}),window.addEventListener("beforeunload",()=>{r.deactivate()})}const On=4,Pn=(r,e,t)=>{const n=document.createElement("div");return n.className="peer",t==="main"?n.innerHTML=`
    profile diff --git a/examples/profile-stack/index.html b/examples/profile-stack/index.html index 60c8821a9..d5ea98abd 100644 --- a/examples/profile-stack/index.html +++ b/examples/profile-stack/index.html @@ -5,7 +5,7 @@ Profile Stack - Yorkie Example - + diff --git a/examples/react-tldraw/assets/index-CTWj4U59.js b/examples/react-tldraw/assets/index-RCvbs4LD.js similarity index 91% rename from examples/react-tldraw/assets/index-CTWj4U59.js rename to examples/react-tldraw/assets/index-RCvbs4LD.js index 211fb753f..8e7376750 100644 --- a/examples/react-tldraw/assets/index-CTWj4U59.js +++ b/examples/react-tldraw/assets/index-RCvbs4LD.js @@ -547,7 +547,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert- * * SPDX-License-Identifier: Apache-2.0 */var di=null;try{di=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function je(e,t,n){this.low=e|0,this.high=t|0,this.unsigned=!!n}je.prototype.__isLong__;Object.defineProperty(je.prototype,"__isLong__",{value:!0});function Yn(e){return(e&&e.__isLong__)===!0}function Ew(e){var t=Math.clz32(e&-e);return e?31-t:t}je.isLong=Yn;var Cw={},bw={};function Au(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=bw[e],r)?r:(n=lt(e,0,!0),i&&(bw[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=Cw[e],r)?r:(n=lt(e,e<0?-1:0,!1),i&&(Cw[e]=n),n))}je.fromInt=Au;function hi(e,t){if(isNaN(e))return t?na:zi;if(t){if(e<0)return na;if(e>=VI)return JI}else{if(e<=-Sw)return yr;if(e+1>=Sw)return WI}return e<0?hi(-e,t).neg():lt(e%Jl|0,e/Jl|0,t)}je.fromNumber=hi;function lt(e,t,n){return new je(e,t,n)}je.fromBits=lt;var Dp=Math.pow;function Ny(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?na:zi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return Ny(e.substring(1),t,n).neg();for(var i=hi(Dp(n,8)),o=zi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Jl+(this.low>>>0):this.high*Jl+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,f=d.toString(t);if(a=u,a.isZero())return f+s;for(;f.length<6;)f="0"+f;s=""+f+s}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(yr)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,n=31;n>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return Yn(t)||(t=eo(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(Yn(t)||(t=eo(t)),this.eq(t))return 0;var n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(yr)?yr:this.not().add(gl)};he.neg=he.negate;he.add=function(t){Yn(t)||(t=eo(t));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=t.high>>>16,s=t.high&65535,u=t.low>>>16,d=t.low&65535,f=0,p=0,g=0,m=0;return m+=o+d,g+=m>>>16,m&=65535,g+=i+u,p+=g>>>16,g&=65535,p+=r+s,f+=p>>>16,p&=65535,f+=n+a,f&=65535,lt(g<<16|m,f<<16|p,this.unsigned)};he.subtract=function(t){return Yn(t)||(t=eo(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(Yn(t)||(t=eo(t)),di){var n=di.mul(this.low,this.high,t.low,t.high);return lt(n,di.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?na:zi;if(this.eq(yr))return t.isOdd()?yr:zi;if(t.eq(yr))return this.isOdd()?yr:zi;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(xw)&&t.lt(xw))return hi(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,o=this.low>>>16,a=this.low&65535,s=t.high>>>16,u=t.high&65535,d=t.low>>>16,f=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*f,m+=v>>>16,v&=65535,m+=o*f,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*f,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*f+i*d+o*u+a*s,p&=65535,lt(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(Yn(t)||(t=eo(t)),t.isZero())throw Error("division by zero");if(di){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var n=(this.unsigned?di.div_u:di.div_s)(this.low,this.high,t.low,t.high);return lt(n,di.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?na:zi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return na;if(t.gt(this.shru(1)))return GI;o=na}else{if(this.eq(yr)){if(t.eq(gl)||t.eq(v2))return yr;if(t.eq(yr))return gl;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(zi)?t.isNegative()?gl:v2:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?na:zi;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=zi}for(i=this;i.gte(t);){r=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(r)/Math.LN2),u=s<=48?1:Dp(2,s-48),d=hi(r),f=d.mul(t);f.isNegative()||f.gt(i);)r-=u,d=hi(r,this.unsigned),f=d.mul(t);d.isZero()&&(d=gl),o=o.add(d),i=i.sub(f)}return o};he.div=he.divide;he.modulo=function(t){if(Yn(t)||(t=eo(t)),di){var n=(this.unsigned?di.rem_u:di.rem_s)(this.low,this.high,t.low,t.high);return lt(n,di.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return lt(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?Ew(this.low):Ew(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return Yn(t)||(t=eo(t)),lt(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return Yn(t)||(t=eo(t)),lt(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return Yn(t)||(t=eo(t)),lt(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return Yn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?lt(this.low<>>32-t,this.unsigned):lt(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):lt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return Yn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?lt(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?lt(this.high,0,this.unsigned):lt(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var n;return Yn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?lt(this.high,this.low,this.unsigned):t<32?(n=32-t,lt(this.low<>>n,this.high<>>n,this.unsigned)):(t-=32,n=32-t,lt(this.high<>>n,this.low<>>n,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var n;return Yn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?lt(this.high,this.low,this.unsigned):t<32?(n=32-t,lt(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,n=32-t,lt(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?lt(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:lt(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};je.fromBytes=function(t,n,r){return r?je.fromBytesLE(t,n):je.fromBytesBE(t,n)};je.fromBytesLE=function(t,n){return new je(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};je.fromBytesBE=function(t,n){return new je(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};const Kje=J.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);J.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:ea}]);J.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);J.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:Vje,repeated:!0}]);const Vje=J.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});J.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:Gje,repeated:!0}]);const Gje=J.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});J.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:Wje,repeated:!0}]);const Wje=J.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});J.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);J.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);J.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:Jje,repeated:!0}]);const Jje=J.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});J.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var W=(e=>(e.Ok="ok",e.ErrClientNotActivated="ErrClientNotActivated",e.ErrClientNotFound="ErrClientNotFound",e.ErrUnimplemented="ErrUnimplemented",e.ErrInvalidType="ErrInvalidType",e.ErrDummy="ErrDummy",e.ErrDocumentNotAttached="ErrDocumentNotAttached",e.ErrDocumentNotDetached="ErrDocumentNotDetached",e.ErrDocumentRemoved="ErrDocumentRemoved",e.ErrInvalidObjectKey="ErrInvalidObjectKey",e.ErrInvalidArgument="ErrInvalidArgument",e.ErrNotInitialized="ErrNotInitialized",e.ErrNotReady="ErrNotReady",e.ErrRefused="ErrRefused",e.ErrContextNotProvided="ErrContextNotProvided",e))(W||{});class Y extends Error{constructor(n,r){super(r);j(this,"name","YorkieError");j(this,"stack");this.code=n,this.message=r,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function Fi(e){if(e instanceof Map){const t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}const YI=e=>e?Object.entries(e).length===0:!0,Yl=e=>{const t={};for(const[n,r]of Object.entries(e))t[n]=JSON.stringify(r);return t},Il=e=>{const t={};for(const[n,r]of Object.entries(e))t[n]=JSON.parse(r);return t};var vs=(e=>(e.Put="put",e.Clear="clear",e))(vs||{});class S4{constructor(t,n){j(this,"context");j(this,"presence");this.context=t,this.presence=n}set(t,n){for(const r of Object.keys(t))this.presence[r]=t[r];this.context.setPresenceChange({type:"put",presence:Fi(this.presence)}),this.context.setReversePresence(t,n)}get(t){return this.presence[t]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const zg="000000000000000000000000",Yje="FFFFFFFFFFFFFFFFFFFFFFFF";class wr{constructor(t,n,r){j(this,"lamport");j(this,"delimiter");j(this,"actorID");this.lamport=t,this.delimiter=n,this.actorID=r}static of(t,n,r){return new wr(t,n,r)}static fromStruct(t){return wr.of(je.fromString(t.lamport,!0),t.delimiter,t.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(t){return new wr(this.lamport,this.delimiter,t)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(t){return this.compare(t)>0}equals(t){return this.compare(t)===0}compare(t){if(this.lamport.greaterThan(t.lamport))return 1;if(t.lamport.greaterThan(this.lamport))return-1;const n=this.actorID.localeCompare(t.actorID);return n!==0?n:this.delimiter>t.delimiter?1:t.delimiter>this.delimiter?-1:0}}const zy=0,Xje=4294967295,Zje=je.MAX_VALUE,Vi=new wr(je.fromNumber(0),zy,zg);new wr(je.fromNumber(1),zy+1,zg);const Ed=new wr(Zje,Xje,Yje);function ko(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(t){switch(t){case'"':case"\\":return"\\"+t;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return t}})}class b0{constructor(t){j(this,"createdAt");j(this,"movedAt");j(this,"removedAt");this.createdAt=t}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(t){return!this.movedAt||t&&t.after(this.movedAt)?(this.movedAt=t,!0):!1}setRemovedAt(t){this.removedAt=t}remove(t){return t&&t.after(this.getPositionedAt())&&(!this.removedAt||t.after(this.removedAt))?(this.removedAt=t,!0):!1}isRemoved(){return!!this.removedAt}}class as extends b0{constructor(t){super(t)}}class Hy{constructor(t,n){j(this,"strKey");j(this,"value");this.strKey=t,this.value=n}static of(t,n){return new Hy(t,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(t){return this.value.remove(t)}}class Yd{constructor(){j(this,"nodeMapByKey");j(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Yd}set(t,n,r){let i;const o=this.nodeMapByKey.get(t);o!=null&&!o.isRemoved()&&o.remove(r)&&(i=o.getValue());const a=Hy.of(t,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),a),(o==null||r.after(o.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(t,a),n.setMovedAt(r)),i}delete(t,n){if(!this.nodeMapByCreatedAt.has(t.toIDString()))throw new Y(W.ErrInvalidArgument,`fail to find ${t.toIDString()}`);const r=this.nodeMapByCreatedAt.get(t.toIDString());return r.remove(n),r.getValue()}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return n.getStrKey()}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find ${t.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(t,n){const r=this.nodeMapByKey.get(t);if(r!=null&&r.remove(n))return r.getValue()}has(t){const n=this.nodeMapByKey.get(t);return n==null?!1:!n.isRemoved()}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}get(t){const n=this.nodeMapByKey.get(t);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,t]of this.nodeMapByKey)yield t}}class Sr extends as{constructor(n,r){super(n);j(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new Sr(n,Yd.create());const i=Yd.create();for(const[o,a]of Object.entries(r))i.set(o,a.deepcopy(),a.getCreatedAt());return new Sr(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${ko(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:o,value:a,type:s}=i.toJSForTest();n[r]={key:r,createdAt:o,value:a,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[o]of this)n.push(o);const r=[];for(const o of n.sort()){const a=(i=this.memberNodes.get(o))==null?void 0:i.getValue();r.push(`"${ko(o)}":${a.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=Sr.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof as&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var St=(e=>(e.Local="local",e.Remote="remote",e.UndoRedo="undoredo",e))(St||{});class Zi{constructor(t,n){j(this,"parentCreatedAt");j(this,"executedAt");this.parentCreatedAt=t,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new Y(W.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(t){this.executedAt&&(this.executedAt=this.executedAt.setActor(t))}setExecutedAt(t){this.executedAt=t}}class XI{constructor(t){j(this,"value");j(this,"left");j(this,"right");j(this,"parent");j(this,"weight");this.value=t,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(t){this.left=t}setRight(t){this.right=t}setParent(t){this.parent=t}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(t){this.weight+=t}initWeight(){this.weight=this.getLength()}}class Xd{constructor(t){j(this,"root");this.root=t}get length(){return this.root?this.root.getWeight():0}find(t){if(!this.root||t<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&t<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new Y(W.ErrInvalidArgument,`out of index range: pos: ${t} > node.length: ${n.getLength()}`);return[n,t]}indexOf(t){if(!t||t!==this.root&&!t.hasLinks())return-1;let n=0,r=t,i;for(;r;)(!i||i===r.getRight())&&(n+=r.getLength()+(r.hasLeft()?r.getLeftWeight():0)),i=r,r=r.getParent();return n-t.getLength()}getRoot(){return this.root}insert(t){return this.insertAfter(this.root,t)}insertAfter(t,n){return t?(this.splayNode(t),this.root=n,n.setRight(t.getRight()),t.hasRight()&&t.getRight().setParent(n),n.setLeft(t),t.setParent(n),t.setRight(),this.updateWeight(t),this.updateWeight(n),n):(this.root=n,n)}updateWeight(t){t.initWeight(),t.hasLeft()&&t.increaseWeight(t.getLeftWeight()),t.hasRight()&&t.increaseWeight(t.getRightWeight())}updateTreeWeight(t){for(;t;)this.updateWeight(t),t=t.getParent()}splayNode(t){if(t)for(;;)if(this.isLeftChild(t.getParent())&&this.isRightChild(t))this.rotateLeft(t),this.rotateRight(t);else if(this.isRightChild(t.getParent())&&this.isLeftChild(t))this.rotateRight(t),this.rotateLeft(t);else if(this.isLeftChild(t.getParent())&&this.isLeftChild(t))this.rotateRight(t.getParent()),this.rotateRight(t);else if(this.isRightChild(t.getParent())&&this.isRightChild(t))this.rotateLeft(t.getParent()),this.rotateLeft(t);else{this.isLeftChild(t)?this.rotateRight(t):this.isRightChild(t)&&this.rotateLeft(t),this.updateWeight(t);return}}delete(t){this.splayNode(t);const n=new Xd(t.getLeft());n.root&&n.root.setParent();const r=new Xd(t.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;t.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(t,n){if(!n){this.splayNode(t),this.cutOffRight(t);return}this.splayNode(t),this.splayNode(n),n.getLeft()!=t&&this.rotateRight(t),this.cutOffRight(t)}cutOffRight(t){const n=[];this.traversePostorder(t.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(t)}toTestString(){const t=[];return this.traverseInorder(this.root,t),t.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const t=[];this.traverseInorder(this.root,t);for(const n of t)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let t=this.root;for(;t.hasRight();)t=t.getRight();return t}traverseInorder(t,n){t&&(this.traverseInorder(t.getLeft(),n),n.push(t),this.traverseInorder(t.getRight(),n))}traversePostorder(t,n){t&&(this.traversePostorder(t.getLeft(),n),this.traversePostorder(t.getRight(),n),n.push(t))}rotateLeft(t){const n=t.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(t):n.getParent().setRight(t):this.root=t,t.setParent(n.getParent()),n.setRight(t.getLeft()),n.hasRight()&&n.getRight().setParent(n),t.setLeft(n),t.getLeft().setParent(t),this.updateWeight(n),this.updateWeight(t)}rotateRight(t){const n=t.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(t):n.getParent().setRight(t):this.root=t,t.setParent(n.getParent()),n.setLeft(t.getRight()),n.hasLeft()&&n.getLeft().setParent(n),t.setRight(n),t.getRight().setParent(t),this.updateWeight(n),this.updateWeight(t)}isLeftChild(t){return t&&t.hasParent()?t.getParent().getLeft()===t:!1}isRightChild(t){return t&&t.hasParent()?t.getParent().getRight()===t:!1}}var yn=(e=>(e[e.Null=0]="Null",e[e.Boolean=1]="Boolean",e[e.Integer=2]="Integer",e[e.Long=3]="Long",e[e.Double=4]="Double",e[e.String=5]="String",e[e.Bytes=6]="Bytes",e[e.Date=7]="Date",e))(yn||{});class Kt extends b0{constructor(n,r){super(r);j(this,"valueType");j(this,"value");this.valueType=Kt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Kt(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(o,a){i.setUint8(a,o)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return je.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(je.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${ko(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Kt.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof je)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Kt.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=je.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Ip extends XI{constructor(n){super(n);j(this,"prev");j(this,"next");this.value=n}static createAfter(n,r){const i=new Ip(r),o=n.next;return n.next=i,i.prev=n,i.next=o,o&&(o.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Zd{constructor(){j(this,"dummyHead");j(this,"last");j(this,"nodeMapByIndex");j(this,"nodeMapByCreatedAt");const t=Kt.of(0,Vi);t.setRemovedAt(Vi),this.dummyHead=new Ip(t),this.last=this.dummyHead,this.nodeMapByIndex=new Xd,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Zd}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=Ip.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class jr extends as{constructor(n,r){super(n);j(this,"elements");this.elements=r}static create(n,r){if(!r)return new jr(n,Zd.create());const i=Zd.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new jr(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof as&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:Il(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,f,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),f=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):Vi:Ed;if(m.canStyle(i,E)){const w=f.get(v),C=m.getCreatedAt();(!w||C.after(w))&&f.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:Il(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[f,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Il(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new yi(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class S0 extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"content");j(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.content=a,this.attributes=s}static create(n,r,i,o,a,s,u){return new S0(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof yi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class x0 extends Zi{constructor(n,r,i,o,a,s){super(n,s);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new x0(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof yi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const qje=2,Qje="root",sa="text";function Gc(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===sa}get paddedSize(){return this.size+(this.isText?0:qje)}isAncestorOf(t){return tUe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function tUe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var rn=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(rn||{});function ZI(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),ZI(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function qI(e,t,n=0){for(const r of e.children)qI(r,t,n+1);t(e,n)}function Hg(e,t,n=0){for(const r of e._children)Hg(r,t,n+1);t(e,n)}function y2(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return y2(o,t-i,n);if(t===i)return{node:e,offset:r};if(!n&&o.paddedSize===t-i)return{node:e,offset:r+1};if(o.paddedSize>t-i)return y2(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function QI(e){return e.isText||e.children.length===0?e:QI(e.children[0])}function nUe(e,t){if(e.sizee===t?0:e0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,o=n;for(;i&&o===i.left;)o=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,n){for(;n;){const r=this.comparator(t,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(t,n,r){if(!r)return this.counter+=1,new oUe(t,n,!0);const i=this.comparator(t,r.key);return i<0?r.left=this.putInternal(t,n,r.left):i>0?r.right=this.putInternal(t,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,n){if(this.comparator(n,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,n);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(n,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(n,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,n)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const n=t.right;return t.right=n.left,n.left=t,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(t){const n=t.left;return t.left=n.right,n.right=t,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Hi{constructor(t,n){j(this,"parentID");j(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Hi(t,n)}static fromTreePos(t){const{offset:n}=t;let{node:r}=t,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Hi.of(r.id,$n.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Hi.of($n.of(wr.fromStruct(t.parentID.createdAt),t.parentID.offset),$n.of(wr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class $n{constructor(t,n){j(this,"createdAt");j(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new $n(t,n)}static fromStruct(t){return $n.of(wr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr($n.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr($n.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new va);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function E2(e){var n;if(e.isText){const r=e;return{type:r.type,value:r.value}}const t={type:e.type,children:e.children.map(E2)};return e.attrs&&(t.attributes=Il((n=e.attrs)==null?void 0:n.toObject())),t}function jy(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${ko(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>jy(n)).join("")}`}function tT(e){if(e.isText){const t=e;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:e.type,children:e.children.map(tT),size:e.size,isRemoved:e.isRemoved}}class Ei extends b0{constructor(n,r){super(r);j(this,"indexTree");j(this,"nodeMapByID");this.indexTree=new rUe(n),this.nodeMapByID=new eT($n.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Ei(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,f=s?0:d.indexOf(a)+1;for(let p=f;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):Vi:Ed;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const A=v.setAttrs(r,i),D=A.reduce((k,[,B])=>(B&&(k[B.getKey()]=p[B.getKey()]),k),{}),P=v.parent,I=v.prevSibling||v.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(P,I),to:this.toIndex(v,v),fromPath:this.toPath(P,I),toPath:this.toPath(v,v),actor:i.getActorID(),value:D});for(const[k]of A)k&&m.push({parent:v,child:k})}}),[g,m,f]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),f=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):Vi:Ed;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new va);for(const D of r){const P=m.attrs.remove(D,i);for(const I of P)g.push({parent:m,child:I})}const b=m.parent,A=m.prevSibling||m.parent;f.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,A),to:this.toIndex(m,m),fromPath:this.toPath(b,A),toPath:this.toPath(m,m),value:r})}}),[p,g,f]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[f,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,f,p,([D,P],I)=>{if(P===rn.Start&&!I)for(const _ of D.children)w.push(_);const k=D.getCreatedAt().getActorID(),B=s?s.has(k)?s.get(k):Vi:Ed;if(D.canDelete(o,B)||v.includes(D.parent)){const _=C.get(k),N=D.getCreatedAt();(!_||N.after(_))&&C.set(k,N),(P===rn.Text||P===rn.Start)&&v.push(D),E.push([D,P])}});const b=this.makeDeletionChanges(E,o),A=[];for(const D of v)D.remove(o),D.isRemoved&&A.push({parent:this,child:D});for(const D of w)D.removedAt||u.append(D);if(i>0){let D=0,P=u,I=d;for(;D{u.isRemoved&&(k.remove(o),A.push({parent:this,child:k})),this.nodeMapByID.put(k.id,k)}),I.isRemoved||D.push(I);if(D.length){const I=D.map(k=>E2(k));b.length&&b[b.length-1].from===g?b[b.length-1].value=I:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:I})}}return[b,A,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Hi.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return jy(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,f;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),f=Hi.fromTreePos(p).toStruct());const g={type:i.type,parent:o==null?void 0:o.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(E=i.insNextID)==null?void 0:E.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:s,attributes:i.attrs?Il((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:f};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===rn.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?rn.Text:rn.Start]:[n,rn.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,rn.End];const s=o[a+1];return[s,s.isText?rn.Text:rn.Start]}findLeftToken([n,r]){if(r===rn.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?rn.Text:rn.End]}return[n,rn.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,rn.Start];const s=o[a-1];return[s,s.isText?rn.Text:rn.End]}}class A0 extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"contents");j(this,"splitLevel");j(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=o,this.splitLevel=a,this.maxCreatedAtMapByActor=s}static create(n,r,i,o,a,s,u){return new A0(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ei))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>wr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>jy(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Wa{constructor(t,n,r,i){j(this,"clientSeq");j(this,"serverSeq");j(this,"lamport");j(this,"actor");this.clientSeq=t,this.serverSeq=i,this.lamport=n,this.actor=r}static of(t,n,r,i){return new Wa(t,n,r,i)}next(){return new Wa(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(t){return t.greaterThan(this.lamport)?new Wa(this.clientSeq,t,this.actor):new Wa(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(t){return wr.of(this.lamport,t,this.actor)}setActor(t){return new Wa(this.clientSeq,this.lamport,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const sUe=new Wa(0,je.fromInt(0,!0),zg);class Xl{constructor({id:t,operations:n,presenceChange:r,message:i}){j(this,"id");j(this,"operations");j(this,"presenceChange");j(this,"message");this.id=t,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:t,operations:n,presenceChange:r,message:i}){return new Xl({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===vs.Put?n.set(this.id.getActorID(),Fi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:En.bytesToHex(En.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>En.bytesToHex(En.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return Xl.create({id:En.bytesToChangeID(En.hexToBytes(n)),operations:r==null?void 0:r.map(a=>En.bytesToOperation(En.hexToBytes(a))),presenceChange:i,message:o})}}class jg{constructor(t,n,r,i,o,a){j(this,"documentKey");j(this,"checkpoint");j(this,"isRemoved");j(this,"changes");j(this,"snapshot");j(this,"minSyncedTicket");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a}static create(t,n,r,i,o,a){return new jg(t,n,r,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Tl{constructor(t,n){j(this,"serverSeq");j(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new Tl(t,n)}increaseClientSeq(t){return t===0?this:new Tl(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq.greaterThan(t.serverSeq)?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Tl.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq.equals(t.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const uUe=new Tl(je.fromInt(0,!0),0);class To{constructor(t,n){j(this,"createdAt");j(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new To(t,n)}static fromStruct(t){return To.of(wr.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new To(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const lUe=To.of(Vi,0);class Gi{constructor(t,n){j(this,"id");j(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new Gi(t,n)}static fromStruct(t){const n=To.fromStruct(t.id);return Gi.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return To.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class ss extends XI{constructor(n,r,i){super(r);j(this,"id");j(this,"removedAt");j(this,"prev");j(this,"next");j(this,"insPrev");j(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new ss(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const f=d.getCreatedAt().getActorID();(!a.has(f)||d.getID().getCreatedAt().after(a.get(f)))&&a.set(f,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const f=d.getCreatedAt().getActorID(),p=i?r.has(f)?r.get(f):Vi:Ed;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var $o=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))($o||{});class Ur extends b0{constructor(n,r,i){super(i);j(this,"valueType");j(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=je.fromNumber(r).toInt():this.value=Aw(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=je.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Ur(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return je.fromBytesLE(Array.from(r));default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Ur.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof je?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!Ur.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===yn.Long?this.value=this.value+n.getValue().toInt():this.value=je.fromNumber(this.value+Aw(n.getValue())).toInt(),this}}class ql extends Zi{constructor(n,r,i){super(n,i);j(this,"value");this.value=r}static create(n,r,i){return new ql(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ur))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===yn.Long?n.getValue().multiply(-1):n.getValue()*-1;return ql.create(this.getParentCreatedAt(),Kt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ua extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"attributes");j(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a,this.attributesToRemove=s}static create(n,r,i,o,a,s){return new ua(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ua(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ei))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:f,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:f,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function cUe(e){const t=new Ly,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function dUe(e){if(e.type===vs.Put)return new m2({type:Jd.PUT,presence:cUe(e.presence)});if(e.type===vs.Clear)return new m2({type:Jd.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function hUe(e){return new KI({serverSeq:e.getServerSeqAsString(),clientSeq:e.getClientSeq()})}function nT(e){return new Lg({clientSeq:e.getClientSeq(),lamport:e.getLamportAsString(),actorId:Yy(e.getActorID())})}function De(e){if(e)return new Te({lamport:e.getLamportAsString(),delimiter:e.getDelimiter(),actorId:Yy(e.getActorID())})}function rT(e){switch(e){case yn.Null:return We.NULL;case yn.Boolean:return We.BOOLEAN;case yn.Integer:return We.INTEGER;case yn.Long:return We.LONG;case yn.Double:return We.DOUBLE;case yn.String:return We.STRING;case yn.Bytes:return We.BYTES;case yn.Date:return We.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function iT(e){switch(e){case $o.IntegerCnt:return We.INTEGER_CNT;case $o.LongCnt:return We.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function x4(e){if(e instanceof Sr)return new Xo({type:We.JSON_OBJECT,createdAt:De(e.getCreatedAt()),value:vT(e)});if(e instanceof jr)return new Xo({type:We.JSON_ARRAY,createdAt:De(e.getCreatedAt()),value:HUe(e)});if(e instanceof yi)return new Xo({type:We.TEXT,createdAt:De(e.getCreatedAt())});if(e instanceof Kt)return new Xo({type:rT(e.getType()),createdAt:De(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ur)return new Xo({type:iT(e.getType()),createdAt:De(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ei)return new Xo({type:We.TREE,createdAt:De(e.getCreatedAt()),value:UUe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function fUe(e){return new g2({createdAt:De(e.getCreatedAt()),offset:e.getOffset()})}function sf(e){return new gu({createdAt:De(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function uf(e){return new Wd({parentId:Cd(e.getParentID()),leftSiblingId:Cd(e.getLeftSiblingID())})}function Cd(e){return new Dl({createdAt:De(e.getCreatedAt()),offset:e.getOffset()})}function oT(e){const t=new _y;if(e instanceof mu){const n=e,r=new kI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.key=n.getKey(),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof w0){const n=e,r=new DI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.prevCreatedAt=De(n.getPrevCreatedAt()),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof Xa){const n=e,r=new II;r.parentCreatedAt=De(n.getParentCreatedAt()),r.prevCreatedAt=De(n.getPrevCreatedAt()),r.createdAt=De(n.getCreatedAt()),r.executedAt=De(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof ys){const n=e,r=new TI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.createdAt=De(n.getCreatedAt()),r.executedAt=De(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof S0){const n=e,r=new PI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=sf(n.getFromPos()),r.to=sf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=De(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof x0){const n=e,r=new MI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=sf(n.getFromPos()),r.to=sf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=De(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof ql){const n=e,r=new BI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof A0){const n=e,r=new $I,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=De(a);r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=uf(n.getFromPos()),r.to=uf(n.getToPos()),r.contents=CUe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=De(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ua){const n=e,r=new RI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=uf(n.getFromPos()),r.to=uf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);const o=n.getAttributesToRemove();if(o.length>0)r.attributesToRemove=o;else{const a=r.attributes;for(const[s,u]of n.getAttributes())a[s]=u}r.executedAt=De(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(W.ErrUnimplemented,"unimplemented operation");return t}function pUe(e){const t=[];for(const n of e)t.push(oT(n));return t}function gUe(e){const t=new AI({id:nT(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=pUe(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=dUe(e.getPresenceChange())),t}function mUe(e){const t=[];for(const n of e)t.push(gUe(n));return t}function vUe(e){const t=[];for(const n of e)t.push(new HI({key:n.getStrKey(),element:Ky(n.getValue())}));return t}function yUe(e){const t=[];for(const n of e)t.push(new Fy({element:Ky(n.getValue())}));return t}function EUe(e){const t=[];for(const n of e){const r=new jI;r.id=fUe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=De(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new Ng;s.value=a.getValue(),s.updatedAt=De(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function CUe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new UI({content:Uy(n)}));return t}function bUe(e){const t={};for(const n of e)t[n.getKey()]=new Ng({value:n.getValue(),updatedAt:De(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function Uy(e){if(!e)return[];const t=[];return Hg(e,(n,r)=>{const i=new Oy({id:Cd(n.id),type:n.type,removedAt:De(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=Cd(n.insPrevID)),n.insNextID&&(i.insNextId=Cd(n.insNextID)),n.attrs&&(i.attributes=bUe(n.attrs)),t.push(i)}),t}function wUe(e){const t=new Si;return t.body.case="jsonObject",t.body.value=new _I({nodes:vUe(e.getRHT()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function aT(e){const t=new Si;return t.body.case="jsonArray",t.body.value=new FI({nodes:yUe(e.getElements()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function SUe(e){const t=new Si;return t.body.case="primitive",t.body.value=new OI({type:rT(e.getType()),value:e.toBytes(),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function xUe(e){const t=new Si;return t.body.case="text",t.body.value=new LI({nodes:EUe(e.getRGATreeSplit()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function AUe(e){const t=new Si;return t.body.case="counter",t.body.value=new NI({type:iT(e.getType()),value:e.toBytes(),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function sT(e){const t=new Si;return t.body.case="tree",t.body.value=new zI({nodes:Uy(e.getRoot()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function Ky(e){if(e instanceof Sr)return wUe(e);if(e instanceof jr)return aT(e);if(e instanceof Kt)return SUe(e);if(e instanceof yi)return xUe(e);if(e instanceof Ur)return AUe(e);if(e instanceof Ei)return sT(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function kUe(e){return new Sa({documentKey:e.getDocumentKey(),checkpoint:hUe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:mUe(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:De(e.getMinSyncedTicket())})}function kw(e){const t=e.findDetails(Kje);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function uT(e){let t;return e.serverSeq&&(t=je.fromString(e.serverSeq,!0)),Wa.of(e.clientSeq,je.fromString(e.lamport,!0),Jy(e.actorId),t)}function Ie(e){if(e)return wr.of(je.fromString(e.lamport,!0),e.delimiter,Jy(e.actorId))}function Vy(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function DUe(e){const t=e.type;if(t===Jd.PUT){const n=Vy(e.presence);return{type:vs.Put,presence:n}}if(t===Jd.CLEAR)return{type:vs.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function IUe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,Vy(r))}),t}function lT(e){switch(e){case We.NULL:return yn.Null;case We.BOOLEAN:return yn.Boolean;case We.INTEGER:return yn.Integer;case We.LONG:return yn.Long;case We.DOUBLE:return yn.Double;case We.STRING:return yn.String;case We.BYTES:return yn.Bytes;case We.DATE:return yn.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function Tp(e){switch(e){case We.INTEGER_CNT:return $o.IntegerCnt;case We.LONG_CNT:return $o.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function A4(e){switch(e.type){case We.JSON_OBJECT:return e.value?mT(e.value):Sr.create(Ie(e.createdAt));case We.JSON_ARRAY:return e.value?zUe(e.value):jr.create(Ie(e.createdAt));case We.TEXT:return yi.create(Zl.create(),Ie(e.createdAt));case We.TREE:return jUe(e.value);case We.NULL:case We.BOOLEAN:case We.INTEGER:case We.LONG:case We.DOUBLE:case We.STRING:case We.BYTES:case We.DATE:return Kt.of(Kt.valueFromBytes(lT(e.type),e.value),Ie(e.createdAt));case We.INTEGER_CNT:case We.LONG_CNT:return Ur.create(Tp(e.type),Ur.valueFromBytes(Tp(e.type),e.value),Ie(e.createdAt))}}function lf(e){return Gi.of(To.of(Ie(e.createdAt),e.offset),e.relativeOffset)}function cT(e){return To.of(Ie(e.createdAt),e.offset)}function TUe(e){const t=qd.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Ie(i.updatedAt))});const n=ss.create(cT(e.id),t);return n.remove(Ie(e.removedAt)),n}function qu(e){return Hi.of(bd(e.parentId),bd(e.leftSiblingId))}function bd(e){return $n.of(Ie(e.createdAt),e.offset)}function PUe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=Gy(n.content);t.push(r)}),t}function Gy(e){if(e.length===0)return;const t=[];for(const i of e)t.push(BUe(i));const n=t[t.length-1],r=new Map;r.set(e[t.length-1].depth,t[t.length-1]);for(let i=t.length-2;i>=0;i--)r.get(e[i].depth-1).prepend(t[i]),r.set(e[i].depth,t[i]);return n.updateDescendantsSize(),Ei.create(n,Vi).getRoot()}function MUe(e){const t=va.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Ie(r.updatedAt),r.isRemoved);return t}function BUe(e){const t=bd(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=MUe(e.attributes)),e.insPrevId&&(n.insPrevID=bd(e.insPrevId)),e.insNextId&&(n.insNextID=bd(e.insNextId)),n.removedAt=Ie(e.removedAt),n}function dT(e){if(e.body.case==="set"){const t=e.body.value;return mu.create(t.key,A4(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return w0.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),A4(t.value),Ie(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return Xa.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return ys.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(e.body.case==="edit"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Ie(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),S0.create(Ie(t.parentCreatedAt),lf(t.from),lf(t.to),n,t.content,r,Ie(t.executedAt))}else if(e.body.case==="style"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Ie(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),x0.create(Ie(t.parentCreatedAt),lf(t.from),lf(t.to),n,r,Ie(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return ql.create(Ie(t.parentCreatedAt),A4(t.value),Ie(t.executedAt))}else if(e.body.case==="treeEdit"){const t=e.body.value,n=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,i])=>{n.set(r,Ie(i))}),A0.create(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),PUe(t.contents),t.splitLevel,n,Ie(t.executedAt))}else if(e.body.case==="treeStyle"){const t=e.body.value,n=new Map,r=t.attributesToRemove,i=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,a])=>{i.set(o,Ie(a))}),(r==null?void 0:r.length)>0?ua.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),i,r,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ua.create(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),i,n,Ie(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function $Ue(e){const t=[];for(const n of e){const r=dT(n);r&&t.push(r)}return t}function hT(e){const t=[];for(const n of e)t.push(Xl.create({id:uT(n.id),operations:$Ue(n.operations),presenceChange:n.presenceChange?DUe(n.presenceChange):void 0,message:n.message}));return t}function RUe(e){return Tl.of(je.fromString(e.serverSeq,!0),e.clientSeq)}function _Ue(e){return jg.create(e.documentKey,RUe(e.checkpoint),e.isRemoved,hT(e.changes),e.snapshot,Ie(e.minSyncedTicket))}function fT(e){const t=new Yd;for(const r of e.nodes){const i=Wy(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new Sr(Ie(e.createdAt),t);return n.setMovedAt(Ie(e.movedAt)),n.setRemovedAt(Ie(e.removedAt)),n}function pT(e){const t=new Zd;for(const r of e.nodes)t.insert(Wy(r.element));const n=new jr(Ie(e.createdAt),t);return n.setMovedAt(Ie(e.movedAt)),n.setRemovedAt(Ie(e.removedAt)),n}function FUe(e){const t=Kt.of(Kt.valueFromBytes(lT(e.type),e.value),Ie(e.createdAt));return t.setMovedAt(Ie(e.movedAt)),t.setRemovedAt(Ie(e.removedAt)),t}function OUe(e){const t=new Zl;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,TUe(i));i.insPrevId&&o.setInsPrev(t.findNode(cT(i.insPrevId))),n=o}const r=new yi(t,Ie(e.createdAt));return r.setMovedAt(Ie(e.movedAt)),r.setRemovedAt(Ie(e.removedAt)),r}function LUe(e){const t=Ur.create(Tp(e.type),Ur.valueFromBytes(Tp(e.type),e.value),Ie(e.createdAt));return t.setMovedAt(Ie(e.movedAt)),t.setRemovedAt(Ie(e.removedAt)),t}function gT(e){const t=Gy(e.nodes);return Ei.create(t,Ie(e.createdAt))}function Wy(e){if(e.body.case==="jsonObject")return fT(e.body.value);if(e.body.case==="jsonArray")return pT(e.body.value);if(e.body.case==="primitive")return FUe(e.body.value);if(e.body.case==="text")return OUe(e.body.value);if(e.body.case==="counter")return LUe(e.body.value);if(e.body.case==="tree")return gT(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function NUe(e){if(!e)return{root:Sr.create(Vi),presences:new Map};const t=Cje.fromBinary(e);return{root:Wy(t.root),presences:IUe(t.presences)}}function mT(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return fT(t.body.value)}function vT(e){return Ky(e).toBinary()}function zUe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return pT(t.body.value)}function HUe(e){return aT(e).toBinary()}function jUe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return gT(t.body.value)}function UUe(e){return sT(e).toBinary()}function yT(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function Jy(e){return yT(e)}function ET(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Yy(e){return ET(e)}function KUe(e){const t=Lg.fromBinary(e);return uT(t)}function VUe(e){const t=_y.fromBinary(e);return dT(t)}const En={fromPresence:Vy,toChangePack:kUe,fromChangePack:_Ue,fromChanges:hT,toTreeNodes:Uy,fromTreeNodes:Gy,objectToBytes:vT,bytesToObject:mT,bytesToSnapshot:NUe,bytesToHex:yT,hexToBytes:ET,toHexString:Jy,toUint8Array:Yy,toOperation:oT,toChangeID:nT,PbChangeID:Lg,bytesToChangeID:KUe,bytesToOperation:VUe};var ir=(e=>(e[e.Trivial=0]="Trivial",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Fatal=5]="Fatal",e))(ir||{});let Ks=3;function CT(e){Ks=e}const Be={trivial:(...e)=>{Ks>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{Ks>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{Ks>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{Ks>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{Ks>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...e):console.log("YORKIE E:",...e))},fatal:(...e)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...e):console.log("YORKIE F:",...e))},isEnabled:e=>Ks<=e};function bT(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class GUe{constructor(t,n,r,i,o){j(this,"reconnectStreamDelay");j(this,"doc");j(this,"docID");j(this,"syncMode");j(this,"remoteChangeEventReceived");j(this,"watchStream");j(this,"watchLoopTimerID");j(this,"watchAbortController");j(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===_f.RealtimeSyncOff?!1:this.syncMode===_f.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==_f.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const k4=()=>{};class WUe{constructor(t){j(this,"finalized",!1);j(this,"observers",[]);j(this,"finalError");try{t(this)}catch(n){this.error(n)}}next(t){this.forEachObserver(n=>{n.next(t)})}error(t){this.forEachObserver(n=>{n.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,n,r){let i;if(!t)throw new Y(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=k4),i.error===void 0&&(i.error=k4),i.complete===void 0&&(i.complete=k4);const o=bT(),a=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(s){Be.warn(s)}return a}unsubscribeOne(t){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let n=0;nt}}class ml{constructor(t,n,r,i){j(this,"id");j(this,"delimiter");j(this,"message");j(this,"root");j(this,"operations");j(this,"presenceChange");j(this,"previousPresence");j(this,"reversePresenceKeys");this.id=t,this.delimiter=zy,this.root=n,this.operations=[],this.previousPresence=Fi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new ml(t,n,r,i)}push(t){this.operations.push(t)}registerElement(t,n){this.root.registerElement(t,n)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Xl.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,n){for(const r of Object.keys(t))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const n of this.reversePresenceKeys)t[n]=this.previousPresence[n];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Qd{constructor(t){j(this,"rootObject");j(this,"elementPairMapByCreatedAt");j(this,"gcElementSetByCreatedAt");j(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof yi||n instanceof Ei)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Qd(Sr.create(Vi))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof as&&t.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(t){let n=0;const r=i=>{const o=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),n++};return r(t),t instanceof as&&t.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const n of this.gcElementSetByCreatedAt){t.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof as&&r.element.getDescendants(i=>(t.add(i.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Qd(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&t.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&t.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function wT(e,t){const n=new e0(e);return new Proxy(t,n.getHandlers())}class e0{constructor(t){j(this,"context");j(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]=${JSON.stringify(i)}`),e0.setInternal(t,n,r,i),!0),get:(n,r)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Vs(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]`),e0.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=Pp(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(mu.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=Pp(t,o,a);r[i]=s}return r}static deleteInternal(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByKey(r,i);o&&(t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function YUe(e,t){const n=new Jt(e,t);return new Proxy(t,n.getHandlers())}function XUe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function ZUe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class Jt{constructor(t,n){j(this,"context");j(this,"handlers");j(this,"array");this.context=t,this.array=n,this.handlers={get:(r,i,o)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?a=>{const s=r.getByID(a);if(!(!s||s.isRemoved()))return za(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return za(t,s)}:i==="getLast"?()=>za(t,r.getLast()):i==="deleteByID"?a=>{const s=Jt.deleteInternalByID(t,r,a);return za(t,s)}:i==="insertAfter"?(a,s)=>{const u=Jt.insertAfterInternal(t,r,a,s);return za(t,u)}:i==="insertBefore"?(a,s)=>{const u=Jt.insertBeforeInternal(t,r,a,s);return za(t,u)}:i==="moveBefore"?(a,s)=>{Jt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{Jt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{Jt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{Jt.moveLastInternal(t,r,a)}:XUe(i)?Vs(t,r.get(Number(i))):i==="push"?a=>Jt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>Jt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?Jt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>Jt.includes(t,r,a,s):i==="indexOf"?(a,s)=>Jt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>Jt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>Jt.toTestString(r):typeof i=="string"&&ZUe(i)?(...a)=>{const s=Array.from(r).map(u=>Vs(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`array[${i}]`),Jt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield za(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=Pp(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return Jt.insertAfterInternal(t,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(t,n,r,i){const o=t.issueTimeTicket(),a=n.getPrevCreatedAt(r);n.moveAfter(a,i,o),t.push(Xa.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(Xa.create(n.getCreatedAt(),r,i,o))}static moveFrontInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getHead();n.moveAfter(o.getCreatedAt(),r,i),t.push(Xa.create(n.getCreatedAt(),o.getCreatedAt(),r,i))}static moveLastInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getLastCreatedAt();n.moveAfter(o,r,i),t.push(Xa.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=Pp(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(w0.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return Jt.insertAfterInternal(t,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByIndex(r,i);if(o)return t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static deleteInternalByID(t,n,r){const i=t.issueTimeTicket(),o=n.delete(r,i);return t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let f=s;f=o)return!1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).lastIndexOf(r,a);for(let u=a;u>0;u--)if(((s=n.get(u))==null?void 0:s.getID())===r.getID())return u;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class Ug{constructor(t,n){j(this,"context");j(this,"text");this.context=t,this.text=n}initialize(t,n){this.context=t,this.text=n}getID(){return this.text.getID()}edit(t,n,r,i){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);Be.isEnabled(ir.Debug)&&Be.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?Yl(i):void 0,s=this.context.issueTimeTicket(),[u,,d,f]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new S0(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(f)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);Be.isEnabled(ir.Debug)&&Be.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=Yl(r),a=this.context.issueTimeTicket(),[s,u]=this.text.setStyle(i,o,a);for(const d of u)this.context.registerGCPair(d);return this.context.push(new x0(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([Gi.fromStruct(t[0]),Gi.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class Kg{constructor(t,n){j(this,"valueType");j(this,"value");j(this,"context");j(this,"counter");this.valueType=t,this.value=n}initialize(t,n){this.valueType=n.getValueType(),this.context=t,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Kt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ql.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Xy(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===sa){ST(e);const{value:o}=e,a=Nr.create($n.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!YI(a)){const d=Yl(a);s=new va;for(const[f,p]of Object.entries(d))s.set(f,p,i)}const u=Nr.create($n.of(i,0),r,void 0,s);t.append(u);for(const d of o)Xy(d,u,n)}}function qUe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===sa){const{value:o}=t;i=Nr.create($n.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!YI(a)){const u=Yl(a);s=new va;for(const[d,f]of Object.entries(u))s.set(d,f,r)}i=Nr.create($n.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)Xy(u,i,e)}return i}function ST(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function Dw(e){if(!e.length)return!0;if(e[0].type===sa)for(const n of e){const{type:r}=n;if(r!==sa)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");ST(n)}else for(const n of e){const{type:r}=n;if(r===sa)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Vg{constructor(t){j(this,"initialRoot");j(this,"context");j(this,"tree");this.initialRoot=t}initialize(t,n){this.context=t,this.tree=n}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Nr.create($n.of(t.issueTimeTicket(),0),Qje);const n=Nr.create($n.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)Xy(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?Yl(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ua.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?Yl(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const f of d)this.context.registerGCPair(f);this.context.push(ua.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ua.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Dw(r),r[0].type!==sa))for(const f of r){const{children:p=[]}=f;Dw(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===sa){let f="";for(const p of r){const{value:g}=p;f+=g}a.push(Nr.create($n.of(this.context.issueTimeTicket(),0),sa,f))}else a=r.map(f=>f&&qUe(this.context,f)).filter(f=>f);const[,s,u]=this.tree.edit([t,n],a.length?a.map(f=>f==null?void 0:f.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const f of s)this.context.registerGCPair(f);return this.context.push(A0.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Hi.fromStruct(t[0]),Hi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Hi.fromStruct(t[0]),Hi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Iw(e,t){return wT(e,t)}function za(e,t){if(t){if(t instanceof Kt)return t;if(t instanceof Sr)return wT(e,t);if(t instanceof jr)return YUe(e,t);if(t instanceof yi)return new Ug(e,t);if(t instanceof Ur){const n=new Kg($o.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Ei){const n=new Vg;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function Vs(e,t){const n=za(e,t);return n instanceof Kt?n.getValue():n}function Pp(e,t,n){let r;if(Kt.isSupport(t))r=Kt.of(t,n);else if(Array.isArray(t))r=jr.create(n,Jt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof Ug?(r=yi.create(Zl.create(),n),t.initialize(e,r)):t instanceof Kg?(r=Ur.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof Vg?(r=Ei.create(t.buildRoot(e),n),t.initialize(e,r)):r=Sr.create(n,e0.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const Tw=50;class QUe{constructor(){j(this,"undoStack",[]);j(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Tw&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Tw&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const eKe="yorkie-devtools-panel",tKe="yorkie-devtools-sdk";let el="disconnected";const Pw=new Map,Rf=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Rf);function cf(e,t){(t!=null&&t.force||el!=="disconnected")&&window.postMessage({source:tKe,...e},"*")}function nKe(e){if(!e.isEnableDevtools()||typeof window>"u"||Pw.has(e.getKey()))return;Rf.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==jn.StatusChanged&&r.type!==jn.Snapshot&&r.type!==jn.LocalChange&&r.type!==jn.RemoteChange&&r.type!==jn.Initialized&&r.type!==jn.Watched&&r.type!==jn.Unwatched&&r.type!==jn.PresenceChanged)||(Rf.get(e.getKey()).push(n),el==="synced"&&cf({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Pw.set(e.getKey(),[t]),cf({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==eKe)return;switch(n.data.msg){case"devtools::connect":if(el!=="disconnected")break;el="connected",cf({msg:"doc::available",docKey:e.getKey()}),Be.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":el="disconnected",Be.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":el="synced",cf({msg:"doc::sync::full",docKey:e.getKey(),events:Rf.get(e.getKey())}),Be.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Ha=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Ha||{}),jn=(e=>(e.StatusChanged="status-changed",e.ConnectionChanged="connection-changed",e.SyncStatusChanged="sync-status-changed",e.Snapshot="snapshot",e.LocalChange="local-change",e.RemoteChange="remote-change",e.Initialized="initialized",e.Watched="watched",e.Unwatched="unwatched",e.PresenceChanged="presence-changed",e.Broadcast="broadcast",e.LocalBroadcast="local-broadcast",e))(jn||{}),C2=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(C2||{}),b2=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(b2||{});class Zy{constructor(t,n){j(this,"key");j(this,"status");j(this,"opts");j(this,"changeID");j(this,"checkpoint");j(this,"localChanges");j(this,"root");j(this,"clone");j(this,"eventStream");j(this,"eventStreamObserver");j(this,"onlineClients");j(this,"presences");j(this,"history");j(this,"internalHistory");j(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=Qd.create(),this.changeID=sUe,this.checkpoint=uUe,this.localChanges=[],this.eventStream=JUe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new QUe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},nKe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Iw(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new S4(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){Be.isEnabled(ir.Trivial)&&Be.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,St.Local),u=i.getReversePresence();u&&s.push({type:"presence",value:u}),this.localChanges.push(o),s.length>0&&this.internalHistory.pushUndo(s),a.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const d=[];a.length>0&&d.push({type:"local-change",source:St.Local,value:{message:o.getMessage()||"",operations:a,actor:r,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&d.push({type:"presence-changed",source:St.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),Be.isEnabled(ir.Trivial)&&Be.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const f of u.value.operations)this.isSameElementOrChildOf(f.path,o)&&d.push(f);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}applyChangePack(t){for(t.hasSnapshot()?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),St.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();t.hasSnapshot()&&this.applyChanges(this.localChanges,St.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),this.garbageCollect(t.getMinSyncedTicket()),t.getIsRemoved()&&this.applyStatus("removed"),Be.isEnabled(ir.Trivial)&&Be.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Fi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return jg.create(this.key,n,!1,t)}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Iw(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n){const{root:r,presences:i}=En.bytesToSnapshot(n);this.root=new Qd(r),this.presences=i,this.changeID=this.changeID.syncLamport(t),this.clone=void 0,this.publish([{type:"snapshot",source:St.Remote,value:{snapshot:this.isEnableDevtools()?En.bytesToHex(n):void 0,serverSeq:t.toString()}}])}applyChanges(t,n){Be.isEnabled(ir.Debug)&&Be.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Be.isEnabled(ir.Trivial)&&Be.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return t}})}class b0{constructor(t){j(this,"createdAt");j(this,"movedAt");j(this,"removedAt");this.createdAt=t}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(t){return!this.movedAt||t&&t.after(this.movedAt)?(this.movedAt=t,!0):!1}setRemovedAt(t){this.removedAt=t}remove(t){return t&&t.after(this.getPositionedAt())&&(!this.removedAt||t.after(this.removedAt))?(this.removedAt=t,!0):!1}isRemoved(){return!!this.removedAt}}class as extends b0{constructor(t){super(t)}}class Hy{constructor(t,n){j(this,"strKey");j(this,"value");this.strKey=t,this.value=n}static of(t,n){return new Hy(t,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(t){return this.value.remove(t)}}class Yd{constructor(){j(this,"nodeMapByKey");j(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Yd}set(t,n,r){let i;const o=this.nodeMapByKey.get(t);o!=null&&!o.isRemoved()&&o.remove(r)&&(i=o.getValue());const a=Hy.of(t,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),a),(o==null||r.after(o.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(t,a),n.setMovedAt(r)),i}delete(t,n){if(!this.nodeMapByCreatedAt.has(t.toIDString()))throw new Y(W.ErrInvalidArgument,`fail to find ${t.toIDString()}`);const r=this.nodeMapByCreatedAt.get(t.toIDString());return r.remove(n),r.getValue()}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return n.getStrKey()}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find ${t.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(t,n){const r=this.nodeMapByKey.get(t);if(r!=null&&r.remove(n))return r.getValue()}has(t){const n=this.nodeMapByKey.get(t);return n==null?!1:!n.isRemoved()}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}get(t){const n=this.nodeMapByKey.get(t);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,t]of this.nodeMapByKey)yield t}}class Sr extends as{constructor(n,r){super(n);j(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new Sr(n,Yd.create());const i=Yd.create();for(const[o,a]of Object.entries(r))i.set(o,a.deepcopy(),a.getCreatedAt());return new Sr(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${ko(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:o,value:a,type:s}=i.toJSForTest();n[r]={key:r,createdAt:o,value:a,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[o]of this)n.push(o);const r=[];for(const o of n.sort()){const a=(i=this.memberNodes.get(o))==null?void 0:i.getValue();r.push(`"${ko(o)}":${a.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=Sr.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof as&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var St=(e=>(e.Local="local",e.Remote="remote",e.UndoRedo="undoredo",e))(St||{});class Zi{constructor(t,n){j(this,"parentCreatedAt");j(this,"executedAt");this.parentCreatedAt=t,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new Y(W.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(t){this.executedAt&&(this.executedAt=this.executedAt.setActor(t))}setExecutedAt(t){this.executedAt=t}}class XI{constructor(t){j(this,"value");j(this,"left");j(this,"right");j(this,"parent");j(this,"weight");this.value=t,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(t){this.left=t}setRight(t){this.right=t}setParent(t){this.parent=t}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(t){this.weight+=t}initWeight(){this.weight=this.getLength()}}class Xd{constructor(t){j(this,"root");this.root=t}get length(){return this.root?this.root.getWeight():0}find(t){if(!this.root||t<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&t<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new Y(W.ErrInvalidArgument,`out of index range: pos: ${t} > node.length: ${n.getLength()}`);return this.splayNode(n),[n,t]}indexOf(t){return!t||t!==this.root&&!t.hasLinks()?-1:(this.splayNode(t),this.root.getLeftWeight())}getRoot(){return this.root}insert(t){return this.insertAfter(this.root,t)}insertAfter(t,n){return t?(this.splayNode(t),this.root=n,n.setRight(t.getRight()),t.hasRight()&&t.getRight().setParent(n),n.setLeft(t),t.setParent(n),t.setRight(),this.updateWeight(t),this.updateWeight(n),n):(this.root=n,n)}updateWeight(t){t.initWeight(),t.hasLeft()&&t.increaseWeight(t.getLeftWeight()),t.hasRight()&&t.increaseWeight(t.getRightWeight())}updateTreeWeight(t){for(;t;)this.updateWeight(t),t=t.getParent()}splayNode(t){if(t)for(;;)if(this.isLeftChild(t.getParent())&&this.isRightChild(t))this.rotateLeft(t),this.rotateRight(t);else if(this.isRightChild(t.getParent())&&this.isLeftChild(t))this.rotateRight(t),this.rotateLeft(t);else if(this.isLeftChild(t.getParent())&&this.isLeftChild(t))this.rotateRight(t.getParent()),this.rotateRight(t);else if(this.isRightChild(t.getParent())&&this.isRightChild(t))this.rotateLeft(t.getParent()),this.rotateLeft(t);else{this.isLeftChild(t)?this.rotateRight(t):this.isRightChild(t)&&this.rotateLeft(t),this.updateWeight(t);return}}delete(t){this.splayNode(t);const n=new Xd(t.getLeft());n.root&&n.root.setParent();const r=new Xd(t.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;t.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(t,n){if(!n){this.splayNode(t),this.cutOffRight(t);return}this.splayNode(t),this.splayNode(n),n.getLeft()!=t&&this.rotateRight(t),this.cutOffRight(t)}cutOffRight(t){const n=[];this.traversePostorder(t.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(t)}toTestString(){const t=[];return this.traverseInorder(this.root,t),t.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const t=[];this.traverseInorder(this.root,t);for(const n of t)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let t=this.root;for(;t.hasRight();)t=t.getRight();return t}traverseInorder(t,n){t&&(this.traverseInorder(t.getLeft(),n),n.push(t),this.traverseInorder(t.getRight(),n))}traversePostorder(t,n){t&&(this.traversePostorder(t.getLeft(),n),this.traversePostorder(t.getRight(),n),n.push(t))}rotateLeft(t){const n=t.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(t):n.getParent().setRight(t):this.root=t,t.setParent(n.getParent()),n.setRight(t.getLeft()),n.hasRight()&&n.getRight().setParent(n),t.setLeft(n),t.getLeft().setParent(t),this.updateWeight(n),this.updateWeight(t)}rotateRight(t){const n=t.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(t):n.getParent().setRight(t):this.root=t,t.setParent(n.getParent()),n.setLeft(t.getRight()),n.hasLeft()&&n.getLeft().setParent(n),t.setRight(n),t.getRight().setParent(t),this.updateWeight(n),this.updateWeight(t)}isLeftChild(t){return t&&t.hasParent()?t.getParent().getLeft()===t:!1}isRightChild(t){return t&&t.hasParent()?t.getParent().getRight()===t:!1}}var yn=(e=>(e[e.Null=0]="Null",e[e.Boolean=1]="Boolean",e[e.Integer=2]="Integer",e[e.Long=3]="Long",e[e.Double=4]="Double",e[e.String=5]="String",e[e.Bytes=6]="Bytes",e[e.Date=7]="Date",e))(yn||{});class Kt extends b0{constructor(n,r){super(r);j(this,"valueType");j(this,"value");this.valueType=Kt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Kt(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(o,a){i.setUint8(a,o)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return je.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(je.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${ko(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Kt.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof je)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Kt.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=je.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Ip extends XI{constructor(n){super(n);j(this,"prev");j(this,"next");this.value=n}static createAfter(n,r){const i=new Ip(r),o=n.next;return n.next=i,i.prev=n,i.next=o,o&&(o.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Zd{constructor(){j(this,"dummyHead");j(this,"last");j(this,"nodeMapByIndex");j(this,"nodeMapByCreatedAt");const t=Kt.of(0,Vi);t.setRemovedAt(Vi),this.dummyHead=new Ip(t),this.last=this.dummyHead,this.nodeMapByIndex=new Xd,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Zd}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=Ip.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class jr extends as{constructor(n,r){super(n);j(this,"elements");this.elements=r}static create(n,r){if(!r)return new jr(n,Zd.create());const i=Zd.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new jr(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof as&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:Il(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,f,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),f=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):Vi:Ed;if(m.canStyle(i,E)){const w=f.get(v),C=m.getCreatedAt();(!w||C.after(w))&&f.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:Il(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[f,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Il(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new yi(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class S0 extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"content");j(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.content=a,this.attributes=s}static create(n,r,i,o,a,s,u){return new S0(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof yi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class x0 extends Zi{constructor(n,r,i,o,a,s){super(n,s);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new x0(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof yi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const qje=2,Qje="root",sa="text";function Gc(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===sa}get paddedSize(){return this.size+(this.isText?0:qje)}isAncestorOf(t){return tUe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function tUe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var rn=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(rn||{});function ZI(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),ZI(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function qI(e,t,n=0){for(const r of e.children)qI(r,t,n+1);t(e,n)}function Hg(e,t,n=0){for(const r of e._children)Hg(r,t,n+1);t(e,n)}function y2(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return y2(o,t-i,n);if(t===i)return{node:e,offset:r};if(!n&&o.paddedSize===t-i)return{node:e,offset:r+1};if(o.paddedSize>t-i)return y2(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function QI(e){return e.isText||e.children.length===0?e:QI(e.children[0])}function nUe(e,t){if(e.sizee===t?0:e0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,o=n;for(;i&&o===i.left;)o=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,n){for(;n;){const r=this.comparator(t,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(t,n,r){if(!r)return this.counter+=1,new oUe(t,n,!0);const i=this.comparator(t,r.key);return i<0?r.left=this.putInternal(t,n,r.left):i>0?r.right=this.putInternal(t,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,n){if(this.comparator(n,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,n);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(n,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(n,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,n)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const n=t.right;return t.right=n.left,n.left=t,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(t){const n=t.left;return t.left=n.right,n.right=t,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Hi{constructor(t,n){j(this,"parentID");j(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Hi(t,n)}static fromTreePos(t){const{offset:n}=t;let{node:r}=t,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Hi.of(r.id,$n.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Hi.of($n.of(wr.fromStruct(t.parentID.createdAt),t.parentID.offset),$n.of(wr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class $n{constructor(t,n){j(this,"createdAt");j(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new $n(t,n)}static fromStruct(t){return $n.of(wr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr($n.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr($n.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new va);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function E2(e){var n;if(e.isText){const r=e;return{type:r.type,value:r.value}}const t={type:e.type,children:e.children.map(E2)};return e.attrs&&(t.attributes=Il((n=e.attrs)==null?void 0:n.toObject())),t}function jy(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${ko(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>jy(n)).join("")}`}function tT(e){if(e.isText){const t=e;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:e.type,children:e.children.map(tT),size:e.size,isRemoved:e.isRemoved}}class Ei extends b0{constructor(n,r){super(r);j(this,"indexTree");j(this,"nodeMapByID");this.indexTree=new rUe(n),this.nodeMapByID=new eT($n.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Ei(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,f=s?0:d.indexOf(a)+1;for(let p=f;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):Vi:Ed;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const A=v.setAttrs(r,i),D=A.reduce((k,[,B])=>(B&&(k[B.getKey()]=p[B.getKey()]),k),{}),P=v.parent,I=v.prevSibling||v.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(P,I),to:this.toIndex(v,v),fromPath:this.toPath(P,I),toPath:this.toPath(v,v),actor:i.getActorID(),value:D});for(const[k]of A)k&&m.push({parent:v,child:k})}}),[g,m,f]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),f=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):Vi:Ed;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new va);for(const D of r){const P=m.attrs.remove(D,i);for(const I of P)g.push({parent:m,child:I})}const b=m.parent,A=m.prevSibling||m.parent;f.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,A),to:this.toIndex(m,m),fromPath:this.toPath(b,A),toPath:this.toPath(m,m),value:r})}}),[p,g,f]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[f,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,f,p,([D,P],I)=>{if(P===rn.Start&&!I)for(const _ of D.children)w.push(_);const k=D.getCreatedAt().getActorID(),B=s?s.has(k)?s.get(k):Vi:Ed;if(D.canDelete(o,B)||v.includes(D.parent)){const _=C.get(k),N=D.getCreatedAt();(!_||N.after(_))&&C.set(k,N),(P===rn.Text||P===rn.Start)&&v.push(D),E.push([D,P])}});const b=this.makeDeletionChanges(E,o),A=[];for(const D of v)D.remove(o),D.isRemoved&&A.push({parent:this,child:D});for(const D of w)D.removedAt||u.append(D);if(i>0){let D=0,P=u,I=d;for(;D{u.isRemoved&&(k.remove(o),A.push({parent:this,child:k})),this.nodeMapByID.put(k.id,k)}),I.isRemoved||D.push(I);if(D.length){const I=D.map(k=>E2(k));b.length&&b[b.length-1].from===g?b[b.length-1].value=I:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:I})}}return[b,A,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Hi.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return jy(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,f;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),f=Hi.fromTreePos(p).toStruct());const g={type:i.type,parent:o==null?void 0:o.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(E=i.insNextID)==null?void 0:E.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:s,attributes:i.attrs?Il((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:f};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===rn.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?rn.Text:rn.Start]:[n,rn.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,rn.End];const s=o[a+1];return[s,s.isText?rn.Text:rn.Start]}findLeftToken([n,r]){if(r===rn.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?rn.Text:rn.End]}return[n,rn.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,rn.Start];const s=o[a-1];return[s,s.isText?rn.Text:rn.End]}}class A0 extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"contents");j(this,"splitLevel");j(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=o,this.splitLevel=a,this.maxCreatedAtMapByActor=s}static create(n,r,i,o,a,s,u){return new A0(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ei))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>wr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>jy(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Wa{constructor(t,n,r,i){j(this,"clientSeq");j(this,"serverSeq");j(this,"lamport");j(this,"actor");this.clientSeq=t,this.serverSeq=i,this.lamport=n,this.actor=r}static of(t,n,r,i){return new Wa(t,n,r,i)}next(){return new Wa(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(t){return t.greaterThan(this.lamport)?new Wa(this.clientSeq,t,this.actor):new Wa(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(t){return wr.of(this.lamport,t,this.actor)}setActor(t){return new Wa(this.clientSeq,this.lamport,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const sUe=new Wa(0,je.fromInt(0,!0),zg);class Xl{constructor({id:t,operations:n,presenceChange:r,message:i}){j(this,"id");j(this,"operations");j(this,"presenceChange");j(this,"message");this.id=t,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:t,operations:n,presenceChange:r,message:i}){return new Xl({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===vs.Put?n.set(this.id.getActorID(),Fi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:En.bytesToHex(En.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>En.bytesToHex(En.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return Xl.create({id:En.bytesToChangeID(En.hexToBytes(n)),operations:r==null?void 0:r.map(a=>En.bytesToOperation(En.hexToBytes(a))),presenceChange:i,message:o})}}class jg{constructor(t,n,r,i,o,a){j(this,"documentKey");j(this,"checkpoint");j(this,"isRemoved");j(this,"changes");j(this,"snapshot");j(this,"minSyncedTicket");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a}static create(t,n,r,i,o,a){return new jg(t,n,r,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Tl{constructor(t,n){j(this,"serverSeq");j(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new Tl(t,n)}increaseClientSeq(t){return t===0?this:new Tl(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq.greaterThan(t.serverSeq)?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Tl.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq.equals(t.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const uUe=new Tl(je.fromInt(0,!0),0);class To{constructor(t,n){j(this,"createdAt");j(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new To(t,n)}static fromStruct(t){return To.of(wr.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new To(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const lUe=To.of(Vi,0);class Gi{constructor(t,n){j(this,"id");j(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new Gi(t,n)}static fromStruct(t){const n=To.fromStruct(t.id);return Gi.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return To.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class ss extends XI{constructor(n,r,i){super(r);j(this,"id");j(this,"removedAt");j(this,"prev");j(this,"next");j(this,"insPrev");j(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new ss(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const f=d.getCreatedAt().getActorID();(!a.has(f)||d.getID().getCreatedAt().after(a.get(f)))&&a.set(f,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const f=d.getCreatedAt().getActorID(),p=i?r.has(f)?r.get(f):Vi:Ed;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var $o=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))($o||{});class Ur extends b0{constructor(n,r,i){super(i);j(this,"valueType");j(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=je.fromNumber(r).toInt():this.value=Aw(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=je.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Ur(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return je.fromBytesLE(Array.from(r));default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Ur.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof je?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!Ur.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===yn.Long?this.value=this.value+n.getValue().toInt():this.value=je.fromNumber(this.value+Aw(n.getValue())).toInt(),this}}class ql extends Zi{constructor(n,r,i){super(n,i);j(this,"value");this.value=r}static create(n,r,i){return new ql(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ur))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===yn.Long?n.getValue().multiply(-1):n.getValue()*-1;return ql.create(this.getParentCreatedAt(),Kt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ua extends Zi{constructor(n,r,i,o,a,s,u){super(n,u);j(this,"fromPos");j(this,"toPos");j(this,"maxCreatedAtMapByActor");j(this,"attributes");j(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a,this.attributesToRemove=s}static create(n,r,i,o,a,s){return new ua(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ua(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ei))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:f,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:f,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function cUe(e){const t=new Ly,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function dUe(e){if(e.type===vs.Put)return new m2({type:Jd.PUT,presence:cUe(e.presence)});if(e.type===vs.Clear)return new m2({type:Jd.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function hUe(e){return new KI({serverSeq:e.getServerSeqAsString(),clientSeq:e.getClientSeq()})}function nT(e){return new Lg({clientSeq:e.getClientSeq(),lamport:e.getLamportAsString(),actorId:Yy(e.getActorID())})}function De(e){if(e)return new Te({lamport:e.getLamportAsString(),delimiter:e.getDelimiter(),actorId:Yy(e.getActorID())})}function rT(e){switch(e){case yn.Null:return We.NULL;case yn.Boolean:return We.BOOLEAN;case yn.Integer:return We.INTEGER;case yn.Long:return We.LONG;case yn.Double:return We.DOUBLE;case yn.String:return We.STRING;case yn.Bytes:return We.BYTES;case yn.Date:return We.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function iT(e){switch(e){case $o.IntegerCnt:return We.INTEGER_CNT;case $o.LongCnt:return We.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function x4(e){if(e instanceof Sr)return new Xo({type:We.JSON_OBJECT,createdAt:De(e.getCreatedAt()),value:vT(e)});if(e instanceof jr)return new Xo({type:We.JSON_ARRAY,createdAt:De(e.getCreatedAt()),value:HUe(e)});if(e instanceof yi)return new Xo({type:We.TEXT,createdAt:De(e.getCreatedAt())});if(e instanceof Kt)return new Xo({type:rT(e.getType()),createdAt:De(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ur)return new Xo({type:iT(e.getType()),createdAt:De(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ei)return new Xo({type:We.TREE,createdAt:De(e.getCreatedAt()),value:UUe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function fUe(e){return new g2({createdAt:De(e.getCreatedAt()),offset:e.getOffset()})}function sf(e){return new gu({createdAt:De(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function uf(e){return new Wd({parentId:Cd(e.getParentID()),leftSiblingId:Cd(e.getLeftSiblingID())})}function Cd(e){return new Dl({createdAt:De(e.getCreatedAt()),offset:e.getOffset()})}function oT(e){const t=new _y;if(e instanceof mu){const n=e,r=new kI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.key=n.getKey(),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof w0){const n=e,r=new DI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.prevCreatedAt=De(n.getPrevCreatedAt()),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof Xa){const n=e,r=new II;r.parentCreatedAt=De(n.getParentCreatedAt()),r.prevCreatedAt=De(n.getPrevCreatedAt()),r.createdAt=De(n.getCreatedAt()),r.executedAt=De(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof ys){const n=e,r=new TI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.createdAt=De(n.getCreatedAt()),r.executedAt=De(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof S0){const n=e,r=new PI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=sf(n.getFromPos()),r.to=sf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=De(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof x0){const n=e,r=new MI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=sf(n.getFromPos()),r.to=sf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=De(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof ql){const n=e,r=new BI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.value=x4(n.getValue()),r.executedAt=De(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof A0){const n=e,r=new $I,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=De(a);r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=uf(n.getFromPos()),r.to=uf(n.getToPos()),r.contents=CUe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=De(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ua){const n=e,r=new RI;r.parentCreatedAt=De(n.getParentCreatedAt()),r.from=uf(n.getFromPos()),r.to=uf(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=De(s);const o=n.getAttributesToRemove();if(o.length>0)r.attributesToRemove=o;else{const a=r.attributes;for(const[s,u]of n.getAttributes())a[s]=u}r.executedAt=De(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(W.ErrUnimplemented,"unimplemented operation");return t}function pUe(e){const t=[];for(const n of e)t.push(oT(n));return t}function gUe(e){const t=new AI({id:nT(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=pUe(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=dUe(e.getPresenceChange())),t}function mUe(e){const t=[];for(const n of e)t.push(gUe(n));return t}function vUe(e){const t=[];for(const n of e)t.push(new HI({key:n.getStrKey(),element:Ky(n.getValue())}));return t}function yUe(e){const t=[];for(const n of e)t.push(new Fy({element:Ky(n.getValue())}));return t}function EUe(e){const t=[];for(const n of e){const r=new jI;r.id=fUe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=De(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new Ng;s.value=a.getValue(),s.updatedAt=De(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function CUe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new UI({content:Uy(n)}));return t}function bUe(e){const t={};for(const n of e)t[n.getKey()]=new Ng({value:n.getValue(),updatedAt:De(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function Uy(e){if(!e)return[];const t=[];return Hg(e,(n,r)=>{const i=new Oy({id:Cd(n.id),type:n.type,removedAt:De(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=Cd(n.insPrevID)),n.insNextID&&(i.insNextId=Cd(n.insNextID)),n.attrs&&(i.attributes=bUe(n.attrs)),t.push(i)}),t}function wUe(e){const t=new Si;return t.body.case="jsonObject",t.body.value=new _I({nodes:vUe(e.getRHT()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function aT(e){const t=new Si;return t.body.case="jsonArray",t.body.value=new FI({nodes:yUe(e.getElements()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function SUe(e){const t=new Si;return t.body.case="primitive",t.body.value=new OI({type:rT(e.getType()),value:e.toBytes(),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function xUe(e){const t=new Si;return t.body.case="text",t.body.value=new LI({nodes:EUe(e.getRGATreeSplit()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function AUe(e){const t=new Si;return t.body.case="counter",t.body.value=new NI({type:iT(e.getType()),value:e.toBytes(),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function sT(e){const t=new Si;return t.body.case="tree",t.body.value=new zI({nodes:Uy(e.getRoot()),createdAt:De(e.getCreatedAt()),movedAt:De(e.getMovedAt()),removedAt:De(e.getRemovedAt())}),t}function Ky(e){if(e instanceof Sr)return wUe(e);if(e instanceof jr)return aT(e);if(e instanceof Kt)return SUe(e);if(e instanceof yi)return xUe(e);if(e instanceof Ur)return AUe(e);if(e instanceof Ei)return sT(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function kUe(e){return new Sa({documentKey:e.getDocumentKey(),checkpoint:hUe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:mUe(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:De(e.getMinSyncedTicket())})}function kw(e){const t=e.findDetails(Kje);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function uT(e){let t;return e.serverSeq&&(t=je.fromString(e.serverSeq,!0)),Wa.of(e.clientSeq,je.fromString(e.lamport,!0),Jy(e.actorId),t)}function Ie(e){if(e)return wr.of(je.fromString(e.lamport,!0),e.delimiter,Jy(e.actorId))}function Vy(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function DUe(e){const t=e.type;if(t===Jd.PUT){const n=Vy(e.presence);return{type:vs.Put,presence:n}}if(t===Jd.CLEAR)return{type:vs.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function IUe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,Vy(r))}),t}function lT(e){switch(e){case We.NULL:return yn.Null;case We.BOOLEAN:return yn.Boolean;case We.INTEGER:return yn.Integer;case We.LONG:return yn.Long;case We.DOUBLE:return yn.Double;case We.STRING:return yn.String;case We.BYTES:return yn.Bytes;case We.DATE:return yn.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function Tp(e){switch(e){case We.INTEGER_CNT:return $o.IntegerCnt;case We.LONG_CNT:return $o.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function A4(e){switch(e.type){case We.JSON_OBJECT:return e.value?mT(e.value):Sr.create(Ie(e.createdAt));case We.JSON_ARRAY:return e.value?zUe(e.value):jr.create(Ie(e.createdAt));case We.TEXT:return yi.create(Zl.create(),Ie(e.createdAt));case We.TREE:return jUe(e.value);case We.NULL:case We.BOOLEAN:case We.INTEGER:case We.LONG:case We.DOUBLE:case We.STRING:case We.BYTES:case We.DATE:return Kt.of(Kt.valueFromBytes(lT(e.type),e.value),Ie(e.createdAt));case We.INTEGER_CNT:case We.LONG_CNT:return Ur.create(Tp(e.type),Ur.valueFromBytes(Tp(e.type),e.value),Ie(e.createdAt))}}function lf(e){return Gi.of(To.of(Ie(e.createdAt),e.offset),e.relativeOffset)}function cT(e){return To.of(Ie(e.createdAt),e.offset)}function TUe(e){const t=qd.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Ie(i.updatedAt))});const n=ss.create(cT(e.id),t);return n.remove(Ie(e.removedAt)),n}function qu(e){return Hi.of(bd(e.parentId),bd(e.leftSiblingId))}function bd(e){return $n.of(Ie(e.createdAt),e.offset)}function PUe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=Gy(n.content);t.push(r)}),t}function Gy(e){if(e.length===0)return;const t=[];for(const i of e)t.push(BUe(i));const n=t[t.length-1],r=new Map;r.set(e[t.length-1].depth,t[t.length-1]);for(let i=t.length-2;i>=0;i--)r.get(e[i].depth-1).prepend(t[i]),r.set(e[i].depth,t[i]);return n.updateDescendantsSize(),Ei.create(n,Vi).getRoot()}function MUe(e){const t=va.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Ie(r.updatedAt),r.isRemoved);return t}function BUe(e){const t=bd(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=MUe(e.attributes)),e.insPrevId&&(n.insPrevID=bd(e.insPrevId)),e.insNextId&&(n.insNextID=bd(e.insNextId)),n.removedAt=Ie(e.removedAt),n}function dT(e){if(e.body.case==="set"){const t=e.body.value;return mu.create(t.key,A4(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return w0.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),A4(t.value),Ie(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return Xa.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return ys.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(e.body.case==="edit"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Ie(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),S0.create(Ie(t.parentCreatedAt),lf(t.from),lf(t.to),n,t.content,r,Ie(t.executedAt))}else if(e.body.case==="style"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Ie(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),x0.create(Ie(t.parentCreatedAt),lf(t.from),lf(t.to),n,r,Ie(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return ql.create(Ie(t.parentCreatedAt),A4(t.value),Ie(t.executedAt))}else if(e.body.case==="treeEdit"){const t=e.body.value,n=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,i])=>{n.set(r,Ie(i))}),A0.create(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),PUe(t.contents),t.splitLevel,n,Ie(t.executedAt))}else if(e.body.case==="treeStyle"){const t=e.body.value,n=new Map,r=t.attributesToRemove,i=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,a])=>{i.set(o,Ie(a))}),(r==null?void 0:r.length)>0?ua.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),i,r,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ua.create(Ie(t.parentCreatedAt),qu(t.from),qu(t.to),i,n,Ie(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function $Ue(e){const t=[];for(const n of e){const r=dT(n);r&&t.push(r)}return t}function hT(e){const t=[];for(const n of e)t.push(Xl.create({id:uT(n.id),operations:$Ue(n.operations),presenceChange:n.presenceChange?DUe(n.presenceChange):void 0,message:n.message}));return t}function RUe(e){return Tl.of(je.fromString(e.serverSeq,!0),e.clientSeq)}function _Ue(e){return jg.create(e.documentKey,RUe(e.checkpoint),e.isRemoved,hT(e.changes),e.snapshot,Ie(e.minSyncedTicket))}function fT(e){const t=new Yd;for(const r of e.nodes){const i=Wy(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new Sr(Ie(e.createdAt),t);return n.setMovedAt(Ie(e.movedAt)),n.setRemovedAt(Ie(e.removedAt)),n}function pT(e){const t=new Zd;for(const r of e.nodes)t.insert(Wy(r.element));const n=new jr(Ie(e.createdAt),t);return n.setMovedAt(Ie(e.movedAt)),n.setRemovedAt(Ie(e.removedAt)),n}function FUe(e){const t=Kt.of(Kt.valueFromBytes(lT(e.type),e.value),Ie(e.createdAt));return t.setMovedAt(Ie(e.movedAt)),t.setRemovedAt(Ie(e.removedAt)),t}function OUe(e){const t=new Zl;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,TUe(i));i.insPrevId&&o.setInsPrev(t.findNode(cT(i.insPrevId))),n=o}const r=new yi(t,Ie(e.createdAt));return r.setMovedAt(Ie(e.movedAt)),r.setRemovedAt(Ie(e.removedAt)),r}function LUe(e){const t=Ur.create(Tp(e.type),Ur.valueFromBytes(Tp(e.type),e.value),Ie(e.createdAt));return t.setMovedAt(Ie(e.movedAt)),t.setRemovedAt(Ie(e.removedAt)),t}function gT(e){const t=Gy(e.nodes);return Ei.create(t,Ie(e.createdAt))}function Wy(e){if(e.body.case==="jsonObject")return fT(e.body.value);if(e.body.case==="jsonArray")return pT(e.body.value);if(e.body.case==="primitive")return FUe(e.body.value);if(e.body.case==="text")return OUe(e.body.value);if(e.body.case==="counter")return LUe(e.body.value);if(e.body.case==="tree")return gT(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function NUe(e){if(!e)return{root:Sr.create(Vi),presences:new Map};const t=Cje.fromBinary(e);return{root:Wy(t.root),presences:IUe(t.presences)}}function mT(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return fT(t.body.value)}function vT(e){return Ky(e).toBinary()}function zUe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return pT(t.body.value)}function HUe(e){return aT(e).toBinary()}function jUe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Si.fromBinary(e);return gT(t.body.value)}function UUe(e){return sT(e).toBinary()}function yT(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function Jy(e){return yT(e)}function ET(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Yy(e){return ET(e)}function KUe(e){const t=Lg.fromBinary(e);return uT(t)}function VUe(e){const t=_y.fromBinary(e);return dT(t)}const En={fromPresence:Vy,toChangePack:kUe,fromChangePack:_Ue,fromChanges:hT,toTreeNodes:Uy,fromTreeNodes:Gy,objectToBytes:vT,bytesToObject:mT,bytesToSnapshot:NUe,bytesToHex:yT,hexToBytes:ET,toHexString:Jy,toUint8Array:Yy,toOperation:oT,toChangeID:nT,PbChangeID:Lg,bytesToChangeID:KUe,bytesToOperation:VUe};var ir=(e=>(e[e.Trivial=0]="Trivial",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Fatal=5]="Fatal",e))(ir||{});let Ks=3;function CT(e){Ks=e}const Be={trivial:(...e)=>{Ks>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{Ks>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{Ks>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{Ks>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{Ks>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...e):console.log("YORKIE E:",...e))},fatal:(...e)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...e):console.log("YORKIE F:",...e))},isEnabled:e=>Ks<=e};function bT(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class GUe{constructor(t,n,r,i,o){j(this,"reconnectStreamDelay");j(this,"doc");j(this,"docID");j(this,"syncMode");j(this,"remoteChangeEventReceived");j(this,"watchStream");j(this,"watchLoopTimerID");j(this,"watchAbortController");j(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===_f.RealtimeSyncOff?!1:this.syncMode===_f.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==_f.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const k4=()=>{};class WUe{constructor(t){j(this,"finalized",!1);j(this,"observers",[]);j(this,"finalError");try{t(this)}catch(n){this.error(n)}}next(t){this.forEachObserver(n=>{n.next(t)})}error(t){this.forEachObserver(n=>{n.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,n,r){let i;if(!t)throw new Y(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=k4),i.error===void 0&&(i.error=k4),i.complete===void 0&&(i.complete=k4);const o=bT(),a=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(s){Be.warn(s)}return a}unsubscribeOne(t){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let n=0;nt}}class ml{constructor(t,n,r,i){j(this,"id");j(this,"delimiter");j(this,"message");j(this,"root");j(this,"operations");j(this,"presenceChange");j(this,"previousPresence");j(this,"reversePresenceKeys");this.id=t,this.delimiter=zy,this.root=n,this.operations=[],this.previousPresence=Fi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new ml(t,n,r,i)}push(t){this.operations.push(t)}registerElement(t,n){this.root.registerElement(t,n)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Xl.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,n){for(const r of Object.keys(t))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const n of this.reversePresenceKeys)t[n]=this.previousPresence[n];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Qd{constructor(t){j(this,"rootObject");j(this,"elementPairMapByCreatedAt");j(this,"gcElementSetByCreatedAt");j(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof yi||n instanceof Ei)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Qd(Sr.create(Vi))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof as&&t.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(t){let n=0;const r=i=>{const o=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),n++};return r(t),t instanceof as&&t.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const n of this.gcElementSetByCreatedAt){t.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof as&&r.element.getDescendants(i=>(t.add(i.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Qd(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&t.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&t.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function wT(e,t){const n=new e0(e);return new Proxy(t,n.getHandlers())}class e0{constructor(t){j(this,"context");j(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]=${JSON.stringify(i)}`),e0.setInternal(t,n,r,i),!0),get:(n,r)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Vs(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`obj[${r}]`),e0.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=Pp(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(mu.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=Pp(t,o,a);r[i]=s}return r}static deleteInternal(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByKey(r,i);o&&(t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function YUe(e,t){const n=new Jt(e,t);return new Proxy(t,n.getHandlers())}function XUe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function ZUe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class Jt{constructor(t,n){j(this,"context");j(this,"handlers");j(this,"array");this.context=t,this.array=n,this.handlers={get:(r,i,o)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?a=>{const s=r.getByID(a);if(!(!s||s.isRemoved()))return za(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return za(t,s)}:i==="getLast"?()=>za(t,r.getLast()):i==="deleteByID"?a=>{const s=Jt.deleteInternalByID(t,r,a);return za(t,s)}:i==="insertAfter"?(a,s)=>{const u=Jt.insertAfterInternal(t,r,a,s);return za(t,u)}:i==="insertBefore"?(a,s)=>{const u=Jt.insertBeforeInternal(t,r,a,s);return za(t,u)}:i==="moveBefore"?(a,s)=>{Jt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{Jt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{Jt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{Jt.moveLastInternal(t,r,a)}:XUe(i)?Vs(t,r.get(Number(i))):i==="push"?a=>Jt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>Jt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?Jt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>Jt.includes(t,r,a,s):i==="indexOf"?(a,s)=>Jt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>Jt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>Jt.toTestString(r):typeof i=="string"&&ZUe(i)?(...a)=>{const s=Array.from(r).map(u=>Vs(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>(Be.isEnabled(ir.Trivial)&&Be.trivial(`array[${i}]`),Jt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield za(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=Pp(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return Jt.insertAfterInternal(t,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(t,n,r,i){const o=t.issueTimeTicket(),a=n.getPrevCreatedAt(r);n.moveAfter(a,i,o),t.push(Xa.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(Xa.create(n.getCreatedAt(),r,i,o))}static moveFrontInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getHead();n.moveAfter(o.getCreatedAt(),r,i),t.push(Xa.create(n.getCreatedAt(),o.getCreatedAt(),r,i))}static moveLastInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getLastCreatedAt();n.moveAfter(o,r,i),t.push(Xa.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=Pp(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(w0.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return Jt.insertAfterInternal(t,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByIndex(r,i);if(o)return t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static deleteInternalByID(t,n,r){const i=t.issueTimeTicket(),o=n.delete(r,i);return t.push(ys.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let f=s;f=o)return!1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Kt.isSupport(r))return Array.from(n).map(d=>Vs(t,d)).lastIndexOf(r,a);for(let u=a;u>0;u--)if(((s=n.get(u))==null?void 0:s.getID())===r.getID())return u;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class Ug{constructor(t,n){j(this,"context");j(this,"text");this.context=t,this.text=n}initialize(t,n){this.context=t,this.text=n}getID(){return this.text.getID()}edit(t,n,r,i){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);Be.isEnabled(ir.Debug)&&Be.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?Yl(i):void 0,s=this.context.issueTimeTicket(),[u,,d,f]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new S0(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(f)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);Be.isEnabled(ir.Debug)&&Be.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=Yl(r),a=this.context.issueTimeTicket(),[s,u]=this.text.setStyle(i,o,a);for(const d of u)this.context.registerGCPair(d);return this.context.push(new x0(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([Gi.fromStruct(t[0]),Gi.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class Kg{constructor(t,n){j(this,"valueType");j(this,"value");j(this,"context");j(this,"counter");this.valueType=t,this.value=n}initialize(t,n){this.valueType=n.getValueType(),this.context=t,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Kt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ql.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Xy(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===sa){ST(e);const{value:o}=e,a=Nr.create($n.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!YI(a)){const d=Yl(a);s=new va;for(const[f,p]of Object.entries(d))s.set(f,p,i)}const u=Nr.create($n.of(i,0),r,void 0,s);t.append(u);for(const d of o)Xy(d,u,n)}}function qUe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===sa){const{value:o}=t;i=Nr.create($n.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!YI(a)){const u=Yl(a);s=new va;for(const[d,f]of Object.entries(u))s.set(d,f,r)}i=Nr.create($n.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)Xy(u,i,e)}return i}function ST(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function Dw(e){if(!e.length)return!0;if(e[0].type===sa)for(const n of e){const{type:r}=n;if(r!==sa)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");ST(n)}else for(const n of e){const{type:r}=n;if(r===sa)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Vg{constructor(t){j(this,"initialRoot");j(this,"context");j(this,"tree");this.initialRoot=t}initialize(t,n){this.context=t,this.tree=n}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Nr.create($n.of(t.issueTimeTicket(),0),Qje);const n=Nr.create($n.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)Xy(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?Yl(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ua.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?Yl(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const f of d)this.context.registerGCPair(f);this.context.push(ua.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ua.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Dw(r),r[0].type!==sa))for(const f of r){const{children:p=[]}=f;Dw(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===sa){let f="";for(const p of r){const{value:g}=p;f+=g}a.push(Nr.create($n.of(this.context.issueTimeTicket(),0),sa,f))}else a=r.map(f=>f&&qUe(this.context,f)).filter(f=>f);const[,s,u]=this.tree.edit([t,n],a.length?a.map(f=>f==null?void 0:f.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const f of s)this.context.registerGCPair(f);return this.context.push(A0.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Hi.fromStruct(t[0]),Hi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Hi.fromStruct(t[0]),Hi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Iw(e,t){return wT(e,t)}function za(e,t){if(t){if(t instanceof Kt)return t;if(t instanceof Sr)return wT(e,t);if(t instanceof jr)return YUe(e,t);if(t instanceof yi)return new Ug(e,t);if(t instanceof Ur){const n=new Kg($o.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Ei){const n=new Vg;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function Vs(e,t){const n=za(e,t);return n instanceof Kt?n.getValue():n}function Pp(e,t,n){let r;if(Kt.isSupport(t))r=Kt.of(t,n);else if(Array.isArray(t))r=jr.create(n,Jt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof Ug?(r=yi.create(Zl.create(),n),t.initialize(e,r)):t instanceof Kg?(r=Ur.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof Vg?(r=Ei.create(t.buildRoot(e),n),t.initialize(e,r)):r=Sr.create(n,e0.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const Tw=50;class QUe{constructor(){j(this,"undoStack",[]);j(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Tw&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Tw&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const eKe="yorkie-devtools-panel",tKe="yorkie-devtools-sdk";let el="disconnected";const Pw=new Map,Rf=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Rf);function cf(e,t){(t!=null&&t.force||el!=="disconnected")&&window.postMessage({source:tKe,...e},"*")}function nKe(e){if(!e.isEnableDevtools()||typeof window>"u"||Pw.has(e.getKey()))return;Rf.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==jn.StatusChanged&&r.type!==jn.Snapshot&&r.type!==jn.LocalChange&&r.type!==jn.RemoteChange&&r.type!==jn.Initialized&&r.type!==jn.Watched&&r.type!==jn.Unwatched&&r.type!==jn.PresenceChanged)||(Rf.get(e.getKey()).push(n),el==="synced"&&cf({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Pw.set(e.getKey(),[t]),cf({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==eKe)return;switch(n.data.msg){case"devtools::connect":if(el!=="disconnected")break;el="connected",cf({msg:"doc::available",docKey:e.getKey()}),Be.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":el="disconnected",Be.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":el="synced",cf({msg:"doc::sync::full",docKey:e.getKey(),events:Rf.get(e.getKey())}),Be.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Ha=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Ha||{}),jn=(e=>(e.StatusChanged="status-changed",e.ConnectionChanged="connection-changed",e.SyncStatusChanged="sync-status-changed",e.Snapshot="snapshot",e.LocalChange="local-change",e.RemoteChange="remote-change",e.Initialized="initialized",e.Watched="watched",e.Unwatched="unwatched",e.PresenceChanged="presence-changed",e.Broadcast="broadcast",e.LocalBroadcast="local-broadcast",e))(jn||{}),C2=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(C2||{}),b2=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(b2||{});class Zy{constructor(t,n){j(this,"key");j(this,"status");j(this,"opts");j(this,"changeID");j(this,"checkpoint");j(this,"localChanges");j(this,"root");j(this,"clone");j(this,"eventStream");j(this,"eventStreamObserver");j(this,"onlineClients");j(this,"presences");j(this,"history");j(this,"internalHistory");j(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=Qd.create(),this.changeID=sUe,this.checkpoint=uUe,this.localChanges=[],this.eventStream=JUe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new QUe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},nKe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Iw(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new S4(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){Be.isEnabled(ir.Trivial)&&Be.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,St.Local),u=i.getReversePresence();u&&s.push({type:"presence",value:u}),this.localChanges.push(o),s.length>0&&this.internalHistory.pushUndo(s),a.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const d=[];a.length>0&&d.push({type:"local-change",source:St.Local,value:{message:o.getMessage()||"",operations:a,actor:r,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&d.push({type:"presence-changed",source:St.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),Be.isEnabled(ir.Trivial)&&Be.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const f of u.value.operations)this.isSameElementOrChildOf(f.path,o)&&d.push(f);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}applyChangePack(t){for(t.hasSnapshot()?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),St.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();t.hasSnapshot()&&this.applyChanges(this.localChanges,St.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),this.garbageCollect(t.getMinSyncedTicket()),t.getIsRemoved()&&this.applyStatus("removed"),Be.isEnabled(ir.Trivial)&&Be.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Fi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return jg.create(this.key,n,!1,t)}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Iw(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n){const{root:r,presences:i}=En.bytesToSnapshot(n);this.root=new Qd(r),this.presences=i,this.changeID=this.changeID.syncLamport(t),this.clone=void 0,this.publish([{type:"snapshot",source:St.Remote,value:{snapshot:this.isEnableDevtools()?En.bytesToHex(n):void 0,serverSeq:t.toString()}}])}applyChanges(t,n){Be.isEnabled(ir.Debug)&&Be.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Be.isEnabled(ir.Trivial)&&Be.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of t)this.applyChange(r,n);Be.isEnabled(ir.Debug)&&Be.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,n){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,n);const r=[],i=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(i)){const a=t.getPresenceChange();switch(a.type){case vs.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:St.Remote,value:{clientID:i,presence:a.presence}});break;case vs.Clear:r.push({type:"unwatched",source:St.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:o}=t.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncLamport(t.getID().getLamport()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===St.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a}:{type:"local-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const n=t.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:St.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===yd.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:St.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===yd.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:St.Remote,value:{clientID:r,presence:o}})}else if(n===yd.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:a}=t.body.value.body,s=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:o,payload:JSON.parse(s.decode(a))}})}i.length>0&&this.publish(i)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(zg),this.publish([{source:t==="removed"?St.Remote:St.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:n,serverSeq:r}=t.value;if(!n)return;this.applySnapshot(je.fromString(r),En.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=Xl.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Fi(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const n=this.presences.get(t);return n?Fi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Fi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Fi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Fi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof Zi)){new S4(n,Fi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,St.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,St.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushRedo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:St.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:St.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=ml.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof Zi)){new S4(n,Fi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,St.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,St.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushUndo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:St.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:St.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,n,r){const i={type:"local-broadcast",value:{topic:t,payload:n},options:r};this.publish([i])}}function rKe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const iKe="yorkie-js-sdk",oKe="0.5.0",aKe="Yorkie JS SDK",sKe="./src/yorkie.ts",uKe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},lKe=["dist"],cKe={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},dKe={node:">=18.0.0",npm:">=7.1.0"},hKe={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},fKe={name:"hackerwins",email:"susukang98@gmail.com"},pKe="Apache-2.0",gKe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},mKe="https://github.com/yorkie-team/yorkie-js-sdk#readme",vKe={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},yKe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Mw={name:iKe,version:oKe,description:aKe,main:sKe,publishConfig:uKe,files:lKe,scripts:cKe,engines:dKe,repository:hKe,author:fKe,license:pKe,bugs:gKe,homepage:mKe,devDependencies:vKe,dependencies:yKe};function EKe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Mw.name+"/"+Mw.version),await e(t))}const CKe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var _f=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(_f||{});const df={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},D4={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class qy{constructor(t,n){j(this,"id");j(this,"key");j(this,"status");j(this,"attachmentMap");j(this,"apiKey");j(this,"conditions");j(this,"syncLoopDuration");j(this,"reconnectStreamDelay");j(this,"retrySyncLoopDelay");j(this,"rpcClient");j(this,"taskQueue");j(this,"processing",!1);n=n||df,this.key=n.key?n.key:bT(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||df.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||df.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||df.retrySyncLoopDelay,this.rpcClient=ZHe(jje,Eje({baseUrl:t,interceptors:[rKe(n.apiKey,n.token),EKe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Be.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Be.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Be.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Be.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Ha.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var f;const{topic:a,payload:s}=o.value,u=(f=o.options)==null?void 0:f.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:En.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=En.fromChangePack(o.changePack);return t.applyChangePack(a),t.getStatus()===Ha.Removed||(t.applyStatus(Ha.Attached),this.attachmentMap.set(t.getKey(),new GUe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),Be.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(o=>{throw Be.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:En.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=En.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Ha.Removed&&t.applyStatus(Ha.Detached),this.detachInternal(t.getKey()),Be.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw Be.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw Be.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw Be.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=En.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=En.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Be.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw Be.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!CKe(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??D4.maxRetries,s=D4.maxBackoff;let u=0;const d=p=>Math.min(D4.initialRetryInterval*2**p,s),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Be.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if(Be.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uf(),d(u-1)),Be.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw Be.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){Be.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{Be.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Be.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const n=this.attachmentMap.get(t);if(!n)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:jn.ConnectionChanged,value:C2.Connected}]),Be.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((a,s)=>{(async()=>{try{for await(const d of o)this.handleWatchDocumentsResponse(n,d),d.body.case==="initialization"&&a([o,i])}catch(d){n.doc.resetOnlineClients(),n.doc.publish([{type:jn.Initialized,source:St.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:jn.ConnectionChanged,value:C2.Disconnected}]),Be.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===yd.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[t,n]of this.attachmentMap)this.detachInternal(t),n.doc.applyStatus(Ha.Detached)}detachInternal(t){const n=this.attachmentMap.get(t);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,n){const{doc:r,docID:i}=t,o=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:En.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=En.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:jn.SyncStatusChanged,value:b2.Synced}]),r.getStatus()===Ha.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return Be.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(a=>{throw r.publish([{type:jn.SyncStatusChanged,value:b2.SyncFailed}]),Be.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof cn?t.code===mt.Canceled||t.code===mt.Unknown||t.code===mt.ResourceExhausted||t.code===mt.Unavailable?!0:((kw(t)===W.ErrClientNotActivated||kw(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{Be.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}$o.IntegerCnt,$o.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:qy,Document:Zy,Primitive:Kt,Text:Ug,Counter:Kg,Tree:Vg,LogLevel:ir,setLogLevel:CT,IntType:$o.IntegerCnt,LongType:$o.LongCnt});var w2={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(Qu,function(){var n=null,r={};C();var i=[],o=function(k){if(k=k||{},k.seed!==void 0&&k.seed!==null&&k.seed===parseInt(k.seed,10))n=k.seed;else if(typeof k.seed=="string")n=P(k.seed);else{if(k.seed!==void 0&&k.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var B,_,N;if(k.count!==null&&k.count!==void 0){for(var U=k.count,q=[],Z=0;Zq.length;){var pe=o(k);n!==null&&(k.seed=n),q.push(pe)}return k.count=U,q}return B=a(k),_=s(B,k),N=u(B,_,k),d([B,_,N],k)};function a(k){if(i.length>0){var B=I(k.hue),_=v(B),N=(B[1]-B[0])/i.length,U=parseInt((_-B[0])/N);i[U]===!0?U=(U+2)%i.length:i[U]=!0;var q=(B[0]+U*N)%359,Z=(B[0]+(U+1)*N)%359;return B=[q,Z],_=v(B),_<0&&(_=360+_),_}else{var B=p(k.hue);return _=v(B),_<0&&(_=360+_),_}}function s(k,B){if(B.hue==="monochrome")return 0;if(B.luminosity==="random")return v([0,100]);var _=g(k),N=_[0],U=_[1];switch(B.luminosity){case"bright":N=55;break;case"dark":N=U-10;break;case"light":U=55;break}return v([N,U])}function u(k,B,_){var N=f(k,B),U=100;switch(_.luminosity){case"dark":U=N+20;break;case"light":N=(U+N)/2;break;case"random":N=0,U=100;break}return v([N,U])}function d(k,B){switch(B.format){case"hsvArray":return k;case"hslArray":return D(k);case"hsl":var _=D(k);return"hsl("+_[0]+", "+_[1]+"%, "+_[2]+"%)";case"hsla":var N=D(k),Z=B.alpha||Math.random();return"hsla("+N[0]+", "+N[1]+"%, "+N[2]+"%, "+Z+")";case"rgbArray":return b(k);case"rgb":var U=b(k);return"rgb("+U.join(", ")+")";case"rgba":var q=b(k),Z=B.alpha||Math.random();return"rgba("+q.join(", ")+", "+Z+")";default:return E(k)}}function f(k,B){for(var _=m(k).lowerBounds,N=0;N<_.length-1;N++){var U=_[N][0],q=_[N][1],Z=_[N+1][0],pe=_[N+1][1];if(B>=U&&B<=Z){var me=(pe-q)/(Z-U),Ee=q-me*U;return me*B+Ee}}return 0}function p(k){if(typeof parseInt(k)=="number"){var B=parseInt(k);if(B<360&&B>0)return[B,B]}if(typeof k=="string"){if(r[k]){var _=r[k];if(_.hueRange)return _.hueRange}else if(k.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var N=A(k)[0];return[N,N]}}return[0,360]}function g(k){return m(k).saturationRange}function m(k){k>=334&&k<=360&&(k-=360);for(var B in r){var _=r[B];if(_.hueRange&&k>=_.hueRange[0]&&k<=_.hueRange[1])return r[B]}return"Color not found"}function v(k){if(n===null){var B=.618033988749895,_=Math.random();return _+=B,_%=1,Math.floor(k[0]+_*(k[1]+1-k[0]))}else{var N=k[1]||1,U=k[0]||0;n=(n*9301+49297)%233280;var q=n/233280;return Math.floor(U+q*(N-U))}}function E(k){var B=b(k);function _(U){var q=U.toString(16);return q.length==1?"0"+q:q}var N="#"+_(B[0])+_(B[1])+_(B[2]);return N}function w(k,B,_){var N=_[0][0],U=_[_.length-1][0],q=_[_.length-1][1],Z=_[0][1];r[k]={hueRange:B,lowerBounds:_,saturationRange:[N,U],brightnessRange:[q,Z]}}function C(){w("monochrome",null,[[0,0],[100,0]]),w("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),w("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),w("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),w("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),w("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),w("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),w("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function b(k){var B=k[0];B===0&&(B=1),B===360&&(B=359),B=B/360;var _=k[1]/100,N=k[2]/100,U=Math.floor(B*6),q=B*6-U,Z=N*(1-_),pe=N*(1-q*_),me=N*(1-(1-q)*_),Ee=256,G=256,H=256;switch(U){case 0:Ee=N,G=me,H=Z;break;case 1:Ee=pe,G=N,H=Z;break;case 2:Ee=Z,G=N,H=me;break;case 3:Ee=Z,G=pe,H=N;break;case 4:Ee=me,G=Z,H=N;break;case 5:Ee=N,G=Z,H=pe;break}var ne=[Math.floor(Ee*255),Math.floor(G*255),Math.floor(H*255)];return ne}function A(k){k=k.replace(/^#/,""),k=k.length===3?k.replace(/(.)/g,"$1$1"):k;var B=parseInt(k.substr(0,2),16)/255,_=parseInt(k.substr(2,2),16)/255,N=parseInt(k.substr(4,2),16)/255,U=Math.max(B,_,N),q=U-Math.min(B,_,N),Z=U?q/U:0;switch(U){case B:return[60*((_-N)/q%6)||0,Z,U];case _:return[60*((N-B)/q+2)||0,Z,U];case N:return[60*((B-_)/q+4)||0,Z,U]}}function D(k){var B=k[0],_=k[1]/100,N=k[2]/100,U=(2-_)*N;return[B,Math.round(_*N/(U<1?U:2-U)*1e4)/100,U/2*100]}function P(k){for(var B=0,_=0;_!==k.length&&!(B>=Number.MAX_SAFE_INTEGER);_++)B+=k.charCodeAt(_);return B}function I(k){if(isNaN(k)){if(typeof k=="string"){if(r[k]){var _=r[k];if(_.hueRange)return _.hueRange}else if(k.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var N=A(k)[0];return m(N).hueRange}}}else{var B=parseInt(k);if(B<360&&B>0)return m(k).hueRange}return[0,360]}return o})})(w2,w2.exports);var bKe=w2.exports;const wKe=t0(bKe),Bw=e=>{e=1831565813+(e|=0)|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};class SKe{constructor(t){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:o,seed:a}=t;this.dictionaries=i,this.separator=r,this.length=n,this.style=o,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries. Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let t=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let i;t?(i=(a=>{if(typeof a=="string"){const s=a.split("").map(d=>d.charCodeAt(0)).reduce((d,f)=>d+f,1),u=Math.floor(Number(s));return Bw(u)}return Bw(a)})(t),t=4294967296*i):i=Math.random();let o=r[Math.floor(i*r.length)]||"";if(this.style==="lowerCase")o=o.toLowerCase();else if(this.style==="capital"){const[a,...s]=o.split("");o=a.toUpperCase()+s.join("")}else this.style==="upperCase"&&(o=o.toUpperCase());return n?`${n}${this.separator}${o}`:`${o}`},"")}}const $w={separator:"_",dictionaries:[]},xKe=e=>{const t=[...e&&e.dictionaries||$w.dictionaries],n={...$w,...e,length:e&&e.length||t.length,dictionaries:t};if(!e||!e.dictionaries||!e.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new SKe(n).generate()};var AKe=["Aaren","Aarika","Abagael","Abagail","Abbe","Abbey","Abbi","Abbie","Abby","Abbye","Abigael","Abigail","Abigale","Abra","Ada","Adah","Adaline","Adan","Adara","Adda","Addi","Addia","Addie","Addy","Adel","Adela","Adelaida","Adelaide","Adele","Adelheid","Adelice","Adelina","Adelind","Adeline","Adella","Adelle","Adena","Adey","Adi","Adiana","Adina","Adora","Adore","Adoree","Adorne","Adrea","Adria","Adriaens","Adrian","Adriana","Adriane","Adrianna","Adrianne","Adriena","Adrienne","Aeriel","Aeriela","Aeriell","Afton","Ag","Agace","Agata","Agatha","Agathe","Aggi","Aggie","Aggy","Agna","Agnella","Agnes","Agnese","Agnesse","Agneta","Agnola","Agretha","Aida","Aidan","Aigneis","Aila","Aile","Ailee","Aileen","Ailene","Ailey","Aili","Ailina","Ailis","Ailsun","Ailyn","Aime","Aimee","Aimil","Aindrea","Ainslee","Ainsley","Ainslie","Ajay","Alaine","Alameda","Alana","Alanah","Alane","Alanna","Alayne","Alberta","Albertina","Albertine","Albina","Alecia","Aleda","Aleece","Aleen","Alejandra","Alejandrina","Alena","Alene","Alessandra","Aleta","Alethea","Alex","Alexa","Alexandra","Alexandrina","Alexi","Alexia","Alexina","Alexine","Alexis","Alfi","Alfie","Alfreda","Alfy","Ali","Alia","Alica","Alice","Alicea","Alicia","Alida","Alidia","Alie","Alika","Alikee","Alina","Aline","Alis","Alisa","Alisha","Alison","Alissa","Alisun","Alix","Aliza","Alla","Alleen","Allegra","Allene","Alli","Allianora","Allie","Allina","Allis","Allison","Allissa","Allix","Allsun","Allx","Ally","Allyce","Allyn","Allys","Allyson","Alma","Almeda","Almeria","Almeta","Almira","Almire","Aloise","Aloisia","Aloysia","Alta","Althea","Alvera","Alverta","Alvina","Alvinia","Alvira","Alyce","Alyda","Alys","Alysa","Alyse","Alysia","Alyson","Alyss","Alyssa","Amabel","Amabelle","Amalea","Amalee","Amaleta","Amalia","Amalie","Amalita","Amalle","Amanda","Amandi","Amandie","Amandy","Amara","Amargo","Amata","Amber","Amberly","Ambur","Ame","Amelia","Amelie","Amelina","Ameline","Amelita","Ami","Amie","Amii","Amil","Amitie","Amity","Ammamaria","Amy","Amye","Ana","Anabal","Anabel","Anabella","Anabelle","Analiese","Analise","Anallese","Anallise","Anastasia","Anastasie","Anastassia","Anatola","Andee","Andeee","Anderea","Andi","Andie","Andra","Andrea","Andreana","Andree","Andrei","Andria","Andriana","Andriette","Andromache","Andy","Anestassia","Anet","Anett","Anetta","Anette","Ange","Angel","Angela","Angele","Angelia","Angelica","Angelika","Angelina","Angeline","Angelique","Angelita","Angelle","Angie","Angil","Angy","Ania","Anica","Anissa","Anita","Anitra","Anjanette","Anjela","Ann","Ann-marie","Anna","Anna-diana","Anna-diane","Anna-maria","Annabal","Annabel","Annabela","Annabell","Annabella","Annabelle","Annadiana","Annadiane","Annalee","Annaliese","Annalise","Annamaria","Annamarie","Anne","Anne-corinne","Anne-marie","Annecorinne","Anneliese","Annelise","Annemarie","Annetta","Annette","Anni","Annice","Annie","Annis","Annissa","Annmaria","Annmarie","Annnora","Annora","Anny","Anselma","Ansley","Anstice","Anthe","Anthea","Anthia","Anthiathia","Antoinette","Antonella","Antonetta","Antonia","Antonie","Antonietta","Antonina","Anya","Appolonia","April","Aprilette","Ara","Arabel","Arabela","Arabele","Arabella","Arabelle","Arda","Ardath","Ardeen","Ardelia","Ardelis","Ardella","Ardelle","Arden","Ardene","Ardenia","Ardine","Ardis","Ardisj","Ardith","Ardra","Ardyce","Ardys","Ardyth","Aretha","Ariadne","Ariana","Aridatha","Ariel","Ariela","Ariella","Arielle","Arlana","Arlee","Arleen","Arlen","Arlena","Arlene","Arleta","Arlette","Arleyne","Arlie","Arliene","Arlina","Arlinda","Arline","Arluene","Arly","Arlyn","Arlyne","Aryn","Ashely","Ashia","Ashien","Ashil","Ashla","Ashlan","Ashlee","Ashleigh","Ashlen","Ashley","Ashli","Ashlie","Ashly","Asia","Astra","Astrid","Astrix","Atalanta","Athena","Athene","Atlanta","Atlante","Auberta","Aubine","Aubree","Aubrette","Aubrey","Aubrie","Aubry","Audi","Audie","Audra","Audre","Audrey","Audrie","Audry","Audrye","Audy","Augusta","Auguste","Augustina","Augustine","Aundrea","Aura","Aurea","Aurel","Aurelea","Aurelia","Aurelie","Auria","Aurie","Aurilia","Aurlie","Auroora","Aurora","Aurore","Austin","Austina","Austine","Ava","Aveline","Averil","Averyl","Avie","Avis","Aviva","Avivah","Avril","Avrit","Ayn","Bab","Babara","Babb","Babbette","Babbie","Babette","Babita","Babs","Bambi","Bambie","Bamby","Barb","Barbabra","Barbara","Barbara-anne","Barbaraanne","Barbe","Barbee","Barbette","Barbey","Barbi","Barbie","Barbra","Barby","Bari","Barrie","Barry","Basia","Bathsheba","Batsheva","Bea","Beatrice","Beatrisa","Beatrix","Beatriz","Bebe","Becca","Becka","Becki","Beckie","Becky","Bee","Beilul","Beitris","Bekki","Bel","Belia","Belicia","Belinda","Belita","Bell","Bella","Bellanca","Belle","Bellina","Belva","Belvia","Bendite","Benedetta","Benedicta","Benedikta","Benetta","Benita","Benni","Bennie","Benny","Benoite","Berenice","Beret","Berget","Berna","Bernadene","Bernadette","Bernadina","Bernadine","Bernardina","Bernardine","Bernelle","Bernete","Bernetta","Bernette","Berni","Bernice","Bernie","Bernita","Berny","Berri","Berrie","Berry","Bert","Berta","Berte","Bertha","Berthe","Berti","Bertie","Bertina","Bertine","Berty","Beryl","Beryle","Bess","Bessie","Bessy","Beth","Bethanne","Bethany","Bethena","Bethina","Betsey","Betsy","Betta","Bette","Bette-ann","Betteann","Betteanne","Betti","Bettina","Bettine","Betty","Bettye","Beulah","Bev","Beverie","Beverlee","Beverley","Beverlie","Beverly","Bevvy","Bianca","Bianka","Bibbie","Bibby","Bibbye","Bibi","Biddie","Biddy","Bidget","Bili","Bill","Billi","Billie","Billy","Billye","Binni","Binnie","Binny","Bird","Birdie","Birgit","Birgitta","Blair","Blaire","Blake","Blakelee","Blakeley","Blanca","Blanch","Blancha","Blanche","Blinni","Blinnie","Blinny","Bliss","Blisse","Blithe","Blondell","Blondelle","Blondie","Blondy","Blythe","Bobbe","Bobbee","Bobbette","Bobbi","Bobbie","Bobby","Bobbye","Bobette","Bobina","Bobine","Bobinette","Bonita","Bonnee","Bonni","Bonnibelle","Bonnie","Bonny","Brana","Brandais","Brande","Brandea","Brandi","Brandice","Brandie","Brandise","Brandy","Breanne","Brear","Bree","Breena","Bren","Brena","Brenda","Brenn","Brenna","Brett","Bria","Briana","Brianna","Brianne","Bride","Bridget","Bridgette","Bridie","Brier","Brietta","Brigid","Brigida","Brigit","Brigitta","Brigitte","Brina","Briney","Brinn","Brinna","Briny","Brit","Brita","Britney","Britni","Britt","Britta","Brittan","Brittaney","Brittani","Brittany","Britte","Britteny","Brittne","Brittney","Brittni","Brook","Brooke","Brooks","Brunhilda","Brunhilde","Bryana","Bryn","Bryna","Brynn","Brynna","Brynne","Buffy","Bunni","Bunnie","Bunny","Cacilia","Cacilie","Cahra","Cairistiona","Caitlin","Caitrin","Cal","Calida","Calla","Calley","Calli","Callida","Callie","Cally","Calypso","Cam","Camala","Camel","Camella","Camellia","Cami","Camila","Camile","Camilla","Camille","Cammi","Cammie","Cammy","Candace","Candi","Candice","Candida","Candide","Candie","Candis","Candra","Candy","Caprice","Cara","Caralie","Caren","Carena","Caresa","Caressa","Caresse","Carey","Cari","Caria","Carie","Caril","Carilyn","Carin","Carina","Carine","Cariotta","Carissa","Carita","Caritta","Carla","Carlee","Carleen","Carlen","Carlene","Carley","Carlie","Carlin","Carlina","Carline","Carlita","Carlota","Carlotta","Carly","Carlye","Carlyn","Carlynn","Carlynne","Carma","Carmel","Carmela","Carmelia","Carmelina","Carmelita","Carmella","Carmelle","Carmen","Carmencita","Carmina","Carmine","Carmita","Carmon","Caro","Carol","Carol-jean","Carola","Carolan","Carolann","Carole","Carolee","Carolin","Carolina","Caroline","Caroljean","Carolyn","Carolyne","Carolynn","Caron","Carree","Carri","Carrie","Carrissa","Carroll","Carry","Cary","Caryl","Caryn","Casandra","Casey","Casi","Casie","Cass","Cassandra","Cassandre","Cassandry","Cassaundra","Cassey","Cassi","Cassie","Cassondra","Cassy","Catarina","Cate","Caterina","Catha","Catharina","Catharine","Cathe","Cathee","Catherin","Catherina","Catherine","Cathi","Cathie","Cathleen","Cathlene","Cathrin","Cathrine","Cathryn","Cathy","Cathyleen","Cati","Catie","Catina","Catlaina","Catlee","Catlin","Catrina","Catriona","Caty","Caye","Cayla","Cecelia","Cecil","Cecile","Ceciley","Cecilia","Cecilla","Cecily","Ceil","Cele","Celene","Celesta","Celeste","Celestia","Celestina","Celestine","Celestyn","Celestyna","Celia","Celie","Celina","Celinda","Celine","Celinka","Celisse","Celka","Celle","Cesya","Chad","Chanda","Chandal","Chandra","Channa","Chantal","Chantalle","Charil","Charin","Charis","Charissa","Charisse","Charita","Charity","Charla","Charlean","Charleen","Charlena","Charlene","Charline","Charlot","Charlotta","Charlotte","Charmain","Charmaine","Charmane","Charmian","Charmine","Charmion","Charo","Charyl","Chastity","Chelsae","Chelsea","Chelsey","Chelsie","Chelsy","Cher","Chere","Cherey","Cheri","Cherianne","Cherice","Cherida","Cherie","Cherilyn","Cherilynn","Cherin","Cherise","Cherish","Cherlyn","Cherri","Cherrita","Cherry","Chery","Cherye","Cheryl","Cheslie","Chiarra","Chickie","Chicky","Chiquia","Chiquita","Chlo","Chloe","Chloette","Chloris","Chris","Chrissie","Chrissy","Christa","Christabel","Christabella","Christal","Christalle","Christan","Christean","Christel","Christen","Christi","Christian","Christiana","Christiane","Christie","Christin","Christina","Christine","Christy","Christye","Christyna","Chrysa","Chrysler","Chrystal","Chryste","Chrystel","Cicely","Cicily","Ciel","Cilka","Cinda","Cindee","Cindelyn","Cinderella","Cindi","Cindie","Cindra","Cindy","Cinnamon","Cissiee","Cissy","Clair","Claire","Clara","Clarabelle","Clare","Claresta","Clareta","Claretta","Clarette","Clarey","Clari","Claribel","Clarice","Clarie","Clarinda","Clarine","Clarissa","Clarisse","Clarita","Clary","Claude","Claudelle","Claudetta","Claudette","Claudia","Claudie","Claudina","Claudine","Clea","Clem","Clemence","Clementia","Clementina","Clementine","Clemmie","Clemmy","Cleo","Cleopatra","Clerissa","Clio","Clo","Cloe","Cloris","Clotilda","Clovis","Codee","Codi","Codie","Cody","Coleen","Colene","Coletta","Colette","Colleen","Collen","Collete","Collette","Collie","Colline","Colly","Con","Concettina","Conchita","Concordia","Conni","Connie","Conny","Consolata","Constance","Constancia","Constancy","Constanta","Constantia","Constantina","Constantine","Consuela","Consuelo","Cookie","Cora","Corabel","Corabella","Corabelle","Coral","Coralie","Coraline","Coralyn","Cordelia","Cordelie","Cordey","Cordi","Cordie","Cordula","Cordy","Coreen","Corella","Corenda","Corene","Coretta","Corette","Corey","Cori","Corie","Corilla","Corina","Corine","Corinna","Corinne","Coriss","Corissa","Corliss","Corly","Cornela","Cornelia","Cornelle","Cornie","Corny","Correna","Correy","Corri","Corrianne","Corrie","Corrina","Corrine","Corrinne","Corry","Cortney","Cory","Cosetta","Cosette","Costanza","Courtenay","Courtnay","Courtney","Crin","Cris","Crissie","Crissy","Crista","Cristabel","Cristal","Cristen","Cristi","Cristie","Cristin","Cristina","Cristine","Cristionna","Cristy","Crysta","Crystal","Crystie","Cthrine","Cyb","Cybil","Cybill","Cymbre","Cynde","Cyndi","Cyndia","Cyndie","Cyndy","Cynthea","Cynthia","Cynthie","Cynthy","Dacey","Dacia","Dacie","Dacy","Dael","Daffi","Daffie","Daffy","Dagmar","Dahlia","Daile","Daisey","Daisi","Daisie","Daisy","Dale","Dalenna","Dalia","Dalila","Dallas","Daloris","Damara","Damaris","Damita","Dana","Danell","Danella","Danette","Dani","Dania","Danica","Danice","Daniela","Daniele","Daniella","Danielle","Danika","Danila","Danit","Danita","Danna","Danni","Dannie","Danny","Dannye","Danya","Danyelle","Danyette","Daphene","Daphna","Daphne","Dara","Darb","Darbie","Darby","Darcee","Darcey","Darci","Darcie","Darcy","Darda","Dareen","Darell","Darelle","Dari","Daria","Darice","Darla","Darleen","Darlene","Darline","Darlleen","Daron","Darrelle","Darryl","Darsey","Darsie","Darya","Daryl","Daryn","Dasha","Dasi","Dasie","Dasya","Datha","Daune","Daveen","Daveta","Davida","Davina","Davine","Davita","Dawn","Dawna","Dayle","Dayna","Ddene","De","Deana","Deane","Deanna","Deanne","Deb","Debbi","Debbie","Debby","Debee","Debera","Debi","Debor","Debora","Deborah","Debra","Dede","Dedie","Dedra","Dee","Deeann","Deeanne","Deedee","Deena","Deerdre","Deeyn","Dehlia","Deidre","Deina","Deirdre","Del","Dela","Delcina","Delcine","Delia","Delila","Delilah","Delinda","Dell","Della","Delly","Delora","Delores","Deloria","Deloris","Delphine","Delphinia","Demeter","Demetra","Demetria","Demetris","Dena","Deni","Denice","Denise","Denna","Denni","Dennie","Denny","Deny","Denys","Denyse","Deonne","Desdemona","Desirae","Desiree","Desiri","Deva","Devan","Devi","Devin","Devina","Devinne","Devon","Devondra","Devonna","Devonne","Devora","Di","Diahann","Dian","Diana","Diandra","Diane","Diane-marie","Dianemarie","Diann","Dianna","Dianne","Diannne","Didi","Dido","Diena","Dierdre","Dina","Dinah","Dinnie","Dinny","Dion","Dione","Dionis","Dionne","Dita","Dix","Dixie","Dniren","Dode","Dodi","Dodie","Dody","Doe","Doll","Dolley","Dolli","Dollie","Dolly","Dolores","Dolorita","Doloritas","Domeniga","Dominga","Domini","Dominica","Dominique","Dona","Donella","Donelle","Donetta","Donia","Donica","Donielle","Donna","Donnamarie","Donni","Donnie","Donny","Dora","Doralia","Doralin","Doralyn","Doralynn","Doralynne","Dore","Doreen","Dorelia","Dorella","Dorelle","Dorena","Dorene","Doretta","Dorette","Dorey","Dori","Doria","Dorian","Dorice","Dorie","Dorine","Doris","Dorisa","Dorise","Dorita","Doro","Dorolice","Dorolisa","Dorotea","Doroteya","Dorothea","Dorothee","Dorothy","Dorree","Dorri","Dorrie","Dorris","Dorry","Dorthea","Dorthy","Dory","Dosi","Dot","Doti","Dotti","Dottie","Dotty","Dre","Dreddy","Dredi","Drona","Dru","Druci","Drucie","Drucill","Drucy","Drusi","Drusie","Drusilla","Drusy","Dulce","Dulcea","Dulci","Dulcia","Dulciana","Dulcie","Dulcine","Dulcinea","Dulcy","Dulsea","Dusty","Dyan","Dyana","Dyane","Dyann","Dyanna","Dyanne","Dyna","Dynah","Eachelle","Eada","Eadie","Eadith","Ealasaid","Eartha","Easter","Eba","Ebba","Ebonee","Ebony","Eda","Eddi","Eddie","Eddy","Ede","Edee","Edeline","Eden","Edi","Edie","Edin","Edita","Edith","Editha","Edithe","Ediva","Edna","Edwina","Edy","Edyth","Edythe","Effie","Eileen","Eilis","Eimile","Eirena","Ekaterina","Elaina","Elaine","Elana","Elane","Elayne","Elberta","Elbertina","Elbertine","Eleanor","Eleanora","Eleanore","Electra","Eleen","Elena","Elene","Eleni","Elenore","Eleonora","Eleonore","Elfie","Elfreda","Elfrida","Elfrieda","Elga","Elianora","Elianore","Elicia","Elie","Elinor","Elinore","Elisa","Elisabet","Elisabeth","Elisabetta","Elise","Elisha","Elissa","Elita","Eliza","Elizabet","Elizabeth","Elka","Elke","Ella","Elladine","Elle","Ellen","Ellene","Ellette","Elli","Ellie","Ellissa","Elly","Ellyn","Ellynn","Elmira","Elna","Elnora","Elnore","Eloisa","Eloise","Elonore","Elora","Elsa","Elsbeth","Else","Elset","Elsey","Elsi","Elsie","Elsinore","Elspeth","Elsy","Elva","Elvera","Elvina","Elvira","Elwira","Elyn","Elyse","Elysee","Elysha","Elysia","Elyssa","Em","Ema","Emalee","Emalia","Emelda","Emelia","Emelina","Emeline","Emelita","Emelyne","Emera","Emilee","Emili","Emilia","Emilie","Emiline","Emily","Emlyn","Emlynn","Emlynne","Emma","Emmalee","Emmaline","Emmalyn","Emmalynn","Emmalynne","Emmeline","Emmey","Emmi","Emmie","Emmy","Emmye","Emogene","Emyle","Emylee","Engracia","Enid","Enrica","Enrichetta","Enrika","Enriqueta","Eolanda","Eolande","Eran","Erda","Erena","Erica","Ericha","Ericka","Erika","Erin","Erina","Erinn","Erinna","Erma","Ermengarde","Ermentrude","Ermina","Erminia","Erminie","Erna","Ernaline","Ernesta","Ernestine","Ertha","Eryn","Esma","Esmaria","Esme","Esmeralda","Essa","Essie","Essy","Esta","Estel","Estele","Estell","Estella","Estelle","Ester","Esther","Estrella","Estrellita","Ethel","Ethelda","Ethelin","Ethelind","Etheline","Ethelyn","Ethyl","Etta","Etti","Ettie","Etty","Eudora","Eugenia","Eugenie","Eugine","Eula","Eulalie","Eunice","Euphemia","Eustacia","Eva","Evaleen","Evangelia","Evangelin","Evangelina","Evangeline","Evania","Evanne","Eve","Eveleen","Evelina","Eveline","Evelyn","Evey","Evie","Evita","Evonne","Evvie","Evvy","Evy","Eyde","Eydie","Ezmeralda","Fae","Faina","Faith","Fallon","Fan","Fanchette","Fanchon","Fancie","Fancy","Fanechka","Fania","Fanni","Fannie","Fanny","Fanya","Fara","Farah","Farand","Farica","Farra","Farrah","Farrand","Faun","Faunie","Faustina","Faustine","Fawn","Fawne","Fawnia","Fay","Faydra","Faye","Fayette","Fayina","Fayre","Fayth","Faythe","Federica","Fedora","Felecia","Felicdad","Felice","Felicia","Felicity","Felicle","Felipa","Felisha","Felita","Feliza","Fenelia","Feodora","Ferdinanda","Ferdinande","Fern","Fernanda","Fernande","Fernandina","Ferne","Fey","Fiann","Fianna","Fidela","Fidelia","Fidelity","Fifi","Fifine","Filia","Filide","Filippa","Fina","Fiona","Fionna","Fionnula","Fiorenze","Fleur","Fleurette","Flo","Flor","Flora","Florance","Flore","Florella","Florence","Florencia","Florentia","Florenza","Florette","Flori","Floria","Florida","Florie","Florina","Florinda","Floris","Florri","Florrie","Florry","Flory","Flossi","Flossie","Flossy","Flss","Fran","Francene","Frances","Francesca","Francine","Francisca","Franciska","Francoise","Francyne","Frank","Frankie","Franky","Franni","Frannie","Franny","Frayda","Fred","Freda","Freddi","Freddie","Freddy","Fredelia","Frederica","Fredericka","Frederique","Fredi","Fredia","Fredra","Fredrika","Freida","Frieda","Friederike","Fulvia","Gabbey","Gabbi","Gabbie","Gabey","Gabi","Gabie","Gabriel","Gabriela","Gabriell","Gabriella","Gabrielle","Gabriellia","Gabrila","Gaby","Gae","Gael","Gail","Gale","Galina","Garland","Garnet","Garnette","Gates","Gavra","Gavrielle","Gay","Gaye","Gayel","Gayla","Gayle","Gayleen","Gaylene","Gaynor","Gelya","Gena","Gene","Geneva","Genevieve","Genevra","Genia","Genna","Genni","Gennie","Gennifer","Genny","Genovera","Genvieve","George","Georgeanna","Georgeanne","Georgena","Georgeta","Georgetta","Georgette","Georgia","Georgiana","Georgianna","Georgianne","Georgie","Georgina","Georgine","Geralda","Geraldine","Gerda","Gerhardine","Geri","Gerianna","Gerianne","Gerladina","Germain","Germaine","Germana","Gerri","Gerrie","Gerrilee","Gerry","Gert","Gerta","Gerti","Gertie","Gertrud","Gertruda","Gertrude","Gertrudis","Gerty","Giacinta","Giana","Gianina","Gianna","Gigi","Gilberta","Gilberte","Gilbertina","Gilbertine","Gilda","Gilemette","Gill","Gillan","Gilli","Gillian","Gillie","Gilligan","Gilly","Gina","Ginelle","Ginevra","Ginger","Ginni","Ginnie","Ginnifer","Ginny","Giorgia","Giovanna","Gipsy","Giralda","Gisela","Gisele","Gisella","Giselle","Giuditta","Giulia","Giulietta","Giustina","Gizela","Glad","Gladi","Gladys","Gleda","Glen","Glenda","Glenine","Glenn","Glenna","Glennie","Glennis","Glori","Gloria","Gloriana","Gloriane","Glory","Glyn","Glynda","Glynis","Glynnis","Gnni","Godiva","Golda","Goldarina","Goldi","Goldia","Goldie","Goldina","Goldy","Grace","Gracia","Gracie","Grata","Gratia","Gratiana","Gray","Grayce","Grazia","Greer","Greta","Gretal","Gretchen","Grete","Gretel","Grethel","Gretna","Gretta","Grier","Griselda","Grissel","Guendolen","Guenevere","Guenna","Guglielma","Gui","Guillema","Guillemette","Guinevere","Guinna","Gunilla","Gus","Gusella","Gussi","Gussie","Gussy","Gusta","Gusti","Gustie","Gusty","Gwen","Gwendolen","Gwendolin","Gwendolyn","Gweneth","Gwenette","Gwenneth","Gwenni","Gwennie","Gwenny","Gwenora","Gwenore","Gwyn","Gwyneth","Gwynne","Gypsy","Hadria","Hailee","Haily","Haleigh","Halette","Haley","Hali","Halie","Halimeda","Halley","Halli","Hallie","Hally","Hana","Hanna","Hannah","Hanni","Hannie","Hannis","Hanny","Happy","Harlene","Harley","Harli","Harlie","Harmonia","Harmonie","Harmony","Harri","Harrie","Harriet","Harriett","Harrietta","Harriette","Harriot","Harriott","Hatti","Hattie","Hatty","Hayley","Hazel","Heath","Heather","Heda","Hedda","Heddi","Heddie","Hedi","Hedvig","Hedvige","Hedwig","Hedwiga","Hedy","Heida","Heidi","Heidie","Helaina","Helaine","Helen","Helen-elizabeth","Helena","Helene","Helenka","Helga","Helge","Helli","Heloise","Helsa","Helyn","Hendrika","Henka","Henrie","Henrieta","Henrietta","Henriette","Henryetta","Hephzibah","Hermia","Hermina","Hermine","Herminia","Hermione","Herta","Hertha","Hester","Hesther","Hestia","Hetti","Hettie","Hetty","Hilary","Hilda","Hildagard","Hildagarde","Hilde","Hildegaard","Hildegarde","Hildy","Hillary","Hilliary","Hinda","Holli","Hollie","Holly","Holly-anne","Hollyanne","Honey","Honor","Honoria","Hope","Horatia","Hortense","Hortensia","Hulda","Hyacinth","Hyacintha","Hyacinthe","Hyacinthia","Hyacinthie","Hynda","Ianthe","Ibbie","Ibby","Ida","Idalia","Idalina","Idaline","Idell","Idelle","Idette","Ileana","Ileane","Ilene","Ilise","Ilka","Illa","Ilsa","Ilse","Ilysa","Ilyse","Ilyssa","Imelda","Imogen","Imogene","Imojean","Ina","Indira","Ines","Inesita","Inessa","Inez","Inga","Ingaberg","Ingaborg","Inge","Ingeberg","Ingeborg","Inger","Ingrid","Ingunna","Inna","Iolande","Iolanthe","Iona","Iormina","Ira","Irena","Irene","Irina","Iris","Irita","Irma","Isa","Isabel","Isabelita","Isabella","Isabelle","Isadora","Isahella","Iseabal","Isidora","Isis","Isobel","Issi","Issie","Issy","Ivett","Ivette","Ivie","Ivonne","Ivory","Ivy","Izabel","Jacenta","Jacinda","Jacinta","Jacintha","Jacinthe","Jackelyn","Jacki","Jackie","Jacklin","Jacklyn","Jackquelin","Jackqueline","Jacky","Jaclin","Jaclyn","Jacquelin","Jacqueline","Jacquelyn","Jacquelynn","Jacquenetta","Jacquenette","Jacquetta","Jacquette","Jacqui","Jacquie","Jacynth","Jada","Jade","Jaime","Jaimie","Jaine","Jami","Jamie","Jamima","Jammie","Jan","Jana","Janaya","Janaye","Jandy","Jane","Janean","Janeczka","Janeen","Janel","Janela","Janella","Janelle","Janene","Janenna","Janessa","Janet","Janeta","Janetta","Janette","Janeva","Janey","Jania","Janice","Janie","Janifer","Janina","Janine","Janis","Janith","Janka","Janna","Jannel","Jannelle","Janot","Jany","Jaquelin","Jaquelyn","Jaquenetta","Jaquenette","Jaquith","Jasmin","Jasmina","Jasmine","Jayme","Jaymee","Jayne","Jaynell","Jazmin","Jean","Jeana","Jeane","Jeanelle","Jeanette","Jeanie","Jeanine","Jeanna","Jeanne","Jeannette","Jeannie","Jeannine","Jehanna","Jelene","Jemie","Jemima","Jemimah","Jemmie","Jemmy","Jen","Jena","Jenda","Jenelle","Jeni","Jenica","Jeniece","Jenifer","Jeniffer","Jenilee","Jenine","Jenn","Jenna","Jennee","Jennette","Jenni","Jennica","Jennie","Jennifer","Jennilee","Jennine","Jenny","Jeralee","Jere","Jeri","Jermaine","Jerrie","Jerrilee","Jerrilyn","Jerrine","Jerry","Jerrylee","Jess","Jessa","Jessalin","Jessalyn","Jessamine","Jessamyn","Jesse","Jesselyn","Jessi","Jessica","Jessie","Jessika","Jessy","Jewel","Jewell","Jewelle","Jill","Jillana","Jillane","Jillayne","Jilleen","Jillene","Jilli","Jillian","Jillie","Jilly","Jinny","Jo","Jo-ann","Jo-anne","Joan","Joana","Joane","Joanie","Joann","Joanna","Joanne","Joannes","Jobey","Jobi","Jobie","Jobina","Joby","Jobye","Jobyna","Jocelin","Joceline","Jocelyn","Jocelyne","Jodee","Jodi","Jodie","Jody","Joeann","Joela","Joelie","Joell","Joella","Joelle","Joellen","Joelly","Joellyn","Joelynn","Joete","Joey","Johanna","Johannah","Johna","Johnath","Johnette","Johnna","Joice","Jojo","Jolee","Joleen","Jolene","Joletta","Joli","Jolie","Joline","Joly","Jolyn","Jolynn","Jonell","Joni","Jonie","Jonis","Jordain","Jordan","Jordana","Jordanna","Jorey","Jori","Jorie","Jorrie","Jorry","Joscelin","Josee","Josefa","Josefina","Josepha","Josephina","Josephine","Josey","Josi","Josie","Josselyn","Josy","Jourdan","Joy","Joya","Joyan","Joyann","Joyce","Joycelin","Joye","Jsandye","Juana","Juanita","Judi","Judie","Judith","Juditha","Judy","Judye","Juieta","Julee","Juli","Julia","Juliana","Juliane","Juliann","Julianna","Julianne","Julie","Julienne","Juliet","Julieta","Julietta","Juliette","Julina","Juline","Julissa","Julita","June","Junette","Junia","Junie","Junina","Justina","Justine","Justinn","Jyoti","Kacey","Kacie","Kacy","Kaela","Kai","Kaia","Kaila","Kaile","Kailey","Kaitlin","Kaitlyn","Kaitlynn","Kaja","Kakalina","Kala","Kaleena","Kali","Kalie","Kalila","Kalina","Kalinda","Kalindi","Kalli","Kally","Kameko","Kamila","Kamilah","Kamillah","Kandace","Kandy","Kania","Kanya","Kara","Kara-lynn","Karalee","Karalynn","Kare","Karee","Karel","Karen","Karena","Kari","Karia","Karie","Karil","Karilynn","Karin","Karina","Karine","Kariotta","Karisa","Karissa","Karita","Karla","Karlee","Karleen","Karlen","Karlene","Karlie","Karlotta","Karlotte","Karly","Karlyn","Karmen","Karna","Karol","Karola","Karole","Karolina","Karoline","Karoly","Karon","Karrah","Karrie","Karry","Kary","Karyl","Karylin","Karyn","Kasey","Kass","Kassandra","Kassey","Kassi","Kassia","Kassie","Kat","Kata","Katalin","Kate","Katee","Katerina","Katerine","Katey","Kath","Katha","Katharina","Katharine","Katharyn","Kathe","Katherina","Katherine","Katheryn","Kathi","Kathie","Kathleen","Kathlin","Kathrine","Kathryn","Kathryne","Kathy","Kathye","Kati","Katie","Katina","Katine","Katinka","Katleen","Katlin","Katrina","Katrine","Katrinka","Katti","Kattie","Katuscha","Katusha","Katy","Katya","Kay","Kaycee","Kaye","Kayla","Kayle","Kaylee","Kayley","Kaylil","Kaylyn","Keeley","Keelia","Keely","Kelcey","Kelci","Kelcie","Kelcy","Kelila","Kellen","Kelley","Kelli","Kellia","Kellie","Kellina","Kellsie","Kelly","Kellyann","Kelsey","Kelsi","Kelsy","Kendra","Kendre","Kenna","Keri","Keriann","Kerianne","Kerri","Kerrie","Kerrill","Kerrin","Kerry","Kerstin","Kesley","Keslie","Kessia","Kessiah","Ketti","Kettie","Ketty","Kevina","Kevyn","Ki","Kiah","Kial","Kiele","Kiersten","Kikelia","Kiley","Kim","Kimberlee","Kimberley","Kimberli","Kimberly","Kimberlyn","Kimbra","Kimmi","Kimmie","Kimmy","Kinna","Kip","Kipp","Kippie","Kippy","Kira","Kirbee","Kirbie","Kirby","Kiri","Kirsten","Kirsteni","Kirsti","Kirstin","Kirstyn","Kissee","Kissiah","Kissie","Kit","Kitti","Kittie","Kitty","Kizzee","Kizzie","Klara","Klarika","Klarrisa","Konstance","Konstanze","Koo","Kora","Koral","Koralle","Kordula","Kore","Korella","Koren","Koressa","Kori","Korie","Korney","Korrie","Korry","Kris","Krissie","Krissy","Krista","Kristal","Kristan","Kriste","Kristel","Kristen","Kristi","Kristien","Kristin","Kristina","Kristine","Kristy","Kristyn","Krysta","Krystal","Krystalle","Krystle","Krystyna","Kyla","Kyle","Kylen","Kylie","Kylila","Kylynn","Kym","Kynthia","Kyrstin","Lacee","Lacey","Lacie","Lacy","Ladonna","Laetitia","Laina","Lainey","Lana","Lanae","Lane","Lanette","Laney","Lani","Lanie","Lanita","Lanna","Lanni","Lanny","Lara","Laraine","Lari","Larina","Larine","Larisa","Larissa","Lark","Laryssa","Latashia","Latia","Latisha","Latrena","Latrina","Laura","Lauraine","Laural","Lauralee","Laure","Lauree","Laureen","Laurel","Laurella","Lauren","Laurena","Laurene","Lauretta","Laurette","Lauri","Laurianne","Laurice","Laurie","Lauryn","Lavena","Laverna","Laverne","Lavina","Lavinia","Lavinie","Layla","Layne","Layney","Lea","Leah","Leandra","Leann","Leanna","Leanor","Leanora","Lebbie","Leda","Lee","Leeann","Leeanne","Leela","Leelah","Leena","Leesa","Leese","Legra","Leia","Leigh","Leigha","Leila","Leilah","Leisha","Lela","Lelah","Leland","Lelia","Lena","Lenee","Lenette","Lenka","Lenna","Lenora","Lenore","Leodora","Leoine","Leola","Leoline","Leona","Leonanie","Leone","Leonelle","Leonie","Leonora","Leonore","Leontine","Leontyne","Leora","Leshia","Lesley","Lesli","Leslie","Lesly","Lesya","Leta","Lethia","Leticia","Letisha","Letitia","Letizia","Letta","Letti","Lettie","Letty","Lexi","Lexie","Lexine","Lexis","Lexy","Leyla","Lezlie","Lia","Lian","Liana","Liane","Lianna","Lianne","Lib","Libbey","Libbi","Libbie","Libby","Licha","Lida","Lidia","Liesa","Lil","Lila","Lilah","Lilas","Lilia","Lilian","Liliane","Lilias","Lilith","Lilla","Lilli","Lillian","Lillis","Lilllie","Lilly","Lily","Lilyan","Lin","Lina","Lind","Linda","Lindi","Lindie","Lindsay","Lindsey","Lindsy","Lindy","Linea","Linell","Linet","Linette","Linn","Linnea","Linnell","Linnet","Linnie","Linzy","Lira","Lisa","Lisabeth","Lisbeth","Lise","Lisetta","Lisette","Lisha","Lishe","Lissa","Lissi","Lissie","Lissy","Lita","Liuka","Liv","Liva","Livia","Livvie","Livvy","Livvyy","Livy","Liz","Liza","Lizabeth","Lizbeth","Lizette","Lizzie","Lizzy","Loella","Lois","Loise","Lola","Loleta","Lolita","Lolly","Lona","Lonee","Loni","Lonna","Lonni","Lonnie","Lora","Lorain","Loraine","Loralee","Loralie","Loralyn","Loree","Loreen","Lorelei","Lorelle","Loren","Lorena","Lorene","Lorenza","Loretta","Lorette","Lori","Loria","Lorianna","Lorianne","Lorie","Lorilee","Lorilyn","Lorinda","Lorine","Lorita","Lorna","Lorne","Lorraine","Lorrayne","Lorri","Lorrie","Lorrin","Lorry","Lory","Lotta","Lotte","Lotti","Lottie","Lotty","Lou","Louella","Louisa","Louise","Louisette","Loutitia","Lu","Luce","Luci","Lucia","Luciana","Lucie","Lucienne","Lucila","Lucilia","Lucille","Lucina","Lucinda","Lucine","Lucita","Lucky","Lucretia","Lucy","Ludovika","Luella","Luelle","Luisa","Luise","Lula","Lulita","Lulu","Lura","Lurette","Lurleen","Lurlene","Lurline","Lusa","Luz","Lyda","Lydia","Lydie","Lyn","Lynda","Lynde","Lyndel","Lyndell","Lyndsay","Lyndsey","Lyndsie","Lyndy","Lynea","Lynelle","Lynett","Lynette","Lynn","Lynna","Lynne","Lynnea","Lynnell","Lynnelle","Lynnet","Lynnett","Lynnette","Lynsey","Lyssa","Mab","Mabel","Mabelle","Mable","Mada","Madalena","Madalyn","Maddalena","Maddi","Maddie","Maddy","Madel","Madelaine","Madeleine","Madelena","Madelene","Madelin","Madelina","Madeline","Madella","Madelle","Madelon","Madelyn","Madge","Madlen","Madlin","Madonna","Mady","Mae","Maegan","Mag","Magda","Magdaia","Magdalen","Magdalena","Magdalene","Maggee","Maggi","Maggie","Maggy","Mahala","Mahalia","Maia","Maible","Maiga","Maighdiln","Mair","Maire","Maisey","Maisie","Maitilde","Mala","Malanie","Malena","Malia","Malina","Malinda","Malinde","Malissa","Malissia","Mallissa","Mallorie","Mallory","Malorie","Malory","Malva","Malvina","Malynda","Mame","Mamie","Manda","Mandi","Mandie","Mandy","Manon","Manya","Mara","Marabel","Marcela","Marcelia","Marcella","Marcelle","Marcellina","Marcelline","Marchelle","Marci","Marcia","Marcie","Marcile","Marcille","Marcy","Mareah","Maren","Marena","Maressa","Marga","Margalit","Margalo","Margaret","Margareta","Margarete","Margaretha","Margarethe","Margaretta","Margarette","Margarita","Margaux","Marge","Margeaux","Margery","Marget","Margette","Margi","Margie","Margit","Margo","Margot","Margret","Marguerite","Margy","Mari","Maria","Mariam","Marian","Mariana","Mariann","Marianna","Marianne","Maribel","Maribelle","Maribeth","Marice","Maridel","Marie","Marie-ann","Marie-jeanne","Marieann","Mariejeanne","Mariel","Mariele","Marielle","Mariellen","Marietta","Mariette","Marigold","Marijo","Marika","Marilee","Marilin","Marillin","Marilyn","Marin","Marina","Marinna","Marion","Mariquilla","Maris","Marisa","Mariska","Marissa","Marita","Maritsa","Mariya","Marj","Marja","Marje","Marji","Marjie","Marjorie","Marjory","Marjy","Marketa","Marla","Marlane","Marleah","Marlee","Marleen","Marlena","Marlene","Marley","Marlie","Marline","Marlo","Marlyn","Marna","Marne","Marney","Marni","Marnia","Marnie","Marquita","Marrilee","Marris","Marrissa","Marsha","Marsiella","Marta","Martelle","Martguerita","Martha","Marthe","Marthena","Marti","Martica","Martie","Martina","Martita","Marty","Martynne","Mary","Marya","Maryann","Maryanna","Maryanne","Marybelle","Marybeth","Maryellen","Maryjane","Maryjo","Maryl","Marylee","Marylin","Marylinda","Marylou","Marylynne","Maryrose","Marys","Marysa","Masha","Matelda","Mathilda","Mathilde","Matilda","Matilde","Matti","Mattie","Matty","Maud","Maude","Maudie","Maura","Maure","Maureen","Maureene","Maurene","Maurine","Maurise","Maurita","Maurizia","Mavis","Mavra","Max","Maxi","Maxie","Maxine","Maxy","May","Maybelle","Maye","Mead","Meade","Meagan","Meaghan","Meara","Mechelle","Meg","Megan","Megen","Meggi","Meggie","Meggy","Meghan","Meghann","Mehetabel","Mei","Mel","Mela","Melamie","Melania","Melanie","Melantha","Melany","Melba","Melesa","Melessa","Melicent","Melina","Melinda","Melinde","Melisa","Melisande","Melisandra","Melisenda","Melisent","Melissa","Melisse","Melita","Melitta","Mella","Melli","Mellicent","Mellie","Mellisa","Mellisent","Melloney","Melly","Melodee","Melodie","Melody","Melonie","Melony","Melosa","Melva","Mercedes","Merci","Mercie","Mercy","Meredith","Meredithe","Meridel","Meridith","Meriel","Merilee","Merilyn","Meris","Merissa","Merl","Merla","Merle","Merlina","Merline","Merna","Merola","Merralee","Merridie","Merrie","Merrielle","Merrile","Merrilee","Merrili","Merrill","Merrily","Merry","Mersey","Meryl","Meta","Mia","Micaela","Michaela","Michaelina","Michaeline","Michaella","Michal","Michel","Michele","Michelina","Micheline","Michell","Michelle","Micki","Mickie","Micky","Midge","Mignon","Mignonne","Miguela","Miguelita","Mikaela","Mil","Mildred","Mildrid","Milena","Milicent","Milissent","Milka","Milli","Millicent","Millie","Millisent","Milly","Milzie","Mimi","Min","Mina","Minda","Mindy","Minerva","Minetta","Minette","Minna","Minnaminnie","Minne","Minni","Minnie","Minnnie","Minny","Minta","Miquela","Mira","Mirabel","Mirabella","Mirabelle","Miran","Miranda","Mireielle","Mireille","Mirella","Mirelle","Miriam","Mirilla","Mirna","Misha","Missie","Missy","Misti","Misty","Mitzi","Modesta","Modestia","Modestine","Modesty","Moina","Moira","Moll","Mollee","Molli","Mollie","Molly","Mommy","Mona","Monah","Monica","Monika","Monique","Mora","Moreen","Morena","Morgan","Morgana","Morganica","Morganne","Morgen","Moria","Morissa","Morna","Moselle","Moyna","Moyra","Mozelle","Muffin","Mufi","Mufinella","Muire","Mureil","Murial","Muriel","Murielle","Myra","Myrah","Myranda","Myriam","Myrilla","Myrle","Myrlene","Myrna","Myrta","Myrtia","Myrtice","Myrtie","Myrtle","Nada","Nadean","Nadeen","Nadia","Nadine","Nadiya","Nady","Nadya","Nalani","Nan","Nana","Nananne","Nance","Nancee","Nancey","Nanci","Nancie","Nancy","Nanete","Nanette","Nani","Nanice","Nanine","Nannette","Nanni","Nannie","Nanny","Nanon","Naoma","Naomi","Nara","Nari","Nariko","Nat","Nata","Natala","Natalee","Natalie","Natalina","Nataline","Natalya","Natasha","Natassia","Nathalia","Nathalie","Natividad","Natka","Natty","Neala","Neda","Nedda","Nedi","Neely","Neila","Neile","Neilla","Neille","Nelia","Nelie","Nell","Nelle","Nelli","Nellie","Nelly","Nerissa","Nerita","Nert","Nerta","Nerte","Nerti","Nertie","Nerty","Nessa","Nessi","Nessie","Nessy","Nesta","Netta","Netti","Nettie","Nettle","Netty","Nevsa","Neysa","Nichol","Nichole","Nicholle","Nicki","Nickie","Nicky","Nicol","Nicola","Nicole","Nicolea","Nicolette","Nicoli","Nicolina","Nicoline","Nicolle","Nikaniki","Nike","Niki","Nikki","Nikkie","Nikoletta","Nikolia","Nina","Ninetta","Ninette","Ninnetta","Ninnette","Ninon","Nissa","Nisse","Nissie","Nissy","Nita","Nixie","Noami","Noel","Noelani","Noell","Noella","Noelle","Noellyn","Noelyn","Noemi","Nola","Nolana","Nolie","Nollie","Nomi","Nona","Nonah","Noni","Nonie","Nonna","Nonnah","Nora","Norah","Norean","Noreen","Norene","Norina","Norine","Norma","Norri","Norrie","Norry","Novelia","Nydia","Nyssa","Octavia","Odele","Odelia","Odelinda","Odella","Odelle","Odessa","Odetta","Odette","Odilia","Odille","Ofelia","Ofella","Ofilia","Ola","Olenka","Olga","Olia","Olimpia","Olive","Olivette","Olivia","Olivie","Oliy","Ollie","Olly","Olva","Olwen","Olympe","Olympia","Olympie","Ondrea","Oneida","Onida","Oona","Opal","Opalina","Opaline","Ophelia","Ophelie","Ora","Oralee","Oralia","Oralie","Oralla","Oralle","Orel","Orelee","Orelia","Orelie","Orella","Orelle","Oriana","Orly","Orsa","Orsola","Ortensia","Otha","Othelia","Othella","Othilia","Othilie","Ottilie","Page","Paige","Paloma","Pam","Pamela","Pamelina","Pamella","Pammi","Pammie","Pammy","Pandora","Pansie","Pansy","Paola","Paolina","Papagena","Pat","Patience","Patrica","Patrice","Patricia","Patrizia","Patsy","Patti","Pattie","Patty","Paula","Paule","Pauletta","Paulette","Pauli","Paulie","Paulina","Pauline","Paulita","Pauly","Pavia","Pavla","Pearl","Pearla","Pearle","Pearline","Peg","Pegeen","Peggi","Peggie","Peggy","Pen","Penelopa","Penelope","Penni","Pennie","Penny","Pepi","Pepita","Peri","Peria","Perl","Perla","Perle","Perri","Perrine","Perry","Persis","Pet","Peta","Petra","Petrina","Petronella","Petronia","Petronilla","Petronille","Petunia","Phaedra","Phaidra","Phebe","Phedra","Phelia","Phil","Philipa","Philippa","Philippe","Philippine","Philis","Phillida","Phillie","Phillis","Philly","Philomena","Phoebe","Phylis","Phyllida","Phyllis","Phyllys","Phylys","Pia","Pier","Pierette","Pierrette","Pietra","Piper","Pippa","Pippy","Polly","Pollyanna","Pooh","Poppy","Portia","Pris","Prisca","Priscella","Priscilla","Prissie","Pru","Prudence","Prudi","Prudy","Prue","Queenie","Quentin","Querida","Quinn","Quinta","Quintana","Quintilla","Quintina","Rachael","Rachel","Rachele","Rachelle","Rae","Raeann","Raf","Rafa","Rafaela","Rafaelia","Rafaelita","Rahal","Rahel","Raina","Raine","Rakel","Ralina","Ramona","Ramonda","Rana","Randa","Randee","Randene","Randi","Randie","Randy","Ranee","Rani","Rania","Ranice","Ranique","Ranna","Raphaela","Raquel","Raquela","Rasia","Rasla","Raven","Ray","Raychel","Raye","Rayna","Raynell","Rayshell","Rea","Reba","Rebbecca","Rebe","Rebeca","Rebecca","Rebecka","Rebeka","Rebekah","Rebekkah","Ree","Reeba","Reena","Reeta","Reeva","Regan","Reggi","Reggie","Regina","Regine","Reiko","Reina","Reine","Remy","Rena","Renae","Renata","Renate","Rene","Renee","Renell","Renelle","Renie","Rennie","Reta","Retha","Revkah","Rey","Reyna","Rhea","Rheba","Rheta","Rhetta","Rhiamon","Rhianna","Rhianon","Rhoda","Rhodia","Rhodie","Rhody","Rhona","Rhonda","Riane","Riannon","Rianon","Rica","Ricca","Rici","Ricki","Rickie","Ricky","Riki","Rikki","Rina","Risa","Rita","Riva","Rivalee","Rivi","Rivkah","Rivy","Roana","Roanna","Roanne","Robbi","Robbie","Robbin","Robby","Robbyn","Robena","Robenia","Roberta","Robin","Robina","Robinet","Robinett","Robinetta","Robinette","Robinia","Roby","Robyn","Roch","Rochell","Rochella","Rochelle","Rochette","Roda","Rodi","Rodie","Rodina","Rois","Romola","Romona","Romonda","Romy","Rona","Ronalda","Ronda","Ronica","Ronna","Ronni","Ronnica","Ronnie","Ronny","Roobbie","Rora","Rori","Rorie","Rory","Ros","Rosa","Rosabel","Rosabella","Rosabelle","Rosaleen","Rosalia","Rosalie","Rosalind","Rosalinda","Rosalinde","Rosaline","Rosalyn","Rosalynd","Rosamond","Rosamund","Rosana","Rosanna","Rosanne","Rose","Roseann","Roseanna","Roseanne","Roselia","Roselin","Roseline","Rosella","Roselle","Rosemaria","Rosemarie","Rosemary","Rosemonde","Rosene","Rosetta","Rosette","Roshelle","Rosie","Rosina","Rosita","Roslyn","Rosmunda","Rosy","Row","Rowe","Rowena","Roxana","Roxane","Roxanna","Roxanne","Roxi","Roxie","Roxine","Roxy","Roz","Rozalie","Rozalin","Rozamond","Rozanna","Rozanne","Roze","Rozele","Rozella","Rozelle","Rozina","Rubetta","Rubi","Rubia","Rubie","Rubina","Ruby","Ruperta","Ruth","Ruthann","Ruthanne","Ruthe","Ruthi","Ruthie","Ruthy","Ryann","Rycca","Saba","Sabina","Sabine","Sabra","Sabrina","Sacha","Sada","Sadella","Sadie","Sadye","Saidee","Sal","Salaidh","Sallee","Salli","Sallie","Sally","Sallyann","Sallyanne","Saloma","Salome","Salomi","Sam","Samantha","Samara","Samaria","Sammy","Sande","Sandi","Sandie","Sandra","Sandy","Sandye","Sapphira","Sapphire","Sara","Sara-ann","Saraann","Sarah","Sarajane","Saree","Sarena","Sarene","Sarette","Sari","Sarina","Sarine","Sarita","Sascha","Sasha","Sashenka","Saudra","Saundra","Savina","Sayre","Scarlet","Scarlett","Sean","Seana","Seka","Sela","Selena","Selene","Selestina","Selia","Selie","Selina","Selinda","Seline","Sella","Selle","Selma","Sena","Sephira","Serena","Serene","Shae","Shaina","Shaine","Shalna","Shalne","Shana","Shanda","Shandee","Shandeigh","Shandie","Shandra","Shandy","Shane","Shani","Shanie","Shanna","Shannah","Shannen","Shannon","Shanon","Shanta","Shantee","Shara","Sharai","Shari","Sharia","Sharity","Sharl","Sharla","Sharleen","Sharlene","Sharline","Sharon","Sharona","Sharron","Sharyl","Shaun","Shauna","Shawn","Shawna","Shawnee","Shay","Shayla","Shaylah","Shaylyn","Shaylynn","Shayna","Shayne","Shea","Sheba","Sheela","Sheelagh","Sheelah","Sheena","Sheeree","Sheila","Sheila-kathryn","Sheilah","Shel","Shela","Shelagh","Shelba","Shelbi","Shelby","Shelia","Shell","Shelley","Shelli","Shellie","Shelly","Shena","Sher","Sheree","Sheri","Sherie","Sherill","Sherilyn","Sherline","Sherri","Sherrie","Sherry","Sherye","Sheryl","Shina","Shir","Shirl","Shirlee","Shirleen","Shirlene","Shirley","Shirline","Shoshana","Shoshanna","Siana","Sianna","Sib","Sibbie","Sibby","Sibeal","Sibel","Sibella","Sibelle","Sibilla","Sibley","Sibyl","Sibylla","Sibylle","Sidoney","Sidonia","Sidonnie","Sigrid","Sile","Sileas","Silva","Silvana","Silvia","Silvie","Simona","Simone","Simonette","Simonne","Sindee","Siobhan","Sioux","Siouxie","Sisely","Sisile","Sissie","Sissy","Siusan","Sofia","Sofie","Sondra","Sonia","Sonja","Sonni","Sonnie","Sonnnie","Sonny","Sonya","Sophey","Sophi","Sophia","Sophie","Sophronia","Sorcha","Sosanna","Stace","Stacee","Stacey","Staci","Stacia","Stacie","Stacy","Stafani","Star","Starla","Starlene","Starlin","Starr","Stefa","Stefania","Stefanie","Steffane","Steffi","Steffie","Stella","Stepha","Stephana","Stephani","Stephanie","Stephannie","Stephenie","Stephi","Stephie","Stephine","Stesha","Stevana","Stevena","Stoddard","Storm","Stormi","Stormie","Stormy","Sue","Suellen","Sukey","Suki","Sula","Sunny","Sunshine","Susan","Susana","Susanetta","Susann","Susanna","Susannah","Susanne","Susette","Susi","Susie","Susy","Suzann","Suzanna","Suzanne","Suzette","Suzi","Suzie","Suzy","Sybil","Sybila","Sybilla","Sybille","Sybyl","Sydel","Sydelle","Sydney","Sylvia","Tabatha","Tabbatha","Tabbi","Tabbie","Tabbitha","Tabby","Tabina","Tabitha","Taffy","Talia","Tallia","Tallie","Tallou","Tallulah","Tally","Talya","Talyah","Tamar","Tamara","Tamarah","Tamarra","Tamera","Tami","Tamiko","Tamma","Tammara","Tammi","Tammie","Tammy","Tamqrah","Tamra","Tana","Tandi","Tandie","Tandy","Tanhya","Tani","Tania","Tanitansy","Tansy","Tanya","Tara","Tarah","Tarra","Tarrah","Taryn","Tasha","Tasia","Tate","Tatiana","Tatiania","Tatum","Tawnya","Tawsha","Ted","Tedda","Teddi","Teddie","Teddy","Tedi","Tedra","Teena","Teirtza","Teodora","Tera","Teresa","Terese","Teresina","Teresita","Teressa","Teri","Teriann","Terra","Terri","Terrie","Terrijo","Terry","Terrye","Tersina","Terza","Tess","Tessa","Tessi","Tessie","Tessy","Thalia","Thea","Theadora","Theda","Thekla","Thelma","Theo","Theodora","Theodosia","Theresa","Therese","Theresina","Theresita","Theressa","Therine","Thia","Thomasa","Thomasin","Thomasina","Thomasine","Tiena","Tierney","Tiertza","Tiff","Tiffani","Tiffanie","Tiffany","Tiffi","Tiffie","Tiffy","Tilda","Tildi","Tildie","Tildy","Tillie","Tilly","Tim","Timi","Timmi","Timmie","Timmy","Timothea","Tina","Tine","Tiphani","Tiphanie","Tiphany","Tish","Tisha","Tobe","Tobey","Tobi","Toby","Tobye","Toinette","Toma","Tomasina","Tomasine","Tomi","Tommi","Tommie","Tommy","Toni","Tonia","Tonie","Tony","Tonya","Tonye","Tootsie","Torey","Tori","Torie","Torrie","Tory","Tova","Tove","Tracee","Tracey","Traci","Tracie","Tracy","Trenna","Tresa","Trescha","Tressa","Tricia","Trina","Trish","Trisha","Trista","Trix","Trixi","Trixie","Trixy","Truda","Trude","Trudey","Trudi","Trudie","Trudy","Trula","Tuesday","Twila","Twyla","Tybi","Tybie","Tyne","Ula","Ulla","Ulrica","Ulrika","Ulrikaumeko","Ulrike","Umeko","Una","Ursa","Ursala","Ursola","Ursula","Ursulina","Ursuline","Uta","Val","Valaree","Valaria","Vale","Valeda","Valencia","Valene","Valenka","Valentia","Valentina","Valentine","Valera","Valeria","Valerie","Valery","Valerye","Valida","Valina","Valli","Vallie","Vally","Valma","Valry","Van","Vanda","Vanessa","Vania","Vanna","Vanni","Vannie","Vanny","Vanya","Veda","Velma","Velvet","Venita","Venus","Vera","Veradis","Vere","Verena","Verene","Veriee","Verile","Verina","Verine","Verla","Verna","Vernice","Veronica","Veronika","Veronike","Veronique","Vevay","Vi","Vicki","Vickie","Vicky","Victoria","Vida","Viki","Vikki","Vikky","Vilhelmina","Vilma","Vin","Vina","Vinita","Vinni","Vinnie","Vinny","Viola","Violante","Viole","Violet","Violetta","Violette","Virgie","Virgina","Virginia","Virginie","Vita","Vitia","Vitoria","Vittoria","Viv","Viva","Vivi","Vivia","Vivian","Viviana","Vivianna","Vivianne","Vivie","Vivien","Viviene","Vivienne","Viviyan","Vivyan","Vivyanne","Vonni","Vonnie","Vonny","Vyky","Wallie","Wallis","Walliw","Wally","Waly","Wanda","Wandie","Wandis","Waneta","Wanids","Wenda","Wendeline","Wendi","Wendie","Wendy","Wendye","Wenona","Wenonah","Whitney","Wileen","Wilhelmina","Wilhelmine","Wilie","Willa","Willabella","Willamina","Willetta","Willette","Willi","Willie","Willow","Willy","Willyt","Wilma","Wilmette","Wilona","Wilone","Wilow","Windy","Wini","Winifred","Winna","Winnah","Winne","Winni","Winnie","Winnifred","Winny","Winona","Winonah","Wren","Wrennie","Wylma","Wynn","Wynne","Wynnie","Wynny","Xaviera","Xena","Xenia","Xylia","Xylina","Yalonda","Yasmeen","Yasmin","Yelena","Yetta","Yettie","Yetty","Yevette","Ynes","Ynez","Yoko","Yolanda","Yolande","Yolane","Yolanthe","Yoshi","Yoshiko","Yovonnda","Ysabel","Yvette","Yvonne","Zabrina","Zahara","Zandra","Zaneta","Zara","Zarah","Zaria","Zarla","Zea","Zelda","Zelma","Zena","Zenia","Zia","Zilvia","Zita","Zitella","Zoe","Zola","Zonda","Zondra","Zonnya","Zora","Zorah","Zorana","Zorina","Zorine","Zsazsa","Zulema","Zuzana"],Mp={exports:{}};/** * @license diff --git a/examples/react-tldraw/index.html b/examples/react-tldraw/index.html index 4b2eabb95..1c5530667 100644 --- a/examples/react-tldraw/index.html +++ b/examples/react-tldraw/index.html @@ -4,7 +4,7 @@ react-tldraw - + diff --git a/examples/react-todomvc/assets/index-Bxwg4Ujf.js b/examples/react-todomvc/assets/index-BM6P165V.js similarity index 70% rename from examples/react-todomvc/assets/index-Bxwg4Ujf.js rename to examples/react-todomvc/assets/index-BM6P165V.js index be6821496..9d7ba008d 100644 --- a/examples/react-todomvc/assets/index-Bxwg4Ujf.js +++ b/examples/react-todomvc/assets/index-BM6P165V.js @@ -58,7 +58,7 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var lt=null;try{lt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function B(t,e,n){this.low=t|0,this.high=e|0,this.unsigned=!!n}B.prototype.__isLong__;Object.defineProperty(B.prototype,"__isLong__",{value:!0});function De(t){return(t&&t.__isLong__)===!0}function Wf(t){var e=Math.clz32(t&-t);return t?31-e:e}B.isLong=De;var qf={},Hf={};function gr(t,e){var n,r,i;return e?(t>>>=0,(i=0<=t&&t<256)&&(r=Hf[t],r)?r:(n=K(t,0,!0),i&&(Hf[t]=n),n)):(t|=0,(i=-128<=t&&t<128)&&(r=qf[t],r)?r:(n=K(t,t<0?-1:0,!1),i&&(qf[t]=n),n))}B.fromInt=gr;function ut(t,e){if(isNaN(t))return e?nn:Tt;if(e){if(t<0)return nn;if(t>=fp)return gp}else{if(t<=-Yf)return je;if(t+1>=Yf)return hp}return t<0?ut(-t,e).neg():K(t%Qr|0,t/Qr|0,e)}B.fromNumber=ut;function K(t,e,n){return new B(t,e,n)}B.fromBits=K;var Lo=Math.pow;function Gu(t,e,n){if(t.length===0)throw Error("empty string");if(typeof e=="number"?(n=e,e=!1):e=!!e,t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e?nn:Tt;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return Gu(t.substring(1),e,n).neg();for(var i=ut(Lo(n,8)),s=Tt,o=0;o>>0:this.low};x.toNumber=function(){return this.unsigned?(this.high>>>0)*Qr+(this.low>>>0):this.high*Qr+(this.low>>>0)};x.toString=function(e){if(e=e||10,e<2||36>>0,c=u.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};x.getHighBits=function(){return this.high};x.getHighBitsUnsigned=function(){return this.high>>>0};x.getLowBits=function(){return this.low};x.getLowBitsUnsigned=function(){return this.low>>>0};x.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,n=31;n>0&&!(e&1<=0};x.isOdd=function(){return(this.low&1)===1};x.isEven=function(){return(this.low&1)===0};x.equals=function(e){return De(e)||(e=Pt(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};x.eq=x.equals;x.notEquals=function(e){return!this.eq(e)};x.neq=x.notEquals;x.ne=x.notEquals;x.lessThan=function(e){return this.comp(e)<0};x.lt=x.lessThan;x.lessThanOrEqual=function(e){return this.comp(e)<=0};x.lte=x.lessThanOrEqual;x.le=x.lessThanOrEqual;x.greaterThan=function(e){return this.comp(e)>0};x.gt=x.greaterThan;x.greaterThanOrEqual=function(e){return this.comp(e)>=0};x.gte=x.greaterThanOrEqual;x.ge=x.greaterThanOrEqual;x.compare=function(e){if(De(e)||(e=Pt(e)),this.eq(e))return 0;var n=this.isNegative(),r=e.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};x.comp=x.compare;x.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(Dr)};x.neg=x.negate;x.add=function(e){De(e)||(e=Pt(e));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,u=e.low&65535,c=0,f=0,g=0,h=0;return h+=s+u,g+=h>>>16,h&=65535,g+=i+l,f+=g>>>16,g&=65535,f+=r+a,c+=f>>>16,f&=65535,c+=n+o,c&=65535,K(g<<16|h,c<<16|f,this.unsigned)};x.subtract=function(e){return De(e)||(e=Pt(e)),this.add(e.neg())};x.sub=x.subtract;x.multiply=function(e){if(this.isZero())return this;if(De(e)||(e=Pt(e)),lt){var n=lt.mul(this.low,this.high,e.low,e.high);return K(n,lt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?nn:Tt;if(this.eq(je))return e.isOdd()?je:Tt;if(e.eq(je))return this.isOdd()?je:Tt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Qf)&&e.lt(Qf))return ut(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,u=e.low>>>16,c=e.low&65535,f=0,g=0,h=0,v=0;return v+=o*c,h+=v>>>16,v&=65535,h+=s*c,g+=h>>>16,h&=65535,h+=o*u,g+=h>>>16,h&=65535,g+=i*c,f+=g>>>16,g&=65535,g+=s*u,f+=g>>>16,g&=65535,g+=o*l,f+=g>>>16,g&=65535,f+=r*c+i*u+s*l+o*a,f&=65535,K(h<<16|v,f<<16|g,this.unsigned)};x.mul=x.multiply;x.divide=function(e){if(De(e)||(e=Pt(e)),e.isZero())throw Error("division by zero");if(lt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var n=(this.unsigned?lt.div_u:lt.div_s)(this.low,this.high,e.low,e.high);return K(n,lt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?nn:Tt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return nn;if(e.gt(this.shru(1)))return dp;s=nn}else{if(this.eq(je)){if(e.eq(Dr)||e.eq(Jl))return je;if(e.eq(je))return Dr;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Tt)?e.isNegative()?Dr:Jl:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?nn:Tt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Tt}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:Lo(2,a-48),u=ut(r),c=u.mul(e);c.isNegative()||c.gt(i);)r-=l,u=ut(r,this.unsigned),c=u.mul(e);u.isZero()&&(u=Dr),s=s.add(u),i=i.sub(c)}return s};x.div=x.divide;x.modulo=function(e){if(De(e)||(e=Pt(e)),lt){var n=(this.unsigned?lt.rem_u:lt.rem_s)(this.low,this.high,e.low,e.high);return K(n,lt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};x.mod=x.modulo;x.rem=x.modulo;x.not=function(){return K(~this.low,~this.high,this.unsigned)};x.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};x.clz=x.countLeadingZeros;x.countTrailingZeros=function(){return this.low?Wf(this.low):Wf(this.high)+32};x.ctz=x.countTrailingZeros;x.and=function(e){return De(e)||(e=Pt(e)),K(this.low&e.low,this.high&e.high,this.unsigned)};x.or=function(e){return De(e)||(e=Pt(e)),K(this.low|e.low,this.high|e.high,this.unsigned)};x.xor=function(e){return De(e)||(e=Pt(e)),K(this.low^e.low,this.high^e.high,this.unsigned)};x.shiftLeft=function(e){return De(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low<>>32-e,this.unsigned):K(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):K(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};x.shr=x.shiftRight;x.shiftRightUnsigned=function(e){return De(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?K(this.high,0,this.unsigned):K(this.high>>>e-32,0,this.unsigned)};x.shru=x.shiftRightUnsigned;x.shr_u=x.shiftRightUnsigned;x.rotateLeft=function(e){var n;return De(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(n=32-e,K(this.low<>>n,this.high<>>n,this.unsigned)):(e-=32,n=32-e,K(this.high<>>n,this.low<>>n,this.unsigned))};x.rotl=x.rotateLeft;x.rotateRight=function(e){var n;return De(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(n=32-e,K(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,n=32-e,K(this.low<>>e,this.high<>>e,this.unsigned))};x.rotr=x.rotateRight;x.toSigned=function(){return this.unsigned?K(this.low,this.high,!1):this};x.toUnsigned=function(){return this.unsigned?this:K(this.low,this.high,!0)};x.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};x.toBytesLE=function(){var e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};x.toBytesBE=function(){var e=this.high,n=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};B.fromBytes=function(e,n,r){return r?B.fromBytesLE(e,n):B.fromBytesBE(e,n)};B.fromBytesLE=function(e,n){return new B(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)};B.fromBytesBE=function(e,n){return new B(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)};const gw=S.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);S.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:en}]);S.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:pw,repeated:!0}]);const pw=S.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});S.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:mw,repeated:!0}]);const mw=S.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});S.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:yw,repeated:!0}]);const yw=S.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});S.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:vw,repeated:!0}]);const vw=S.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});S.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var w=(t=>(t.Ok="ok",t.ErrClientNotActivated="ErrClientNotActivated",t.ErrClientNotFound="ErrClientNotFound",t.ErrUnimplemented="ErrUnimplemented",t.ErrInvalidType="ErrInvalidType",t.ErrDummy="ErrDummy",t.ErrDocumentNotAttached="ErrDocumentNotAttached",t.ErrDocumentNotDetached="ErrDocumentNotDetached",t.ErrDocumentRemoved="ErrDocumentRemoved",t.ErrInvalidObjectKey="ErrInvalidObjectKey",t.ErrInvalidArgument="ErrInvalidArgument",t.ErrNotInitialized="ErrNotInitialized",t.ErrNotReady="ErrNotReady",t.ErrRefused="ErrRefused",t.ErrContextNotProvided="ErrContextNotProvided",t))(w||{});class T extends Error{constructor(n,r){super(r);m(this,"name","YorkieError");m(this,"stack");this.code=n,this.message=r,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function vt(t){if(t instanceof Map){const e=Array.from(t);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(t))}const pp=t=>t?Object.entries(t).length===0:!0,Xr=t=>{const e={};for(const[n,r]of Object.entries(t))e[n]=JSON.stringify(r);return e},zr=t=>{const e={};for(const[n,r]of Object.entries(t))e[n]=JSON.parse(r);return e};var zn=(t=>(t.Put="put",t.Clear="clear",t))(zn||{});class Va{constructor(e,n){m(this,"context");m(this,"presence");this.context=e,this.presence=n}set(e,n){for(const r of Object.keys(e))this.presence[r]=e[r];this.context.setPresenceChange({type:"put",presence:vt(this.presence)}),this.context.setReversePresence(e,n)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const ia="000000000000000000000000",ww="FFFFFFFFFFFFFFFFFFFFFFFF";class We{constructor(e,n,r){m(this,"lamport");m(this,"delimiter");m(this,"actorID");this.lamport=e,this.delimiter=n,this.actorID=r}static of(e,n,r){return new We(e,n,r)}static fromStruct(e){return We.of(B.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new We(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const n=this.actorID.localeCompare(e.actorID);return n!==0?n:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Yu=0,Sw=4294967295,Tw=B.MAX_VALUE,Et=new We(B.fromNumber(0),Yu,ia);new We(B.fromNumber(1),Yu+1,ia);const _i=new We(Tw,Sw,ww);function Vt(t){return t.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class hs{constructor(e){m(this,"createdAt");m(this,"movedAt");m(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ln extends hs{constructor(e){super(e)}}class Qu{constructor(e,n){m(this,"strKey");m(this,"value");this.strKey=e,this.value=n}static of(e,n){return new Qu(e,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class ns{constructor(){m(this,"nodeMapByKey");m(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new ns}set(e,n,r){let i;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(r)&&(i=s.getValue());const o=Qu.of(e,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),o),(s==null||r.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),n.setMovedAt(r)),i}delete(e,n){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(w.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(n),r.getValue()}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return n.getStrKey()}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(e,n){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(n))return r.getValue()}has(e){const n=this.nodeMapByKey.get(e);return n==null?!1:!n.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const n=this.nodeMapByKey.get(e);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class qe extends Ln{constructor(n,r){super(n);m(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new qe(n,ns.create());const i=ns.create();for(const[s,o]of Object.entries(r))i.set(s,o.deepcopy(),o.getCreatedAt());return new qe(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${Vt(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:s,value:o,type:a}=i.toJSForTest();n[r]={key:r,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[s]of this)n.push(s);const r=[];for(const s of n.sort()){const o=(i=this.memberNodes.get(s))==null?void 0:i.getValue();r.push(`"${Vt(s)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=qe.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var G=(t=>(t.Local="local",t.Remote="remote",t.UndoRedo="undoredo",t))(G||{});class Ct{constructor(e,n){m(this,"parentCreatedAt");m(this,"executedAt");this.parentCreatedAt=e,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(w.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class mp{constructor(e){m(this,"value");m(this,"left");m(this,"right");m(this,"parent");m(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class rs{constructor(e){m(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&e<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new T(w.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${n.getLength()}`);return[n,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let n=0,r=e,i;for(;r;)(!i||i===r.getRight())&&(n+=r.getLength()+(r.hasLeft()?r.getLeftWeight():0)),i=r,r=r.getParent();return n-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,n){return e?(this.splayNode(e),this.root=n,n.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(n),n.setLeft(e),e.setParent(n),e.setRight(),this.updateWeight(e),this.updateWeight(n),n):(this.root=n,n)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const n=new rs(e.getLeft());n.root&&n.root.setParent();const r=new rs(e.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,n){if(!n){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(n),n.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const n=[];this.traversePostorder(e.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const n of e)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,n){e&&(this.traverseInorder(e.getLeft(),n),n.push(e),this.traverseInorder(e.getRight(),n))}traversePostorder(e,n){e&&(this.traversePostorder(e.getLeft(),n),this.traversePostorder(e.getRight(),n),n.push(e))}rotateLeft(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setRight(e.getLeft()),n.hasRight()&&n.getRight().setParent(n),e.setLeft(n),e.getLeft().setParent(e),this.updateWeight(n),this.updateWeight(e)}rotateRight(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setLeft(e.getRight()),n.hasLeft()&&n.getLeft().setParent(n),e.setRight(n),e.getRight().setParent(e),this.updateWeight(n),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var me=(t=>(t[t.Null=0]="Null",t[t.Boolean=1]="Boolean",t[t.Integer=2]="Integer",t[t.Long=3]="Long",t[t.Double=4]="Double",t[t.String=5]="String",t[t.Bytes=6]="Bytes",t[t.Date=7]="Date",t))(me||{});class ne extends hs{constructor(n,r){super(r);m(this,"valueType");m(this,"value");this.valueType=ne.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new ne(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return B.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(B.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Vt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=ne.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof B)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return ne.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=B.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Mo extends mp{constructor(n){super(n);m(this,"prev");m(this,"next");this.value=n}static createAfter(n,r){const i=new Mo(r),s=n.next;return n.next=i,i.prev=n,i.next=s,s&&(s.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class is{constructor(){m(this,"dummyHead");m(this,"last");m(this,"nodeMapByIndex");m(this,"nodeMapByCreatedAt");const e=ne.of(0,Et);e.setRemovedAt(Et),this.dummyHead=new Mo(e),this.last=this.dummyHead,this.nodeMapByIndex=new rs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new is}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,n){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=Mo.createAfter(i,n);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,n,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(n.toIDString());if(!s)throw new T(w.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(e){if(e>=this.length)return;const[n,r]=this.nodeMapByIndex.find(e);let i=n;if(e===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let n=this.nodeMapByCreatedAt.get(e.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(e,n){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,n){const r=this.getByIndex(e);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class et extends Ln{constructor(n,r){super(n);m(this,"elements");this.elements=r}static create(n,r){if(!r)return new et(n,is.create());const i=is.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new et(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...h,value:h.value?{attributes:zr(h.value.getAttributes()),content:h.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,g,c,[l,l]]}setStyle(n,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),l=[],u=this.rgaTreeSplit.findBetween(a,o),c=new Map,f=[];for(const h of u){const v=h.getCreatedAt().getActorID(),A=s!=null&&s.size?s.has(v)?s.get(v):Et:_i;if(h.canStyle(i,A)){const O=c.get(v),p=h.getCreatedAt();(!O||p.after(O))&&c.set(v,p),f.push(h)}}const g=[];for(const h of f){if(h.isRemoved())continue;const[v,A]=this.rgaTreeSplit.findIndexesFromRange(h.createPosRange());l.push({type:"style",actor:i.getActorID(),from:v,to:A,value:{attributes:zr(r)}});for(const[O,p]of Object.entries(r)){const[d]=h.getValue().setAttr(O,p,i);d!==void 0&&g.push({parent:h.getValue(),child:d})}}return[c,g,l]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:zr(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new ht(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class ps extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"content");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(n,r,i,s,o,a,l){return new ps(n,r,i,s,o,a,l)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ht))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u})=>({type:"edit",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${n}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ms extends Ct{constructor(n,r,i,s,o,a){super(n,a);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(n,r,i,s,o,a){return new ms(n,r,i,s,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ht))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)n.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:u})=>({type:"style",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const kw=2,Iw="root",sn="text";function mi(t,e){let n=0;const r=t.children;for(let i=0;i0)throw new T(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const n=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*n,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===sn}get paddedSize(){return this.size+(this.isText?0:kw)}isAncestorOf(e){return Ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e+1];if(n)return n}get prevSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e-1];if(n)return n}splitText(e,n){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+n);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const n of e)n.parent=this,n.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const n of e)n.parent=this}insertBefore(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,n),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new T(w.ErrInvalidArgument,"child not found");this._children.splice(n,1),e.parent=void 0}splitElement(e,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.splice(n,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const n=this._children.indexOf(e);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");let n=e;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function Ew(t,e){if(t===e)return!1;for(;e.parent;){if(e.parent===t)return!0;e=e.parent}return!1}var fe=(t=>(t.Start="Start",t.End="End",t.Text="Text",t))(fe||{});function yp(t,e,n,r){if(e>n)throw new T(w.ErrInvalidArgument,`from is greater than to: ${e} > ${n}`);if(e>t.size)throw new T(w.ErrInvalidArgument,`from is out of range: ${e} > ${t.size}`);if(n>t.size)throw new T(w.ErrInvalidArgument,`to is out of range: ${n} > ${t.size}`);if(e===n)return;let i=0;for(const s of t.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],u),yp(s,Math.max(0,o),Math.min(a,s.size),r),u&&r([s,"End"],u)}i+=s.paddedSize}}function vp(t,e,n=0){for(const r of t.children)vp(r,e,n+1);e(t,n)}function sa(t,e,n=0){for(const r of t._children)sa(r,e,n+1);e(t,n)}function Kl(t,e,n=!0){if(e>t.size)throw new T(w.ErrInvalidArgument,`index is out of range: ${e} > ${t.size}`);if(t.isText)return{node:t,offset:e};let r=0,i=0;for(const s of t.children){if(n&&s.isText&&s.size>=e-i)return Kl(s,e-i,n);if(e===i)return{node:t,offset:r};if(!n&&s.paddedSize===e-i)return{node:t,offset:r+1};if(s.paddedSize>e-i)return Kl(s,e-i-1,n);i+=s.paddedSize,r+=1}return{node:t,offset:r}}function wp(t){return t.isText||t.children.length===0?t:wp(t.children[0])}function Nw(t,e){if(t.sizet===e?0:t0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,s=n;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,n){for(;n;){const r=this.comparator(e,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(e,n,r){if(!r)return this.counter+=1,new Pw(e,n,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,n,r.left):i>0?r.right=this.putInternal(e,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,n){if(this.comparator(n,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,n);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(n,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(n,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,n)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const n=e.right;return e.right=n.left,n.left=e,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(e){const n=e.left;return e.left=n.right,n.right=e,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class kt{constructor(e,n){m(this,"parentID");m(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=n}static of(e,n){return new kt(e,n)}static fromTreePos(e){const{offset:n}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],kt.of(r.id,Ae.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(e){return kt.of(Ae.of(We.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(We.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const n=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(n);let s=e.findFloorNode(r);if(!i||!s)throw new T(w.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ae{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Ae(e,n)}static fromStruct(e){return Ae.of(We.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=n,s}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new T(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new T(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Xe(Ae.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Xe(Ae.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=n.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,n.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new fn);const i=new Array;for(const[s,o]of Object.entries(n))i.push(this.attrs.set(s,o,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function Wl(t){var n;if(t.isText){const r=t;return{type:r.type,value:r.value}}const e={type:t.type,children:t.children.map(Wl)};return t.attrs&&(e.attributes=zr((n=t.attrs)==null?void 0:n.toObject())),e}function Xu(t){if(t.isText)return t.value;let e="";return t.attrs&&t.attrs.size()&&(e=" "+Array.from(t.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Vt(n.getValue())}"`}).join(" ")),`<${t.type}${e}>${t.children.map(n=>Xu(n)).join("")}`}function Tp(t){if(t.isText){const e=t;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:t.type,children:t.children.map(Tp),size:t.size,isRemoved:t.isRemoved}}class gt extends hs{constructor(n,r){super(r);m(this,"indexTree");m(this,"nodeMapByID");this.indexTree=new xw(n),this.nodeMapByID=new Sp(Ae.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new gt(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,s]=n.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,n.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const u=l.allChildren,c=a?0:u.indexOf(o)+1;for(let f=c;f{const A=v.getCreatedAt().getActorID(),O=s?s.has(A)?s.get(A):Et:_i;if(v.canStyle(i,O)&&r){const p=g.get(A),d=v.getCreatedAt();(!p||d.after(p))&&g.set(A,d);const y=v.setAttrs(r,i),k=y.reduce((P,[,_])=>(_&&(P[_.getKey()]=f[_.getKey()]),P),{}),N=v.parent,C=v.prevSibling||v.parent;Object.keys(k).length>0&&c.push({type:"style",from:this.toIndex(N,C),to:this.toIndex(v,v),fromPath:this.toPath(N,C),toPath:this.toPath(v,v),actor:i.getActorID(),value:k});for(const[P]of y)P&&h.push({parent:v,child:P})}}),[g,h,c]}removeStyle(n,r,i,s){const[o,a]=this.findNodesAndSplitText(n[0],i),[l,u]=this.findNodesAndSplitText(n[1],i),c=[],f=new Map,g=[];return this.traverseInPosRange(o,a,l,u,([h])=>{const v=h.getCreatedAt().getActorID(),A=s?s.has(v)?s.get(v):Et:_i;if(h.canStyle(i,A)&&r){const O=f.get(v),p=h.getCreatedAt();(!O||p.after(O))&&f.set(v,p),h.attrs||(h.attrs=new fn);for(const k of r){const N=h.attrs.remove(k,i);for(const C of N)g.push({parent:h,child:C})}const d=h.parent,y=h.prevSibling||h.parent;c.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(d,y),to:this.toIndex(h,h),fromPath:this.toPath(d,y),toPath:this.toPath(h,h),value:r})}}),[f,g,c]}edit(n,r,i,s,o,a){const[l,u]=this.findNodesAndSplitText(n[0],s),[c,f]=this.findNodesAndSplitText(n[1],s),g=this.toIndex(l,u),h=this.toPath(l,u),v=[],A=[],O=[],p=new Map;this.traverseInPosRange(l,u,c,f,([k,N],C)=>{if(N===fe.Start&&!C)for(const W of k.children)O.push(W);const P=k.getCreatedAt().getActorID(),_=a?a.has(P)?a.get(P):Et:_i;if(k.canDelete(s,_)||v.includes(k.parent)){const W=p.get(P),U=k.getCreatedAt();(!W||U.after(W))&&p.set(P,U),(N===fe.Text||N===fe.Start)&&v.push(k),A.push([k,N])}});const d=this.makeDeletionChanges(A,s),y=[];for(const k of v)k.remove(s),k.isRemoved&&y.push({parent:this,child:k});for(const k of O)k.removedAt||l.append(k);if(i>0){let k=0,N=l,C=u;for(;k{l.isRemoved&&(P.remove(s),y.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),C.isRemoved||k.push(C);if(k.length){const C=k.map(P=>Wl(P));d.length&&d[d.length-1].from===g?d[d.length-1].value=C:d.push({type:"content",from:g,to:g,fromPath:h,toPath:h,actor:s.getActorID(),value:C})}}return[d,y,p]}editT(n,r,i,s,o){const a=this.findPos(n[0]),l=this.findPos(n[1]);this.edit([a,l],r,i,s,o)}move(n,r,i){throw new T(w.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var s;(s=n.parent)==null||s.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return kt.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Xu(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var h,v,A,O;let l,u,c;const f=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;f&&(l=this.indexTree.indexOf(f),u=this.indexTree.treePosToPath(f),c=kt.fromTreePos(f).toStruct());const g={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(h=i.removedAt)==null?void 0:h.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(A=i.insNextID)==null?void 0:A.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?zr((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:u,pos:c};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=d,i[i.length-1].toPath=this.toPath(O,h)):i.push({type:"content",from:p,to:d,fromPath:this.toPath(A,f),toPath:this.toPath(O,h),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===fe.Start){const l=n.allChildren;return l.length>0?[l[0],l[0].isText?fe.Text:fe.Start]:[n,fe.End]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===s.length-1)return[i,fe.End];const a=s[o+1];return[a,a.isText?fe.Text:fe.Start]}findLeftToken([n,r]){if(r===fe.End){const l=n.allChildren;if(l.length>0){const u=l[l.length-1];return[u,u.isText?fe.Text:fe.End]}return[n,fe.Start]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===0)return[i,fe.Start];const a=s[o-1];return[a,a.isText?fe.Text:fe.End]}}class ys extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"contents");m(this,"splitLevel");m(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(n,r,i,s,o,a,l){return new ys(n,r,i,s,o,a,l)}execute(n){var l;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(u=>u.deepcopy()),this.splitLevel,i,(()=>{let u=i.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>We.of(i.getLamport(),++u,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)n.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${n}.EDIT(${r},${i},${s.map(o=>Xu(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class kn{constructor(e,n,r,i){m(this,"clientSeq");m(this,"serverSeq");m(this,"lamport");m(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=n,this.actor=r}static of(e,n,r,i){return new kn(e,n,r,i)}next(){return new kn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new kn(this.clientSeq,e,this.actor):new kn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return We.of(this.lamport,e,this.actor)}setActor(e){return new kn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Dw=new kn(0,B.fromInt(0,!0),ia);class Zr{constructor({id:e,operations:n,presenceChange:r,message:i}){m(this,"id");m(this,"operations");m(this,"presenceChange");m(this,"message");this.id=e,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:e,operations:n,presenceChange:r,message:i}){return new Zr({id:e,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const n of this.operations)n.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,n,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:u}=a;i.push(...l),u&&s.unshift(u)}return this.presenceChange&&(this.presenceChange.type===zn.Put?n.set(this.id.getActorID(),vt(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ye.bytesToHex(ye.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ye.bytesToHex(ye.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:n,operations:r,presenceChange:i,message:s}=e;return Zr.create({id:ye.bytesToChangeID(ye.hexToBytes(n)),operations:r==null?void 0:r.map(o=>ye.bytesToOperation(ye.hexToBytes(o))),presenceChange:i,message:s})}}class oa{constructor(e,n,r,i,s,o){m(this,"documentKey");m(this,"checkpoint");m(this,"isRemoved");m(this,"changes");m(this,"snapshot");m(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,n,r,i,s,o){return new oa(e,n,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Ur{constructor(e,n){m(this,"serverSeq");m(this,"clientSeq");this.serverSeq=e,this.clientSeq=n}static of(e,n){return new Ur(e,n)}increaseClientSeq(e){return e===0?this:new Ur(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const n=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return Ur.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Rw=new Ur(B.fromInt(0,!0),0);class Wt{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Wt(e,n)}static fromStruct(e){return Wt.of(We.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Wt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _w=Wt.of(Et,0);class Nt{constructor(e,n){m(this,"id");m(this,"relativeOffset");this.id=e,this.relativeOffset=n}static of(e,n){return new Nt(e,n)}static fromStruct(e){const n=Wt.fromStruct(e.id);return Nt.of(n,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Wt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Mn extends mp{constructor(n,r,i){super(r);m(this,"id");m(this,"removedAt");m(this,"prev");m(this,"next");m(this,"insPrev");m(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new Mn(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==e.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(e){const n=this.treeByID.floorEntry(e);if(n&&!(!n.key.equals(e)&&!n.key.hasSameCreatedAt(e)))return n.value}findBetween(e,n){const r=[];let i=e;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(e,n){if(n>e.getContentLength())throw new T(w.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return e;if(n===e.getContentLength())return e.getNext();const r=e.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,n,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,n,r),o=new Map,a=new Map,l=this.makeChanges(s,n);for(const u of i){const c=u.getCreatedAt().getActorID();(!o.has(c)||u.getID().getCreatedAt().after(o.get(c)))&&o.set(c,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(n)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,n,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const c=u.getCreatedAt().getActorID(),f=i?r.has(c)?r.get(c):Et:_i;u.canDelete(n,f)?s.push(u):o.push(u)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,n){const r=[];let i,s;for(let o=0;ot<0?Math.ceil(t):Math.floor(t);var qt=(t=>(t[t.IntegerCnt=0]="IntegerCnt",t[t.LongCnt=1]="LongCnt",t))(qt||{});class tt extends hs{constructor(n,r,i){super(i);m(this,"valueType");m(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=B.fromNumber(r).toInt():this.value=Xf(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=B.fromNumber(r):this.value=r;break;default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new tt(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return B.fromBytesLE(Array.from(r));default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=tt.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof B?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!tt.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===me.Long?this.value=this.value+n.getValue().toInt():this.value=B.fromNumber(this.value+Xf(n.getValue())).toInt(),this}}class ti extends Ct{constructor(n,r,i){super(n,i);m(this,"value");this.value=r}static create(n,r,i){return new ti(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof tt))throw new T(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===me.Long?n.getValue().multiply(-1):n.getValue()*-1;return ti.create(this.getParentCreatedAt(),ne.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class on extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");m(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(n,r,i,s,o,a){return new on(n,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(n,r,i,s,o,a){return new on(n,r,i,s,new Map,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,u])=>a[l]=u),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u,fromPath:c,toPath:f})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:c,toPath:f,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function bw(t){const e=new Hu,n=e.data;for(const[r,i]of Object.entries(t))n[r]=JSON.stringify(i);return e}function Lw(t){if(t.type===zn.Put)return new Vl({type:ts.PUT,presence:bw(t.presence)});if(t.type===zn.Clear)return new Vl({type:ts.CLEAR});throw new T(w.ErrUnimplemented,"unimplemented type")}function Mw(t){return new cp({serverSeq:t.getServerSeqAsString(),clientSeq:t.getClientSeq()})}function kp(t){return new na({clientSeq:t.getClientSeq(),lamport:t.getLamportAsString(),actorId:sc(t.getActorID())})}function b(t){if(t)return new M({lamport:t.getLamportAsString(),delimiter:t.getDelimiter(),actorId:sc(t.getActorID())})}function Ip(t){switch(t){case me.Null:return z.NULL;case me.Boolean:return z.BOOLEAN;case me.Integer:return z.INTEGER;case me.Long:return z.LONG;case me.Double:return z.DOUBLE;case me.String:return z.STRING;case me.Bytes:return z.BYTES;case me.Date:return z.DATE;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ap(t){switch(t){case qt.IntegerCnt:return z.INTEGER_CNT;case qt.LongCnt:return z.LONG_CNT;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ja(t){if(t instanceof qe)return new Yt({type:z.JSON_OBJECT,createdAt:b(t.getCreatedAt()),value:Fp(t)});if(t instanceof et)return new Yt({type:z.JSON_ARRAY,createdAt:b(t.getCreatedAt()),value:f1(t)});if(t instanceof ht)return new Yt({type:z.TEXT,createdAt:b(t.getCreatedAt())});if(t instanceof ne)return new Yt({type:Ip(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof tt)return new Yt({type:Ap(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof gt)return new Yt({type:z.TREE,createdAt:b(t.getCreatedAt()),value:h1(t)});throw new T(w.ErrUnimplemented,"unimplemented element")}function Fw(t){return new jl({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function Bs(t){return new cr({createdAt:b(t.getID().getCreatedAt()),offset:t.getID().getOffset(),relativeOffset:t.getRelativeOffset()})}function $s(t){return new es({parentId:bi(t.getParentID()),leftSiblingId:bi(t.getLeftSiblingID())})}function bi(t){return new $r({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function Ep(t){const e=new Ku;if(t instanceof fr){const n=t,r=new Wg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.key=n.getKey(),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="set",e.body.value=r}else if(t instanceof gs){const n=t,r=new qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="add",e.body.value=r}else if(t instanceof En){const n=t,r=new Hg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="move",e.body.value=r}else if(t instanceof Un){const n=t,r=new Gg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(t instanceof ps){const n=t,r=new Yg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=Bs(n.getFromPos()),r.to=Bs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);r.content=n.getContent();const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(t instanceof ms){const n=t,r=new Qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=Bs(n.getFromPos()),r.to=Bs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="style",e.body.value=r}else if(t instanceof ti){const n=t,r=new Xg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(t instanceof ys){const n=t,r=new Zg,i=r.createdAtMapByActor;for(const[s,o]of n.getMaxCreatedAtMapByActor())i[s]=b(o);r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos()),r.contents=Jw(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=b(n.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(t instanceof on){const n=t,r=new ep;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=n.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of n.getAttributes())o[a]=l}r.executedAt=b(n.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(w.ErrUnimplemented,"unimplemented operation");return e}function Bw(t){const e=[];for(const n of t)e.push(Ep(n));return e}function $w(t){const e=new Kg({id:kp(t.getID()),message:t.getMessage()});return t.hasOperations()&&(e.operations=Bw(t.getOperations())),t.hasPresenceChange()&&(e.presenceChange=Lw(t.getPresenceChange())),e}function zw(t){const e=[];for(const n of t)e.push($w(n));return e}function Uw(t){const e=[];for(const n of t)e.push(new ap({key:n.getStrKey(),element:ec(n.getValue())}));return e}function jw(t){const e=[];for(const n of t)e.push(new Wu({element:ec(n.getValue())}));return e}function Vw(t){const e=[];for(const n of t){const r=new lp;r.id=Fw(n.getID()),r.value=n.getValue().getContent(),r.removedAt=b(n.getRemovedAt());const i=r.attributes,s=n.getValue().getAttrs();for(const o of s){const a=new ra;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function Jw(t){const e=[];if(!t||!t.length)return e;for(const n of t)e.push(new up({content:Zu(n)}));return e}function Kw(t){const e={};for(const n of t)e[n.getKey()]=new ra({value:n.getValue(),updatedAt:b(n.getUpdatedAt()),isRemoved:n.isRemoved()});return e}function Zu(t){if(!t)return[];const e=[];return sa(t,(n,r)=>{const i=new qu({id:bi(n.id),type:n.type,removedAt:b(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=bi(n.insPrevID)),n.insNextID&&(i.insNextId=bi(n.insNextID)),n.attrs&&(i.attributes=Kw(n.attrs)),e.push(i)}),e}function Ww(t){const e=new pt;return e.body.case="jsonObject",e.body.value=new tp({nodes:Uw(t.getRHT()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Np(t){const e=new pt;return e.body.case="jsonArray",e.body.value=new np({nodes:jw(t.getElements()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function qw(t){const e=new pt;return e.body.case="primitive",e.body.value=new rp({type:Ip(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Hw(t){const e=new pt;return e.body.case="text",e.body.value=new ip({nodes:Vw(t.getRGATreeSplit()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Gw(t){const e=new pt;return e.body.case="counter",e.body.value=new sp({type:Ap(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function xp(t){const e=new pt;return e.body.case="tree",e.body.value=new op({nodes:Zu(t.getRoot()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function ec(t){if(t instanceof qe)return Ww(t);if(t instanceof et)return Np(t);if(t instanceof ne)return qw(t);if(t instanceof ht)return Hw(t);if(t instanceof tt)return Gw(t);if(t instanceof gt)return xp(t);throw new T(w.ErrUnimplemented,"unimplemented element")}function Yw(t){return new hn({documentKey:t.getDocumentKey(),checkpoint:Mw(t.getCheckpoint()),isRemoved:t.getIsRemoved(),changes:zw(t.getChanges()),snapshot:t.getSnapshot(),minSyncedTicket:b(t.getMinSyncedTicket())})}function Zf(t){const e=t.findDetails(gw);for(const n of e)if(n.metadata.code)return n.metadata.code;return""}function Cp(t){let e;return t.serverSeq&&(e=B.fromString(t.serverSeq,!0)),kn.of(t.clientSeq,B.fromString(t.lamport,!0),ic(t.actorId),e)}function L(t){if(t)return We.of(B.fromString(t.lamport,!0),t.delimiter,ic(t.actorId))}function tc(t){const e={};return Object.entries(t.data).forEach(([n,r])=>{e[n]=JSON.parse(r)}),e}function Qw(t){const e=t.type;if(e===ts.PUT){const n=tc(t.presence);return{type:zn.Put,presence:n}}if(e===ts.CLEAR)return{type:zn.Clear};throw new T(w.ErrInvalidType,`unsupported type: ${e}`)}function Xw(t){const e=new Map;return Object.entries(t).forEach(([n,r])=>{e.set(n,tc(r))}),e}function Pp(t){switch(t){case z.NULL:return me.Null;case z.BOOLEAN:return me.Boolean;case z.INTEGER:return me.Integer;case z.LONG:return me.Long;case z.DOUBLE:return me.Double;case z.STRING:return me.String;case z.BYTES:return me.Bytes;case z.DATE:return me.Date}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Fo(t){switch(t){case z.INTEGER_CNT:return qt.IntegerCnt;case z.LONG_CNT:return qt.LongCnt}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Ka(t){switch(t.type){case z.JSON_OBJECT:return t.value?Mp(t.value):qe.create(L(t.createdAt));case z.JSON_ARRAY:return t.value?c1(t.value):et.create(L(t.createdAt));case z.TEXT:return ht.create(ei.create(),L(t.createdAt));case z.TREE:return d1(t.value);case z.NULL:case z.BOOLEAN:case z.INTEGER:case z.LONG:case z.DOUBLE:case z.STRING:case z.BYTES:case z.DATE:return ne.of(ne.valueFromBytes(Pp(t.type),t.value),L(t.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return tt.create(Fo(t.type),tt.valueFromBytes(Fo(t.type),t.value),L(t.createdAt))}}function zs(t){return Nt.of(Wt.of(L(t.createdAt),t.offset),t.relativeOffset)}function Op(t){return Wt.of(L(t.createdAt),t.offset)}function Zw(t){const e=ss.create(t.value);Object.entries(t.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,L(i.updatedAt))});const n=Mn.create(Op(t.id),e);return n.remove(L(t.removedAt)),n}function yr(t){return kt.of(Li(t.parentId),Li(t.leftSiblingId))}function Li(t){return Ae.of(L(t.createdAt),t.offset)}function e1(t){if(!t.length)return;const e=[];return t.forEach(n=>{const r=nc(n.content);e.push(r)}),e}function nc(t){if(t.length===0)return;const e=[];for(const i of t)e.push(n1(i));const n=e[e.length-1],r=new Map;r.set(t[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(t[i].depth-1).prepend(e[i]),r.set(t[i].depth,e[i]);return n.updateDescendantsSize(),gt.create(n,Et).getRoot()}function t1(t){const e=fn.create();for(const[n,r]of Object.entries(t))e.setInternal(n,r.value,L(r.updatedAt),r.isRemoved);return e}function n1(t){const e=Li(t.id),n=Xe.create(e,t.type),r=Object.entries(t.attributes);return n.isText?n.value=t.value:r.length&&(n.attrs=t1(t.attributes)),t.insPrevId&&(n.insPrevID=Li(t.insPrevId)),t.insNextId&&(n.insNextID=Li(t.insNextId)),n.removedAt=L(t.removedAt),n}function Dp(t){if(t.body.case==="set"){const e=t.body.value;return fr.create(e.key,Ka(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(t.body.case==="add"){const e=t.body.value;return gs.create(L(e.parentCreatedAt),L(e.prevCreatedAt),Ka(e.value),L(e.executedAt))}else if(t.body.case==="move"){const e=t.body.value;return En.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="remove"){const e=t.body.value;return Un.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="edit"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ps.create(L(e.parentCreatedAt),zs(e.from),zs(e.to),n,e.content,r,L(e.executedAt))}else if(t.body.case==="style"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ms.create(L(e.parentCreatedAt),zs(e.from),zs(e.to),n,r,L(e.executedAt))}else{if(t.body.case==="select")return;if(t.body.case==="increase"){const e=t.body.value;return ti.create(L(e.parentCreatedAt),Ka(e.value),L(e.executedAt))}else if(t.body.case==="treeEdit"){const e=t.body.value,n=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{n.set(r,L(i))}),ys.create(L(e.parentCreatedAt),yr(e.from),yr(e.to),e1(e.contents),e.splitLevel,n,L(e.executedAt))}else if(t.body.case==="treeStyle"){const e=t.body.value,n=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,L(o))}),(r==null?void 0:r.length)>0?on.createTreeRemoveStyleOperation(L(e.parentCreatedAt),yr(e.from),yr(e.to),i,r,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{n.set(s,o)}),on.create(L(e.parentCreatedAt),yr(e.from),yr(e.to),i,n,L(e.executedAt)))}else throw new T(w.ErrUnimplemented,"unimplemented operation")}}function r1(t){const e=[];for(const n of t){const r=Dp(n);r&&e.push(r)}return e}function Rp(t){const e=[];for(const n of t)e.push(Zr.create({id:Cp(n.id),operations:r1(n.operations),presenceChange:n.presenceChange?Qw(n.presenceChange):void 0,message:n.message}));return e}function i1(t){return Ur.of(B.fromString(t.serverSeq,!0),t.clientSeq)}function s1(t){return oa.create(t.documentKey,i1(t.checkpoint),t.isRemoved,Rp(t.changes),t.snapshot,L(t.minSyncedTicket))}function _p(t){const e=new ns;for(const r of t.nodes){const i=rc(r.element);e.set(r.key,i,i.getPositionedAt())}const n=new qe(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function bp(t){const e=new is;for(const r of t.nodes)e.insert(rc(r.element));const n=new et(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function o1(t){const e=ne.of(ne.valueFromBytes(Pp(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function a1(t){const e=new ei;let n=e.getHead();for(const i of t.nodes){const s=e.insertAfter(n,Zw(i));i.insPrevId&&s.setInsPrev(e.findNode(Op(i.insPrevId))),n=s}const r=new ht(e,L(t.createdAt));return r.setMovedAt(L(t.movedAt)),r.setRemovedAt(L(t.removedAt)),r}function l1(t){const e=tt.create(Fo(t.type),tt.valueFromBytes(Fo(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function Lp(t){const e=nc(t.nodes);return gt.create(e,L(t.createdAt))}function rc(t){if(t.body.case==="jsonObject")return _p(t.body.value);if(t.body.case==="jsonArray")return bp(t.body.value);if(t.body.case==="primitive")return o1(t.body.value);if(t.body.case==="text")return a1(t.body.value);if(t.body.case==="counter")return l1(t.body.value);if(t.body.case==="tree")return Lp(t.body.value);throw new T(w.ErrUnimplemented,"unimplemented element")}function u1(t){if(!t)return{root:qe.create(Et),presences:new Map};const e=J0.fromBinary(t);return{root:rc(e.root),presences:Xw(e.presences)}}function Mp(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return _p(e.body.value)}function Fp(t){return ec(t).toBinary()}function c1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return bp(e.body.value)}function f1(t){return Np(t).toBinary()}function d1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return Lp(e.body.value)}function h1(t){return xp(t).toBinary()}function Bp(t){return t?Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ic(t){return Bp(t)}function $p(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function sc(t){return $p(t)}function g1(t){const e=na.fromBinary(t);return Cp(e)}function p1(t){const e=Ku.fromBinary(t);return Dp(e)}const ye={fromPresence:tc,toChangePack:Yw,fromChangePack:s1,fromChanges:Rp,toTreeNodes:Zu,fromTreeNodes:nc,objectToBytes:Fp,bytesToObject:Mp,bytesToSnapshot:u1,bytesToHex:Bp,hexToBytes:$p,toHexString:ic,toUint8Array:sc,toOperation:Ep,toChangeID:kp,PbChangeID:na,bytesToChangeID:g1,bytesToOperation:p1};var be=(t=>(t[t.Trivial=0]="Trivial",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.Fatal=5]="Fatal",t))(be||{});let Gn=3;function zp(t){Gn=t}const F={trivial:(...t)=>{Gn>0||typeof console<"u"&&console.log("YORKIE T:",...t)},debug:(...t)=>{Gn>1||typeof console<"u"&&console.log("YORKIE D:",...t)},info:(...t)=>{Gn>2||typeof console<"u"&&console.log("YORKIE I:",...t)},warn:(...t)=>{Gn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:(...t)=>{Gn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:(...t)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...t):console.log("YORKIE F:",...t))},isEnabled:t=>Gn<=t};function Up(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class m1{constructor(e,n,r,i,s){m(this,"reconnectStreamDelay");m(this,"doc");m(this,"docID");m(this,"syncMode");m(this,"remoteChangeEventReceived");m(this,"watchStream");m(this,"watchLoopTimerID");m(this,"watchAbortController");m(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===ao.RealtimeSyncOff?!1:this.syncMode===ao.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==ao.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Wa=()=>{};class y1{constructor(e){m(this,"finalized",!1);m(this,"observers",[]);m(this,"finalError");try{e(this)}catch(n){this.error(n)}}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(!e)throw new T(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=Wa),i.error===void 0&&(i.error=Wa),i.complete===void 0&&(i.complete=Wa);const s=Up(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){F.warn(a)}return o}unsubscribeOne(e){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let n=0;ne}}class Rr{constructor(e,n,r,i){m(this,"id");m(this,"delimiter");m(this,"message");m(this,"root");m(this,"operations");m(this,"presenceChange");m(this,"previousPresence");m(this,"reversePresenceKeys");this.id=e,this.delimiter=Yu,this.root=n,this.operations=[],this.previousPresence=vt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,n,r,i){return new Rr(e,n,r,i)}push(e){this.operations.push(e)}registerElement(e,n){this.root.registerElement(e,n)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Zr.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,n){for(const r of Object.keys(e))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const n of this.reversePresenceKeys)e[n]=this.previousPresence[n];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class os{constructor(e){m(this,"rootObject");m(this,"elementPairMapByCreatedAt");m(this,"gcElementSetByCreatedAt");m(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof ht||n instanceof gt)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new os(qe.create(Et))}findByCreatedAt(e){const n=this.elementPairMapByCreatedAt.get(e.toIDString());if(n)return n.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let n=this.elementPairMapByCreatedAt.get(e.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),s=n.parent.subPathOf(i);if(s===void 0)throw new T(w.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,n){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:n,element:e}),e instanceof Ln&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let n=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),n++};return r(e),e instanceof Ln&&e.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const n of this.gcElementSetByCreatedAt){e.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof Ln&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new os(this.rootObject.deepcopy())}garbageCollect(e){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function jp(t,e){const n=new as(t);return new Proxy(e,n.getHandlers())}class as{constructor(e){m(this,"context");m(this,"handlers");this.context=e,this.handlers={set:(n,r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]=${JSON.stringify(i)}`),as.setInternal(e,n,r,i),!0),get:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Yn(e,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),as.deleteInternal(e,n,r),!0)}}static setInternal(e,n,r,i){if(r.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=Bo(e,i,s),a=n.set(r,o,s);e.registerElement(o,n),a&&e.registerRemovedElement(a),e.push(fr.create(r,o.deepcopy(),n.getCreatedAt(),s))}static buildObjectMembers(e,n){const r={};for(const[i,s]of Object.entries(n)){if(i.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Bo(e,s,o);r[i]=a}return r}static deleteInternal(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByKey(r,i);s&&(e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function w1(t,e){const n=new se(t,e);return new Proxy(e,n.getHandlers())}function S1(t){return typeof t=="string"||t instanceof String?!isNaN(t):!1}function T1(t){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(t)}class se{constructor(e,n){m(this,"context");m(this,"handlers");m(this,"array");this.context=e,this.array=n,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return mn(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return mn(e,a)}:i==="getLast"?()=>mn(e,r.getLast()):i==="deleteByID"?o=>{const a=se.deleteInternalByID(e,r,o);return mn(e,a)}:i==="insertAfter"?(o,a)=>{const l=se.insertAfterInternal(e,r,o,a);return mn(e,l)}:i==="insertBefore"?(o,a)=>{const l=se.insertBeforeInternal(e,r,o,a);return mn(e,l)}:i==="moveBefore"?(o,a)=>{se.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{se.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{se.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{se.moveLastInternal(e,r,o)}:S1(i)?Yn(e,r.get(Number(i))):i==="push"?o=>se.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>se.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?se.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>se.includes(e,r,o,a):i==="indexOf"?(o,a)=>se.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>se.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>se.toTestString(r):typeof i=="string"&&T1(i)?(...o)=>{const a=Array.from(r).map(l=>Yn(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`array[${i}]`),se.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,n){for(const r of n)yield mn(e,r)}static buildArrayElements(e,n){const r=[];for(const i of n){const s=e.issueTimeTicket(),o=Bo(e,i,s);r.push(o)}return r}static pushInternal(e,n,r){return se.insertAfterInternal(e,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(e,n,r,i){const s=e.issueTimeTicket(),o=n.getPrevCreatedAt(r);n.moveAfter(o,i,s),e.push(En.create(n.getCreatedAt(),o,i,s))}static moveAfterInternal(e,n,r,i){const s=e.issueTimeTicket();n.moveAfter(r,i,s),e.push(En.create(n.getCreatedAt(),r,i,s))}static moveFrontInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getHead();n.moveAfter(s.getCreatedAt(),r,i),e.push(En.create(n.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getLastCreatedAt();n.moveAfter(s,r,i),e.push(En.create(n.getCreatedAt(),s,r,i))}static insertAfterInternal(e,n,r,i){const s=e.issueTimeTicket(),o=Bo(e,i,s);return n.insertAfter(r,o),e.registerElement(o,n),e.push(gs.create(n.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,n,r,i){return se.insertAfterInternal(e,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByIndex(r,i);if(s)return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,n,r){const i=e.issueTimeTicket(),s=n.delete(r,i);return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,n,r,i,...s){const o=n.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),u=[];for(let c=a;c=s)return!1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).includes(r,o);for(let l=o;l=s)return-1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=n.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class aa{constructor(e,n){m(this,"context");m(this,"text");this.context=e,this.text=n}initialize(e,n){this.context=e,this.text=n}getID(){return this.text.getID()}edit(e,n,r,i){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${n}->${s[1].toTestString()} c:${r}`);const o=i?Xr(i):void 0,a=this.context.issueTimeTicket(),[l,,u,c]=this.text.edit(s,r,a,o);for(const f of u)this.context.registerGCPair(f);return this.context.push(new ps(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,n){return this.edit(e,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,n,r){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=Xr(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const u of l)this.context.registerGCPair(u);return this.context.push(new ms(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(e[0],e[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([Nt.fromStruct(e[0]),Nt.fromStruct(e[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,n){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,n)}}class la{constructor(e,n){m(this,"valueType");m(this,"value");m(this,"context");m(this,"counter");this.valueType=e,this.value=n}initialize(e,n){this.valueType=n.getValueType(),this.context=e,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=ne.of(e,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ti.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function oc(t,e,n){const{type:r}=t,i=n.issueTimeTicket();if(r===sn){Vp(t);const{value:s}=t,o=Xe.create(Ae.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=t,{attributes:o}=t;let a;if(typeof o=="object"&&!pp(o)){const u=Xr(o);a=new fn;for(const[c,f]of Object.entries(u))a.set(c,f,i)}const l=Xe.create(Ae.of(i,0),r,void 0,a);e.append(l);for(const u of s)oc(u,l,n)}}function k1(t,e){const{type:n}=e,r=t.issueTimeTicket();let i;if(e.type===sn){const{value:s}=e;i=Xe.create(Ae.of(r,0),n,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!pp(o)){const l=Xr(o);a=new fn;for(const[u,c]of Object.entries(l))a.set(u,c,r)}i=Xe.create(Ae.of(t.issueTimeTicket(),0),n,void 0,a);for(const l of s)oc(l,i,t)}return i}function Vp(t){if(!t.value.length)throw new T(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function ed(t){if(!t.length)return!0;if(t[0].type===sn)for(const n of t){const{type:r}=n;if(r!==sn)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together");Vp(n)}else for(const n of t){const{type:r}=n;if(r===sn)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ua{constructor(e){m(this,"initialRoot");m(this,"context");m(this,"tree");this.initialRoot=e}initialize(e,n){this.context=e,this.tree=n}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ae.of(e.issueTimeTicket(),0),Iw);const n=Xe.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)oc(r,n,e);return n}getSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,n){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=n?Xr(n):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(on.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),a=r?Xr(r):void 0,[l,u]=this.tree.style([i,s],a,o);for(const c of u)this.context.registerGCPair(c);this.context.push(on.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const u of l)this.context.registerGCPair(u);this.context.push(on.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,n,r,i=0){var u;if(r.length!==0&&r[0]&&(ed(r),r[0].type!==sn))for(const c of r){const{children:f=[]}=c;ed(f)}const s=this.context.getLastTimeTicket();let o=new Array;if(((u=r[0])==null?void 0:u.type)===sn){let c="";for(const f of r){const{value:g}=f;c+=g}o.push(Xe.create(Ae.of(this.context.issueTimeTicket(),0),sn,c))}else o=r.map(c=>c&&k1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,n],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(ys.create(this.tree.getCreatedAt(),e,n,o.length?o:void 0,i,l,s)),!0}editByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r,i)}edit(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[kt.fromStruct(e[0]),kt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[kt.fromStruct(e[0]),kt.fromStruct(e[1])];return this.tree.posRangeToPathRange(n)}}function td(t,e){return jp(t,e)}function mn(t,e){if(e){if(e instanceof ne)return e;if(e instanceof qe)return jp(t,e);if(e instanceof et)return w1(t,e);if(e instanceof ht)return new aa(t,e);if(e instanceof tt){const n=new la(qt.IntegerCnt,0);return n.initialize(t,e),n}else if(e instanceof gt){const n=new ua;return n.initialize(t,e),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Yn(t,e){const n=mn(t,e);return n instanceof ne?n.getValue():n}function Bo(t,e,n){let r;if(ne.isSupport(e))r=ne.of(e,n);else if(Array.isArray(e))r=et.create(n,se.buildArrayElements(t,e));else if(typeof e=="object")e instanceof aa?(r=ht.create(ei.create(),n),e.initialize(t,r)):e instanceof la?(r=tt.create(e.getValueType(),e.getValue(),n),e.initialize(t,r)):e instanceof ua?(r=gt.create(e.buildRoot(t),n),e.initialize(t,r)):r=qe.create(n,as.buildObjectMembers(t,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const nd=50;class I1{constructor(){m(this,"undoStack",[]);m(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=nd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=nd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const A1="yorkie-devtools-panel",E1="yorkie-devtools-sdk";let vr="disconnected";const rd=new Map,oo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=oo);function Us(t,e){(e!=null&&e.force||vr!=="disconnected")&&window.postMessage({source:E1,...t},"*")}function N1(t){if(!t.isEnableDevtools()||typeof window>"u"||rd.has(t.getKey()))return;oo.set(t.getKey(),[]);const e=t.subscribe("all",n=>{n.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(oo.get(t.getKey()).push(n),vr==="synced"&&Us({msg:"doc::sync::partial",docKey:t.getKey(),event:n}))});rd.set(t.getKey(),[e]),Us({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==A1)return;switch(n.data.msg){case"devtools::connect":if(vr!=="disconnected")break;vr="connected",Us({msg:"doc::available",docKey:t.getKey()}),F.info(`[YD] Devtools connected. Doc: ${t.getKey()}`);break;case"devtools::disconnect":vr="disconnected",F.info(`[YD] Devtools disconnected. Doc: ${t.getKey()}`);break;case"devtools::subscribe":vr="synced",Us({msg:"doc::sync::full",docKey:t.getKey(),events:oo.get(t.getKey())}),F.info(`[YD] Devtools subscribed. Doc: ${t.getKey()}`);break}})}var yn=(t=>(t.Detached="detached",t.Attached="attached",t.Removed="removed",t))(yn||{}),$e=(t=>(t.StatusChanged="status-changed",t.ConnectionChanged="connection-changed",t.SyncStatusChanged="sync-status-changed",t.Snapshot="snapshot",t.LocalChange="local-change",t.RemoteChange="remote-change",t.Initialized="initialized",t.Watched="watched",t.Unwatched="unwatched",t.PresenceChanged="presence-changed",t.Broadcast="broadcast",t.LocalBroadcast="local-broadcast",t))($e||{}),ql=(t=>(t.Connected="connected",t.Disconnected="disconnected",t))(ql||{}),Hl=(t=>(t.Synced="synced",t.SyncFailed="sync-failed",t))(Hl||{});class Jp{constructor(e,n){m(this,"key");m(this,"status");m(this,"opts");m(this,"changeID");m(this,"checkpoint");m(this,"localChanges");m(this,"root");m(this,"clone");m(this,"eventStream");m(this,"eventStreamObserver");m(this,"onlineClients");m(this,"presences");m(this,"history");m(this,"internalHistory");m(this,"isUpdating");this.opts=n||{},this.key=e,this.status="detached",this.root=os.create(),this.changeID=Dw,this.checkpoint=Rw,this.localChanges=[],this.eventStream=v1(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new I1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},N1(this)}update(e,n){if(this.getStatus()==="removed")throw new T(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const s=td(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Va(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){F.isEnabled(be.Trivial)&&F.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,G.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const u=[];o.length>0&&u.push({type:"local-change",source:G.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&u.push({type:"presence-changed",source:G.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(u),F.isEnabled(be.Trivial)&&F.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,n,r,i){if(typeof e=="string"){if(typeof n!="function")throw new T(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},r,i)}if(e==="my-presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},r,i)}if(e==="others"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},r,i)}if(e==="connection"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="connection-changed"&&a(u)},r,i)}if(e==="status"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="status-changed"&&a(u)},r,i)}if(e==="sync"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="sync-status-changed"&&a(u)},r,i)}if(e==="local-broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="local-broadcast"&&a(u)},r)}if(e==="broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="broadcast"&&a(u)},r)}if(e==="all"){const a=n;return this.eventStream.subscribe(a,r,i)}const s=e,o=n;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const u=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&u.push(c);u.length&&o({...l,value:{...l.value,operations:u}})}},r,i)}if(typeof e=="function"){const s=e,o=n,a=r;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||s(u)},o,a)}throw new T(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,n){if(n===e)return!0;const r=e.split(".");return n.split(".").every((s,o)=>s===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),G.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,G.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),F.isEnabled(be.Trivial)&&F.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:vt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(e.length);return oa.create(this.key,n,!1,e)}setActor(e){for(const n of this.localChanges)n.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return td(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,n){const{root:r,presences:i}=ye.bytesToSnapshot(n);this.root=new os(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:G.Remote,value:{snapshot:this.isEnableDevtools()?ye.bytesToHex(n):void 0,serverSeq:e.toString()}}])}applyChanges(e,n){F.isEnabled(be.Debug)&&F.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),F.isEnabled(be.Trivial)&&F.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class hs{constructor(e){m(this,"createdAt");m(this,"movedAt");m(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ln extends hs{constructor(e){super(e)}}class Qu{constructor(e,n){m(this,"strKey");m(this,"value");this.strKey=e,this.value=n}static of(e,n){return new Qu(e,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class ns{constructor(){m(this,"nodeMapByKey");m(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new ns}set(e,n,r){let i;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(r)&&(i=s.getValue());const o=Qu.of(e,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),o),(s==null||r.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),n.setMovedAt(r)),i}delete(e,n){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(w.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(n),r.getValue()}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return n.getStrKey()}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(e,n){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(n))return r.getValue()}has(e){const n=this.nodeMapByKey.get(e);return n==null?!1:!n.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const n=this.nodeMapByKey.get(e);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class qe extends Ln{constructor(n,r){super(n);m(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new qe(n,ns.create());const i=ns.create();for(const[s,o]of Object.entries(r))i.set(s,o.deepcopy(),o.getCreatedAt());return new qe(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${Vt(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:s,value:o,type:a}=i.toJSForTest();n[r]={key:r,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[s]of this)n.push(s);const r=[];for(const s of n.sort()){const o=(i=this.memberNodes.get(s))==null?void 0:i.getValue();r.push(`"${Vt(s)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=qe.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var G=(t=>(t.Local="local",t.Remote="remote",t.UndoRedo="undoredo",t))(G||{});class Ct{constructor(e,n){m(this,"parentCreatedAt");m(this,"executedAt");this.parentCreatedAt=e,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(w.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class mp{constructor(e){m(this,"value");m(this,"left");m(this,"right");m(this,"parent");m(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class rs{constructor(e){m(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&e<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new T(w.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${n.getLength()}`);return this.splayNode(n),[n,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,n){return e?(this.splayNode(e),this.root=n,n.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(n),n.setLeft(e),e.setParent(n),e.setRight(),this.updateWeight(e),this.updateWeight(n),n):(this.root=n,n)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const n=new rs(e.getLeft());n.root&&n.root.setParent();const r=new rs(e.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,n){if(!n){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(n),n.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const n=[];this.traversePostorder(e.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const n of e)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,n){e&&(this.traverseInorder(e.getLeft(),n),n.push(e),this.traverseInorder(e.getRight(),n))}traversePostorder(e,n){e&&(this.traversePostorder(e.getLeft(),n),this.traversePostorder(e.getRight(),n),n.push(e))}rotateLeft(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setRight(e.getLeft()),n.hasRight()&&n.getRight().setParent(n),e.setLeft(n),e.getLeft().setParent(e),this.updateWeight(n),this.updateWeight(e)}rotateRight(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setLeft(e.getRight()),n.hasLeft()&&n.getLeft().setParent(n),e.setRight(n),e.getRight().setParent(e),this.updateWeight(n),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var me=(t=>(t[t.Null=0]="Null",t[t.Boolean=1]="Boolean",t[t.Integer=2]="Integer",t[t.Long=3]="Long",t[t.Double=4]="Double",t[t.String=5]="String",t[t.Bytes=6]="Bytes",t[t.Date=7]="Date",t))(me||{});class ne extends hs{constructor(n,r){super(r);m(this,"valueType");m(this,"value");this.valueType=ne.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new ne(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return B.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(B.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Vt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=ne.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof B)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return ne.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=B.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Mo extends mp{constructor(n){super(n);m(this,"prev");m(this,"next");this.value=n}static createAfter(n,r){const i=new Mo(r),s=n.next;return n.next=i,i.prev=n,i.next=s,s&&(s.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class is{constructor(){m(this,"dummyHead");m(this,"last");m(this,"nodeMapByIndex");m(this,"nodeMapByCreatedAt");const e=ne.of(0,Et);e.setRemovedAt(Et),this.dummyHead=new Mo(e),this.last=this.dummyHead,this.nodeMapByIndex=new rs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new is}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,n){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=Mo.createAfter(i,n);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,n,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(n.toIDString());if(!s)throw new T(w.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(e){if(e>=this.length)return;const[n,r]=this.nodeMapByIndex.find(e);let i=n;if(e===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let n=this.nodeMapByCreatedAt.get(e.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(e,n){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,n){const r=this.getByIndex(e);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class et extends Ln{constructor(n,r){super(n);m(this,"elements");this.elements=r}static create(n,r){if(!r)return new et(n,is.create());const i=is.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new et(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...h,value:h.value?{attributes:zr(h.value.getAttributes()),content:h.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,g,c,[l,l]]}setStyle(n,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),l=[],u=this.rgaTreeSplit.findBetween(a,o),c=new Map,f=[];for(const h of u){const v=h.getCreatedAt().getActorID(),A=s!=null&&s.size?s.has(v)?s.get(v):Et:_i;if(h.canStyle(i,A)){const O=c.get(v),p=h.getCreatedAt();(!O||p.after(O))&&c.set(v,p),f.push(h)}}const g=[];for(const h of f){if(h.isRemoved())continue;const[v,A]=this.rgaTreeSplit.findIndexesFromRange(h.createPosRange());l.push({type:"style",actor:i.getActorID(),from:v,to:A,value:{attributes:zr(r)}});for(const[O,p]of Object.entries(r)){const[d]=h.getValue().setAttr(O,p,i);d!==void 0&&g.push({parent:h.getValue(),child:d})}}return[c,g,l]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:zr(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new ht(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class ps extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"content");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(n,r,i,s,o,a,l){return new ps(n,r,i,s,o,a,l)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ht))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u})=>({type:"edit",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${n}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ms extends Ct{constructor(n,r,i,s,o,a){super(n,a);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(n,r,i,s,o,a){return new ms(n,r,i,s,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ht))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)n.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:u})=>({type:"style",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const kw=2,Iw="root",sn="text";function mi(t,e){let n=0;const r=t.children;for(let i=0;i0)throw new T(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const n=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*n,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===sn}get paddedSize(){return this.size+(this.isText?0:kw)}isAncestorOf(e){return Ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e+1];if(n)return n}get prevSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e-1];if(n)return n}splitText(e,n){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+n);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const n of e)n.parent=this,n.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const n of e)n.parent=this}insertBefore(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,n),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new T(w.ErrInvalidArgument,"child not found");this._children.splice(n,1),e.parent=void 0}splitElement(e,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.splice(n,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const n=this._children.indexOf(e);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");let n=e;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function Ew(t,e){if(t===e)return!1;for(;e.parent;){if(e.parent===t)return!0;e=e.parent}return!1}var fe=(t=>(t.Start="Start",t.End="End",t.Text="Text",t))(fe||{});function yp(t,e,n,r){if(e>n)throw new T(w.ErrInvalidArgument,`from is greater than to: ${e} > ${n}`);if(e>t.size)throw new T(w.ErrInvalidArgument,`from is out of range: ${e} > ${t.size}`);if(n>t.size)throw new T(w.ErrInvalidArgument,`to is out of range: ${n} > ${t.size}`);if(e===n)return;let i=0;for(const s of t.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],u),yp(s,Math.max(0,o),Math.min(a,s.size),r),u&&r([s,"End"],u)}i+=s.paddedSize}}function vp(t,e,n=0){for(const r of t.children)vp(r,e,n+1);e(t,n)}function sa(t,e,n=0){for(const r of t._children)sa(r,e,n+1);e(t,n)}function Kl(t,e,n=!0){if(e>t.size)throw new T(w.ErrInvalidArgument,`index is out of range: ${e} > ${t.size}`);if(t.isText)return{node:t,offset:e};let r=0,i=0;for(const s of t.children){if(n&&s.isText&&s.size>=e-i)return Kl(s,e-i,n);if(e===i)return{node:t,offset:r};if(!n&&s.paddedSize===e-i)return{node:t,offset:r+1};if(s.paddedSize>e-i)return Kl(s,e-i-1,n);i+=s.paddedSize,r+=1}return{node:t,offset:r}}function wp(t){return t.isText||t.children.length===0?t:wp(t.children[0])}function Nw(t,e){if(t.sizet===e?0:t0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,s=n;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,n){for(;n;){const r=this.comparator(e,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(e,n,r){if(!r)return this.counter+=1,new Pw(e,n,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,n,r.left):i>0?r.right=this.putInternal(e,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,n){if(this.comparator(n,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,n);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(n,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(n,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,n)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const n=e.right;return e.right=n.left,n.left=e,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(e){const n=e.left;return e.left=n.right,n.right=e,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class kt{constructor(e,n){m(this,"parentID");m(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=n}static of(e,n){return new kt(e,n)}static fromTreePos(e){const{offset:n}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],kt.of(r.id,Ae.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(e){return kt.of(Ae.of(We.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(We.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const n=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(n);let s=e.findFloorNode(r);if(!i||!s)throw new T(w.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ae{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Ae(e,n)}static fromStruct(e){return Ae.of(We.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=n,s}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new T(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new T(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Xe(Ae.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Xe(Ae.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=n.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,n.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new fn);const i=new Array;for(const[s,o]of Object.entries(n))i.push(this.attrs.set(s,o,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function Wl(t){var n;if(t.isText){const r=t;return{type:r.type,value:r.value}}const e={type:t.type,children:t.children.map(Wl)};return t.attrs&&(e.attributes=zr((n=t.attrs)==null?void 0:n.toObject())),e}function Xu(t){if(t.isText)return t.value;let e="";return t.attrs&&t.attrs.size()&&(e=" "+Array.from(t.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Vt(n.getValue())}"`}).join(" ")),`<${t.type}${e}>${t.children.map(n=>Xu(n)).join("")}`}function Tp(t){if(t.isText){const e=t;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:t.type,children:t.children.map(Tp),size:t.size,isRemoved:t.isRemoved}}class gt extends hs{constructor(n,r){super(r);m(this,"indexTree");m(this,"nodeMapByID");this.indexTree=new xw(n),this.nodeMapByID=new Sp(Ae.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new gt(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,s]=n.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,n.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const u=l.allChildren,c=a?0:u.indexOf(o)+1;for(let f=c;f{const A=v.getCreatedAt().getActorID(),O=s?s.has(A)?s.get(A):Et:_i;if(v.canStyle(i,O)&&r){const p=g.get(A),d=v.getCreatedAt();(!p||d.after(p))&&g.set(A,d);const y=v.setAttrs(r,i),k=y.reduce((P,[,_])=>(_&&(P[_.getKey()]=f[_.getKey()]),P),{}),N=v.parent,C=v.prevSibling||v.parent;Object.keys(k).length>0&&c.push({type:"style",from:this.toIndex(N,C),to:this.toIndex(v,v),fromPath:this.toPath(N,C),toPath:this.toPath(v,v),actor:i.getActorID(),value:k});for(const[P]of y)P&&h.push({parent:v,child:P})}}),[g,h,c]}removeStyle(n,r,i,s){const[o,a]=this.findNodesAndSplitText(n[0],i),[l,u]=this.findNodesAndSplitText(n[1],i),c=[],f=new Map,g=[];return this.traverseInPosRange(o,a,l,u,([h])=>{const v=h.getCreatedAt().getActorID(),A=s?s.has(v)?s.get(v):Et:_i;if(h.canStyle(i,A)&&r){const O=f.get(v),p=h.getCreatedAt();(!O||p.after(O))&&f.set(v,p),h.attrs||(h.attrs=new fn);for(const k of r){const N=h.attrs.remove(k,i);for(const C of N)g.push({parent:h,child:C})}const d=h.parent,y=h.prevSibling||h.parent;c.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(d,y),to:this.toIndex(h,h),fromPath:this.toPath(d,y),toPath:this.toPath(h,h),value:r})}}),[f,g,c]}edit(n,r,i,s,o,a){const[l,u]=this.findNodesAndSplitText(n[0],s),[c,f]=this.findNodesAndSplitText(n[1],s),g=this.toIndex(l,u),h=this.toPath(l,u),v=[],A=[],O=[],p=new Map;this.traverseInPosRange(l,u,c,f,([k,N],C)=>{if(N===fe.Start&&!C)for(const W of k.children)O.push(W);const P=k.getCreatedAt().getActorID(),_=a?a.has(P)?a.get(P):Et:_i;if(k.canDelete(s,_)||v.includes(k.parent)){const W=p.get(P),U=k.getCreatedAt();(!W||U.after(W))&&p.set(P,U),(N===fe.Text||N===fe.Start)&&v.push(k),A.push([k,N])}});const d=this.makeDeletionChanges(A,s),y=[];for(const k of v)k.remove(s),k.isRemoved&&y.push({parent:this,child:k});for(const k of O)k.removedAt||l.append(k);if(i>0){let k=0,N=l,C=u;for(;k{l.isRemoved&&(P.remove(s),y.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),C.isRemoved||k.push(C);if(k.length){const C=k.map(P=>Wl(P));d.length&&d[d.length-1].from===g?d[d.length-1].value=C:d.push({type:"content",from:g,to:g,fromPath:h,toPath:h,actor:s.getActorID(),value:C})}}return[d,y,p]}editT(n,r,i,s,o){const a=this.findPos(n[0]),l=this.findPos(n[1]);this.edit([a,l],r,i,s,o)}move(n,r,i){throw new T(w.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var s;(s=n.parent)==null||s.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return kt.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Xu(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var h,v,A,O;let l,u,c;const f=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;f&&(l=this.indexTree.indexOf(f),u=this.indexTree.treePosToPath(f),c=kt.fromTreePos(f).toStruct());const g={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(h=i.removedAt)==null?void 0:h.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(A=i.insNextID)==null?void 0:A.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?zr((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:u,pos:c};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=d,i[i.length-1].toPath=this.toPath(O,h)):i.push({type:"content",from:p,to:d,fromPath:this.toPath(A,f),toPath:this.toPath(O,h),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===fe.Start){const l=n.allChildren;return l.length>0?[l[0],l[0].isText?fe.Text:fe.Start]:[n,fe.End]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===s.length-1)return[i,fe.End];const a=s[o+1];return[a,a.isText?fe.Text:fe.Start]}findLeftToken([n,r]){if(r===fe.End){const l=n.allChildren;if(l.length>0){const u=l[l.length-1];return[u,u.isText?fe.Text:fe.End]}return[n,fe.Start]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===0)return[i,fe.Start];const a=s[o-1];return[a,a.isText?fe.Text:fe.End]}}class ys extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"contents");m(this,"splitLevel");m(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(n,r,i,s,o,a,l){return new ys(n,r,i,s,o,a,l)}execute(n){var l;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(u=>u.deepcopy()),this.splitLevel,i,(()=>{let u=i.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>We.of(i.getLamport(),++u,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)n.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${n}.EDIT(${r},${i},${s.map(o=>Xu(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class kn{constructor(e,n,r,i){m(this,"clientSeq");m(this,"serverSeq");m(this,"lamport");m(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=n,this.actor=r}static of(e,n,r,i){return new kn(e,n,r,i)}next(){return new kn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new kn(this.clientSeq,e,this.actor):new kn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return We.of(this.lamport,e,this.actor)}setActor(e){return new kn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Dw=new kn(0,B.fromInt(0,!0),ia);class Zr{constructor({id:e,operations:n,presenceChange:r,message:i}){m(this,"id");m(this,"operations");m(this,"presenceChange");m(this,"message");this.id=e,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:e,operations:n,presenceChange:r,message:i}){return new Zr({id:e,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const n of this.operations)n.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,n,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:u}=a;i.push(...l),u&&s.unshift(u)}return this.presenceChange&&(this.presenceChange.type===zn.Put?n.set(this.id.getActorID(),vt(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ye.bytesToHex(ye.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ye.bytesToHex(ye.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:n,operations:r,presenceChange:i,message:s}=e;return Zr.create({id:ye.bytesToChangeID(ye.hexToBytes(n)),operations:r==null?void 0:r.map(o=>ye.bytesToOperation(ye.hexToBytes(o))),presenceChange:i,message:s})}}class oa{constructor(e,n,r,i,s,o){m(this,"documentKey");m(this,"checkpoint");m(this,"isRemoved");m(this,"changes");m(this,"snapshot");m(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,n,r,i,s,o){return new oa(e,n,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Ur{constructor(e,n){m(this,"serverSeq");m(this,"clientSeq");this.serverSeq=e,this.clientSeq=n}static of(e,n){return new Ur(e,n)}increaseClientSeq(e){return e===0?this:new Ur(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const n=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return Ur.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Rw=new Ur(B.fromInt(0,!0),0);class Wt{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Wt(e,n)}static fromStruct(e){return Wt.of(We.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Wt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _w=Wt.of(Et,0);class Nt{constructor(e,n){m(this,"id");m(this,"relativeOffset");this.id=e,this.relativeOffset=n}static of(e,n){return new Nt(e,n)}static fromStruct(e){const n=Wt.fromStruct(e.id);return Nt.of(n,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Wt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Mn extends mp{constructor(n,r,i){super(r);m(this,"id");m(this,"removedAt");m(this,"prev");m(this,"next");m(this,"insPrev");m(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new Mn(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==e.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(e){const n=this.treeByID.floorEntry(e);if(n&&!(!n.key.equals(e)&&!n.key.hasSameCreatedAt(e)))return n.value}findBetween(e,n){const r=[];let i=e;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(e,n){if(n>e.getContentLength())throw new T(w.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return e;if(n===e.getContentLength())return e.getNext();const r=e.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,n,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,n,r),o=new Map,a=new Map,l=this.makeChanges(s,n);for(const u of i){const c=u.getCreatedAt().getActorID();(!o.has(c)||u.getID().getCreatedAt().after(o.get(c)))&&o.set(c,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(n)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,n,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const c=u.getCreatedAt().getActorID(),f=i?r.has(c)?r.get(c):Et:_i;u.canDelete(n,f)?s.push(u):o.push(u)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,n){const r=[];let i,s;for(let o=0;ot<0?Math.ceil(t):Math.floor(t);var qt=(t=>(t[t.IntegerCnt=0]="IntegerCnt",t[t.LongCnt=1]="LongCnt",t))(qt||{});class tt extends hs{constructor(n,r,i){super(i);m(this,"valueType");m(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=B.fromNumber(r).toInt():this.value=Xf(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=B.fromNumber(r):this.value=r;break;default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new tt(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return B.fromBytesLE(Array.from(r));default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=tt.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof B?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!tt.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===me.Long?this.value=this.value+n.getValue().toInt():this.value=B.fromNumber(this.value+Xf(n.getValue())).toInt(),this}}class ti extends Ct{constructor(n,r,i){super(n,i);m(this,"value");this.value=r}static create(n,r,i){return new ti(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof tt))throw new T(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===me.Long?n.getValue().multiply(-1):n.getValue()*-1;return ti.create(this.getParentCreatedAt(),ne.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class on extends Ct{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");m(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(n,r,i,s,o,a){return new on(n,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(n,r,i,s,o,a){return new on(n,r,i,s,new Map,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,u])=>a[l]=u),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u,fromPath:c,toPath:f})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:c,toPath:f,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function bw(t){const e=new Hu,n=e.data;for(const[r,i]of Object.entries(t))n[r]=JSON.stringify(i);return e}function Lw(t){if(t.type===zn.Put)return new Vl({type:ts.PUT,presence:bw(t.presence)});if(t.type===zn.Clear)return new Vl({type:ts.CLEAR});throw new T(w.ErrUnimplemented,"unimplemented type")}function Mw(t){return new cp({serverSeq:t.getServerSeqAsString(),clientSeq:t.getClientSeq()})}function kp(t){return new na({clientSeq:t.getClientSeq(),lamport:t.getLamportAsString(),actorId:sc(t.getActorID())})}function b(t){if(t)return new M({lamport:t.getLamportAsString(),delimiter:t.getDelimiter(),actorId:sc(t.getActorID())})}function Ip(t){switch(t){case me.Null:return z.NULL;case me.Boolean:return z.BOOLEAN;case me.Integer:return z.INTEGER;case me.Long:return z.LONG;case me.Double:return z.DOUBLE;case me.String:return z.STRING;case me.Bytes:return z.BYTES;case me.Date:return z.DATE;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ap(t){switch(t){case qt.IntegerCnt:return z.INTEGER_CNT;case qt.LongCnt:return z.LONG_CNT;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ja(t){if(t instanceof qe)return new Yt({type:z.JSON_OBJECT,createdAt:b(t.getCreatedAt()),value:Fp(t)});if(t instanceof et)return new Yt({type:z.JSON_ARRAY,createdAt:b(t.getCreatedAt()),value:f1(t)});if(t instanceof ht)return new Yt({type:z.TEXT,createdAt:b(t.getCreatedAt())});if(t instanceof ne)return new Yt({type:Ip(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof tt)return new Yt({type:Ap(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof gt)return new Yt({type:z.TREE,createdAt:b(t.getCreatedAt()),value:h1(t)});throw new T(w.ErrUnimplemented,"unimplemented element")}function Fw(t){return new jl({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function Bs(t){return new cr({createdAt:b(t.getID().getCreatedAt()),offset:t.getID().getOffset(),relativeOffset:t.getRelativeOffset()})}function $s(t){return new es({parentId:bi(t.getParentID()),leftSiblingId:bi(t.getLeftSiblingID())})}function bi(t){return new $r({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function Ep(t){const e=new Ku;if(t instanceof fr){const n=t,r=new Wg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.key=n.getKey(),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="set",e.body.value=r}else if(t instanceof gs){const n=t,r=new qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="add",e.body.value=r}else if(t instanceof En){const n=t,r=new Hg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="move",e.body.value=r}else if(t instanceof Un){const n=t,r=new Gg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(t instanceof ps){const n=t,r=new Yg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=Bs(n.getFromPos()),r.to=Bs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);r.content=n.getContent();const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(t instanceof ms){const n=t,r=new Qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=Bs(n.getFromPos()),r.to=Bs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="style",e.body.value=r}else if(t instanceof ti){const n=t,r=new Xg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.value=Ja(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(t instanceof ys){const n=t,r=new Zg,i=r.createdAtMapByActor;for(const[s,o]of n.getMaxCreatedAtMapByActor())i[s]=b(o);r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos()),r.contents=Jw(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=b(n.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(t instanceof on){const n=t,r=new ep;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=n.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of n.getAttributes())o[a]=l}r.executedAt=b(n.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(w.ErrUnimplemented,"unimplemented operation");return e}function Bw(t){const e=[];for(const n of t)e.push(Ep(n));return e}function $w(t){const e=new Kg({id:kp(t.getID()),message:t.getMessage()});return t.hasOperations()&&(e.operations=Bw(t.getOperations())),t.hasPresenceChange()&&(e.presenceChange=Lw(t.getPresenceChange())),e}function zw(t){const e=[];for(const n of t)e.push($w(n));return e}function Uw(t){const e=[];for(const n of t)e.push(new ap({key:n.getStrKey(),element:ec(n.getValue())}));return e}function jw(t){const e=[];for(const n of t)e.push(new Wu({element:ec(n.getValue())}));return e}function Vw(t){const e=[];for(const n of t){const r=new lp;r.id=Fw(n.getID()),r.value=n.getValue().getContent(),r.removedAt=b(n.getRemovedAt());const i=r.attributes,s=n.getValue().getAttrs();for(const o of s){const a=new ra;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function Jw(t){const e=[];if(!t||!t.length)return e;for(const n of t)e.push(new up({content:Zu(n)}));return e}function Kw(t){const e={};for(const n of t)e[n.getKey()]=new ra({value:n.getValue(),updatedAt:b(n.getUpdatedAt()),isRemoved:n.isRemoved()});return e}function Zu(t){if(!t)return[];const e=[];return sa(t,(n,r)=>{const i=new qu({id:bi(n.id),type:n.type,removedAt:b(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=bi(n.insPrevID)),n.insNextID&&(i.insNextId=bi(n.insNextID)),n.attrs&&(i.attributes=Kw(n.attrs)),e.push(i)}),e}function Ww(t){const e=new pt;return e.body.case="jsonObject",e.body.value=new tp({nodes:Uw(t.getRHT()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Np(t){const e=new pt;return e.body.case="jsonArray",e.body.value=new np({nodes:jw(t.getElements()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function qw(t){const e=new pt;return e.body.case="primitive",e.body.value=new rp({type:Ip(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Hw(t){const e=new pt;return e.body.case="text",e.body.value=new ip({nodes:Vw(t.getRGATreeSplit()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Gw(t){const e=new pt;return e.body.case="counter",e.body.value=new sp({type:Ap(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function xp(t){const e=new pt;return e.body.case="tree",e.body.value=new op({nodes:Zu(t.getRoot()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function ec(t){if(t instanceof qe)return Ww(t);if(t instanceof et)return Np(t);if(t instanceof ne)return qw(t);if(t instanceof ht)return Hw(t);if(t instanceof tt)return Gw(t);if(t instanceof gt)return xp(t);throw new T(w.ErrUnimplemented,"unimplemented element")}function Yw(t){return new hn({documentKey:t.getDocumentKey(),checkpoint:Mw(t.getCheckpoint()),isRemoved:t.getIsRemoved(),changes:zw(t.getChanges()),snapshot:t.getSnapshot(),minSyncedTicket:b(t.getMinSyncedTicket())})}function Zf(t){const e=t.findDetails(gw);for(const n of e)if(n.metadata.code)return n.metadata.code;return""}function Cp(t){let e;return t.serverSeq&&(e=B.fromString(t.serverSeq,!0)),kn.of(t.clientSeq,B.fromString(t.lamport,!0),ic(t.actorId),e)}function L(t){if(t)return We.of(B.fromString(t.lamport,!0),t.delimiter,ic(t.actorId))}function tc(t){const e={};return Object.entries(t.data).forEach(([n,r])=>{e[n]=JSON.parse(r)}),e}function Qw(t){const e=t.type;if(e===ts.PUT){const n=tc(t.presence);return{type:zn.Put,presence:n}}if(e===ts.CLEAR)return{type:zn.Clear};throw new T(w.ErrInvalidType,`unsupported type: ${e}`)}function Xw(t){const e=new Map;return Object.entries(t).forEach(([n,r])=>{e.set(n,tc(r))}),e}function Pp(t){switch(t){case z.NULL:return me.Null;case z.BOOLEAN:return me.Boolean;case z.INTEGER:return me.Integer;case z.LONG:return me.Long;case z.DOUBLE:return me.Double;case z.STRING:return me.String;case z.BYTES:return me.Bytes;case z.DATE:return me.Date}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Fo(t){switch(t){case z.INTEGER_CNT:return qt.IntegerCnt;case z.LONG_CNT:return qt.LongCnt}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Ka(t){switch(t.type){case z.JSON_OBJECT:return t.value?Mp(t.value):qe.create(L(t.createdAt));case z.JSON_ARRAY:return t.value?c1(t.value):et.create(L(t.createdAt));case z.TEXT:return ht.create(ei.create(),L(t.createdAt));case z.TREE:return d1(t.value);case z.NULL:case z.BOOLEAN:case z.INTEGER:case z.LONG:case z.DOUBLE:case z.STRING:case z.BYTES:case z.DATE:return ne.of(ne.valueFromBytes(Pp(t.type),t.value),L(t.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return tt.create(Fo(t.type),tt.valueFromBytes(Fo(t.type),t.value),L(t.createdAt))}}function zs(t){return Nt.of(Wt.of(L(t.createdAt),t.offset),t.relativeOffset)}function Op(t){return Wt.of(L(t.createdAt),t.offset)}function Zw(t){const e=ss.create(t.value);Object.entries(t.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,L(i.updatedAt))});const n=Mn.create(Op(t.id),e);return n.remove(L(t.removedAt)),n}function yr(t){return kt.of(Li(t.parentId),Li(t.leftSiblingId))}function Li(t){return Ae.of(L(t.createdAt),t.offset)}function e1(t){if(!t.length)return;const e=[];return t.forEach(n=>{const r=nc(n.content);e.push(r)}),e}function nc(t){if(t.length===0)return;const e=[];for(const i of t)e.push(n1(i));const n=e[e.length-1],r=new Map;r.set(t[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(t[i].depth-1).prepend(e[i]),r.set(t[i].depth,e[i]);return n.updateDescendantsSize(),gt.create(n,Et).getRoot()}function t1(t){const e=fn.create();for(const[n,r]of Object.entries(t))e.setInternal(n,r.value,L(r.updatedAt),r.isRemoved);return e}function n1(t){const e=Li(t.id),n=Xe.create(e,t.type),r=Object.entries(t.attributes);return n.isText?n.value=t.value:r.length&&(n.attrs=t1(t.attributes)),t.insPrevId&&(n.insPrevID=Li(t.insPrevId)),t.insNextId&&(n.insNextID=Li(t.insNextId)),n.removedAt=L(t.removedAt),n}function Dp(t){if(t.body.case==="set"){const e=t.body.value;return fr.create(e.key,Ka(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(t.body.case==="add"){const e=t.body.value;return gs.create(L(e.parentCreatedAt),L(e.prevCreatedAt),Ka(e.value),L(e.executedAt))}else if(t.body.case==="move"){const e=t.body.value;return En.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="remove"){const e=t.body.value;return Un.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="edit"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ps.create(L(e.parentCreatedAt),zs(e.from),zs(e.to),n,e.content,r,L(e.executedAt))}else if(t.body.case==="style"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ms.create(L(e.parentCreatedAt),zs(e.from),zs(e.to),n,r,L(e.executedAt))}else{if(t.body.case==="select")return;if(t.body.case==="increase"){const e=t.body.value;return ti.create(L(e.parentCreatedAt),Ka(e.value),L(e.executedAt))}else if(t.body.case==="treeEdit"){const e=t.body.value,n=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{n.set(r,L(i))}),ys.create(L(e.parentCreatedAt),yr(e.from),yr(e.to),e1(e.contents),e.splitLevel,n,L(e.executedAt))}else if(t.body.case==="treeStyle"){const e=t.body.value,n=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,L(o))}),(r==null?void 0:r.length)>0?on.createTreeRemoveStyleOperation(L(e.parentCreatedAt),yr(e.from),yr(e.to),i,r,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{n.set(s,o)}),on.create(L(e.parentCreatedAt),yr(e.from),yr(e.to),i,n,L(e.executedAt)))}else throw new T(w.ErrUnimplemented,"unimplemented operation")}}function r1(t){const e=[];for(const n of t){const r=Dp(n);r&&e.push(r)}return e}function Rp(t){const e=[];for(const n of t)e.push(Zr.create({id:Cp(n.id),operations:r1(n.operations),presenceChange:n.presenceChange?Qw(n.presenceChange):void 0,message:n.message}));return e}function i1(t){return Ur.of(B.fromString(t.serverSeq,!0),t.clientSeq)}function s1(t){return oa.create(t.documentKey,i1(t.checkpoint),t.isRemoved,Rp(t.changes),t.snapshot,L(t.minSyncedTicket))}function _p(t){const e=new ns;for(const r of t.nodes){const i=rc(r.element);e.set(r.key,i,i.getPositionedAt())}const n=new qe(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function bp(t){const e=new is;for(const r of t.nodes)e.insert(rc(r.element));const n=new et(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function o1(t){const e=ne.of(ne.valueFromBytes(Pp(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function a1(t){const e=new ei;let n=e.getHead();for(const i of t.nodes){const s=e.insertAfter(n,Zw(i));i.insPrevId&&s.setInsPrev(e.findNode(Op(i.insPrevId))),n=s}const r=new ht(e,L(t.createdAt));return r.setMovedAt(L(t.movedAt)),r.setRemovedAt(L(t.removedAt)),r}function l1(t){const e=tt.create(Fo(t.type),tt.valueFromBytes(Fo(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function Lp(t){const e=nc(t.nodes);return gt.create(e,L(t.createdAt))}function rc(t){if(t.body.case==="jsonObject")return _p(t.body.value);if(t.body.case==="jsonArray")return bp(t.body.value);if(t.body.case==="primitive")return o1(t.body.value);if(t.body.case==="text")return a1(t.body.value);if(t.body.case==="counter")return l1(t.body.value);if(t.body.case==="tree")return Lp(t.body.value);throw new T(w.ErrUnimplemented,"unimplemented element")}function u1(t){if(!t)return{root:qe.create(Et),presences:new Map};const e=J0.fromBinary(t);return{root:rc(e.root),presences:Xw(e.presences)}}function Mp(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return _p(e.body.value)}function Fp(t){return ec(t).toBinary()}function c1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return bp(e.body.value)}function f1(t){return Np(t).toBinary()}function d1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=pt.fromBinary(t);return Lp(e.body.value)}function h1(t){return xp(t).toBinary()}function Bp(t){return t?Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ic(t){return Bp(t)}function $p(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function sc(t){return $p(t)}function g1(t){const e=na.fromBinary(t);return Cp(e)}function p1(t){const e=Ku.fromBinary(t);return Dp(e)}const ye={fromPresence:tc,toChangePack:Yw,fromChangePack:s1,fromChanges:Rp,toTreeNodes:Zu,fromTreeNodes:nc,objectToBytes:Fp,bytesToObject:Mp,bytesToSnapshot:u1,bytesToHex:Bp,hexToBytes:$p,toHexString:ic,toUint8Array:sc,toOperation:Ep,toChangeID:kp,PbChangeID:na,bytesToChangeID:g1,bytesToOperation:p1};var be=(t=>(t[t.Trivial=0]="Trivial",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.Fatal=5]="Fatal",t))(be||{});let Gn=3;function zp(t){Gn=t}const F={trivial:(...t)=>{Gn>0||typeof console<"u"&&console.log("YORKIE T:",...t)},debug:(...t)=>{Gn>1||typeof console<"u"&&console.log("YORKIE D:",...t)},info:(...t)=>{Gn>2||typeof console<"u"&&console.log("YORKIE I:",...t)},warn:(...t)=>{Gn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:(...t)=>{Gn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:(...t)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...t):console.log("YORKIE F:",...t))},isEnabled:t=>Gn<=t};function Up(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class m1{constructor(e,n,r,i,s){m(this,"reconnectStreamDelay");m(this,"doc");m(this,"docID");m(this,"syncMode");m(this,"remoteChangeEventReceived");m(this,"watchStream");m(this,"watchLoopTimerID");m(this,"watchAbortController");m(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===ao.RealtimeSyncOff?!1:this.syncMode===ao.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==ao.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Wa=()=>{};class y1{constructor(e){m(this,"finalized",!1);m(this,"observers",[]);m(this,"finalError");try{e(this)}catch(n){this.error(n)}}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(!e)throw new T(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=Wa),i.error===void 0&&(i.error=Wa),i.complete===void 0&&(i.complete=Wa);const s=Up(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){F.warn(a)}return o}unsubscribeOne(e){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let n=0;ne}}class Rr{constructor(e,n,r,i){m(this,"id");m(this,"delimiter");m(this,"message");m(this,"root");m(this,"operations");m(this,"presenceChange");m(this,"previousPresence");m(this,"reversePresenceKeys");this.id=e,this.delimiter=Yu,this.root=n,this.operations=[],this.previousPresence=vt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,n,r,i){return new Rr(e,n,r,i)}push(e){this.operations.push(e)}registerElement(e,n){this.root.registerElement(e,n)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Zr.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,n){for(const r of Object.keys(e))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const n of this.reversePresenceKeys)e[n]=this.previousPresence[n];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class os{constructor(e){m(this,"rootObject");m(this,"elementPairMapByCreatedAt");m(this,"gcElementSetByCreatedAt");m(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof ht||n instanceof gt)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new os(qe.create(Et))}findByCreatedAt(e){const n=this.elementPairMapByCreatedAt.get(e.toIDString());if(n)return n.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let n=this.elementPairMapByCreatedAt.get(e.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),s=n.parent.subPathOf(i);if(s===void 0)throw new T(w.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,n){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:n,element:e}),e instanceof Ln&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let n=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),n++};return r(e),e instanceof Ln&&e.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const n of this.gcElementSetByCreatedAt){e.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof Ln&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new os(this.rootObject.deepcopy())}garbageCollect(e){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function jp(t,e){const n=new as(t);return new Proxy(e,n.getHandlers())}class as{constructor(e){m(this,"context");m(this,"handlers");this.context=e,this.handlers={set:(n,r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]=${JSON.stringify(i)}`),as.setInternal(e,n,r,i),!0),get:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Yn(e,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),as.deleteInternal(e,n,r),!0)}}static setInternal(e,n,r,i){if(r.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=Bo(e,i,s),a=n.set(r,o,s);e.registerElement(o,n),a&&e.registerRemovedElement(a),e.push(fr.create(r,o.deepcopy(),n.getCreatedAt(),s))}static buildObjectMembers(e,n){const r={};for(const[i,s]of Object.entries(n)){if(i.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Bo(e,s,o);r[i]=a}return r}static deleteInternal(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByKey(r,i);s&&(e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function w1(t,e){const n=new se(t,e);return new Proxy(e,n.getHandlers())}function S1(t){return typeof t=="string"||t instanceof String?!isNaN(t):!1}function T1(t){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(t)}class se{constructor(e,n){m(this,"context");m(this,"handlers");m(this,"array");this.context=e,this.array=n,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return mn(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return mn(e,a)}:i==="getLast"?()=>mn(e,r.getLast()):i==="deleteByID"?o=>{const a=se.deleteInternalByID(e,r,o);return mn(e,a)}:i==="insertAfter"?(o,a)=>{const l=se.insertAfterInternal(e,r,o,a);return mn(e,l)}:i==="insertBefore"?(o,a)=>{const l=se.insertBeforeInternal(e,r,o,a);return mn(e,l)}:i==="moveBefore"?(o,a)=>{se.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{se.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{se.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{se.moveLastInternal(e,r,o)}:S1(i)?Yn(e,r.get(Number(i))):i==="push"?o=>se.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>se.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?se.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>se.includes(e,r,o,a):i==="indexOf"?(o,a)=>se.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>se.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>se.toTestString(r):typeof i=="string"&&T1(i)?(...o)=>{const a=Array.from(r).map(l=>Yn(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`array[${i}]`),se.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,n){for(const r of n)yield mn(e,r)}static buildArrayElements(e,n){const r=[];for(const i of n){const s=e.issueTimeTicket(),o=Bo(e,i,s);r.push(o)}return r}static pushInternal(e,n,r){return se.insertAfterInternal(e,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(e,n,r,i){const s=e.issueTimeTicket(),o=n.getPrevCreatedAt(r);n.moveAfter(o,i,s),e.push(En.create(n.getCreatedAt(),o,i,s))}static moveAfterInternal(e,n,r,i){const s=e.issueTimeTicket();n.moveAfter(r,i,s),e.push(En.create(n.getCreatedAt(),r,i,s))}static moveFrontInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getHead();n.moveAfter(s.getCreatedAt(),r,i),e.push(En.create(n.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getLastCreatedAt();n.moveAfter(s,r,i),e.push(En.create(n.getCreatedAt(),s,r,i))}static insertAfterInternal(e,n,r,i){const s=e.issueTimeTicket(),o=Bo(e,i,s);return n.insertAfter(r,o),e.registerElement(o,n),e.push(gs.create(n.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,n,r,i){return se.insertAfterInternal(e,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByIndex(r,i);if(s)return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,n,r){const i=e.issueTimeTicket(),s=n.delete(r,i);return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,n,r,i,...s){const o=n.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),u=[];for(let c=a;c=s)return!1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).includes(r,o);for(let l=o;l=s)return-1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ne.isSupport(r))return Array.from(n).map(u=>Yn(e,u)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=n.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class aa{constructor(e,n){m(this,"context");m(this,"text");this.context=e,this.text=n}initialize(e,n){this.context=e,this.text=n}getID(){return this.text.getID()}edit(e,n,r,i){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${n}->${s[1].toTestString()} c:${r}`);const o=i?Xr(i):void 0,a=this.context.issueTimeTicket(),[l,,u,c]=this.text.edit(s,r,a,o);for(const f of u)this.context.registerGCPair(f);return this.context.push(new ps(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,n){return this.edit(e,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,n,r){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=Xr(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const u of l)this.context.registerGCPair(u);return this.context.push(new ms(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(e[0],e[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([Nt.fromStruct(e[0]),Nt.fromStruct(e[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,n){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,n)}}class la{constructor(e,n){m(this,"valueType");m(this,"value");m(this,"context");m(this,"counter");this.valueType=e,this.value=n}initialize(e,n){this.valueType=n.getValueType(),this.context=e,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=ne.of(e,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ti.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function oc(t,e,n){const{type:r}=t,i=n.issueTimeTicket();if(r===sn){Vp(t);const{value:s}=t,o=Xe.create(Ae.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=t,{attributes:o}=t;let a;if(typeof o=="object"&&!pp(o)){const u=Xr(o);a=new fn;for(const[c,f]of Object.entries(u))a.set(c,f,i)}const l=Xe.create(Ae.of(i,0),r,void 0,a);e.append(l);for(const u of s)oc(u,l,n)}}function k1(t,e){const{type:n}=e,r=t.issueTimeTicket();let i;if(e.type===sn){const{value:s}=e;i=Xe.create(Ae.of(r,0),n,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!pp(o)){const l=Xr(o);a=new fn;for(const[u,c]of Object.entries(l))a.set(u,c,r)}i=Xe.create(Ae.of(t.issueTimeTicket(),0),n,void 0,a);for(const l of s)oc(l,i,t)}return i}function Vp(t){if(!t.value.length)throw new T(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function ed(t){if(!t.length)return!0;if(t[0].type===sn)for(const n of t){const{type:r}=n;if(r!==sn)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together");Vp(n)}else for(const n of t){const{type:r}=n;if(r===sn)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ua{constructor(e){m(this,"initialRoot");m(this,"context");m(this,"tree");this.initialRoot=e}initialize(e,n){this.context=e,this.tree=n}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ae.of(e.issueTimeTicket(),0),Iw);const n=Xe.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)oc(r,n,e);return n}getSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,n){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=n?Xr(n):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(on.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),a=r?Xr(r):void 0,[l,u]=this.tree.style([i,s],a,o);for(const c of u)this.context.registerGCPair(c);this.context.push(on.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const u of l)this.context.registerGCPair(u);this.context.push(on.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,n,r,i=0){var u;if(r.length!==0&&r[0]&&(ed(r),r[0].type!==sn))for(const c of r){const{children:f=[]}=c;ed(f)}const s=this.context.getLastTimeTicket();let o=new Array;if(((u=r[0])==null?void 0:u.type)===sn){let c="";for(const f of r){const{value:g}=f;c+=g}o.push(Xe.create(Ae.of(this.context.issueTimeTicket(),0),sn,c))}else o=r.map(c=>c&&k1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,n],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(ys.create(this.tree.getCreatedAt(),e,n,o.length?o:void 0,i,l,s)),!0}editByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r,i)}edit(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[kt.fromStruct(e[0]),kt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[kt.fromStruct(e[0]),kt.fromStruct(e[1])];return this.tree.posRangeToPathRange(n)}}function td(t,e){return jp(t,e)}function mn(t,e){if(e){if(e instanceof ne)return e;if(e instanceof qe)return jp(t,e);if(e instanceof et)return w1(t,e);if(e instanceof ht)return new aa(t,e);if(e instanceof tt){const n=new la(qt.IntegerCnt,0);return n.initialize(t,e),n}else if(e instanceof gt){const n=new ua;return n.initialize(t,e),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Yn(t,e){const n=mn(t,e);return n instanceof ne?n.getValue():n}function Bo(t,e,n){let r;if(ne.isSupport(e))r=ne.of(e,n);else if(Array.isArray(e))r=et.create(n,se.buildArrayElements(t,e));else if(typeof e=="object")e instanceof aa?(r=ht.create(ei.create(),n),e.initialize(t,r)):e instanceof la?(r=tt.create(e.getValueType(),e.getValue(),n),e.initialize(t,r)):e instanceof ua?(r=gt.create(e.buildRoot(t),n),e.initialize(t,r)):r=qe.create(n,as.buildObjectMembers(t,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const nd=50;class I1{constructor(){m(this,"undoStack",[]);m(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=nd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=nd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const A1="yorkie-devtools-panel",E1="yorkie-devtools-sdk";let vr="disconnected";const rd=new Map,oo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=oo);function Us(t,e){(e!=null&&e.force||vr!=="disconnected")&&window.postMessage({source:E1,...t},"*")}function N1(t){if(!t.isEnableDevtools()||typeof window>"u"||rd.has(t.getKey()))return;oo.set(t.getKey(),[]);const e=t.subscribe("all",n=>{n.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(oo.get(t.getKey()).push(n),vr==="synced"&&Us({msg:"doc::sync::partial",docKey:t.getKey(),event:n}))});rd.set(t.getKey(),[e]),Us({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==A1)return;switch(n.data.msg){case"devtools::connect":if(vr!=="disconnected")break;vr="connected",Us({msg:"doc::available",docKey:t.getKey()}),F.info(`[YD] Devtools connected. Doc: ${t.getKey()}`);break;case"devtools::disconnect":vr="disconnected",F.info(`[YD] Devtools disconnected. Doc: ${t.getKey()}`);break;case"devtools::subscribe":vr="synced",Us({msg:"doc::sync::full",docKey:t.getKey(),events:oo.get(t.getKey())}),F.info(`[YD] Devtools subscribed. Doc: ${t.getKey()}`);break}})}var yn=(t=>(t.Detached="detached",t.Attached="attached",t.Removed="removed",t))(yn||{}),$e=(t=>(t.StatusChanged="status-changed",t.ConnectionChanged="connection-changed",t.SyncStatusChanged="sync-status-changed",t.Snapshot="snapshot",t.LocalChange="local-change",t.RemoteChange="remote-change",t.Initialized="initialized",t.Watched="watched",t.Unwatched="unwatched",t.PresenceChanged="presence-changed",t.Broadcast="broadcast",t.LocalBroadcast="local-broadcast",t))($e||{}),ql=(t=>(t.Connected="connected",t.Disconnected="disconnected",t))(ql||{}),Hl=(t=>(t.Synced="synced",t.SyncFailed="sync-failed",t))(Hl||{});class Jp{constructor(e,n){m(this,"key");m(this,"status");m(this,"opts");m(this,"changeID");m(this,"checkpoint");m(this,"localChanges");m(this,"root");m(this,"clone");m(this,"eventStream");m(this,"eventStreamObserver");m(this,"onlineClients");m(this,"presences");m(this,"history");m(this,"internalHistory");m(this,"isUpdating");this.opts=n||{},this.key=e,this.status="detached",this.root=os.create(),this.changeID=Dw,this.checkpoint=Rw,this.localChanges=[],this.eventStream=v1(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new I1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},N1(this)}update(e,n){if(this.getStatus()==="removed")throw new T(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const s=td(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Va(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){F.isEnabled(be.Trivial)&&F.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,G.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const u=[];o.length>0&&u.push({type:"local-change",source:G.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&u.push({type:"presence-changed",source:G.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(u),F.isEnabled(be.Trivial)&&F.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,n,r,i){if(typeof e=="string"){if(typeof n!="function")throw new T(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},r,i)}if(e==="my-presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},r,i)}if(e==="others"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},r,i)}if(e==="connection"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="connection-changed"&&a(u)},r,i)}if(e==="status"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="status-changed"&&a(u)},r,i)}if(e==="sync"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="sync-status-changed"&&a(u)},r,i)}if(e==="local-broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="local-broadcast"&&a(u)},r)}if(e==="broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="broadcast"&&a(u)},r)}if(e==="all"){const a=n;return this.eventStream.subscribe(a,r,i)}const s=e,o=n;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const u=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&u.push(c);u.length&&o({...l,value:{...l.value,operations:u}})}},r,i)}if(typeof e=="function"){const s=e,o=n,a=r;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||s(u)},o,a)}throw new T(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,n){if(n===e)return!0;const r=e.split(".");return n.split(".").every((s,o)=>s===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),G.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,G.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),F.isEnabled(be.Trivial)&&F.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:vt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(e.length);return oa.create(this.key,n,!1,e)}setActor(e){for(const n of this.localChanges)n.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return td(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,n){const{root:r,presences:i}=ye.bytesToSnapshot(n);this.root=new os(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:G.Remote,value:{snapshot:this.isEnableDevtools()?ye.bytesToHex(n):void 0,serverSeq:e.toString()}}])}applyChanges(e,n){F.isEnabled(be.Debug)&&F.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),F.isEnabled(be.Trivial)&&F.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of e)this.applyChange(r,n);F.isEnabled(be.Debug)&&F.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,n){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,n);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case zn.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:o.presence}}:{type:"watched",source:G.Remote,value:{clientID:i,presence:o.presence}});break;case zn.Clear:r.push({type:"unwatched",source:G.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(n===G.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const n=e.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:G.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:n,publisher:r}=e.body.value,i=[];if(n===Ri.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:G.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===Ri.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:G.Remote,value:{clientID:r,presence:s}})}else if(n===Ri.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(ia),this.publish([{source:e==="removed"?G.Remote:G.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:n,serverSeq:r}=e.value;if(!n)return;this.applySnapshot(B.fromString(r),ye.hexToBytes(n));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const n=Zr.fromStruct(e.rawChange);this.applyChange(n,e.source)}if(e.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of e.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(e.type==="watched"){const{clientID:n,presence:r}=e.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(e.type==="unwatched"){const{clientID:n}=e.value;this.removeOnlineClient(n),this.presences.delete(n)}if(e.type==="presence-changed"){const{clientID:n,presence:r}=e.value;this.presences.set(n,r)}}applyTransactionEvent(e){for(const n of e)this.applyDocEvent(n)}getValueByPath(e){if(!e.startsWith("$"))throw new T(w.ErrInvalidArgument,'path must start with "$"');const n=e.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?vt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const n=this.presences.get(e);return n?vt(n):void 0}getPresenceForTest(e){const n=this.presences.get(e);return n?vt(n):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:vt(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&e.push({clientID:n,presence:vt(this.presences.get(n))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==e).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new T(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new T(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof Ct)){new Va(n,vt(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const c=n.issueTimeTicket();u.setExecutedAt(c),n.push(u)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,G.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,G.UndoRedo),o=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:G.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:G.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new T(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new T(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Rr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof Ct)){new Va(n,vt(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const c=n.issueTimeTicket();u.setExecutedAt(c),n.push(u)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,G.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,G.UndoRedo),o=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:G.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:G.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,n,r){const i={type:"local-broadcast",value:{topic:e,payload:n},options:r};this.publish([i])}}function x1(t,e){return n=>async r=>(t&&r.header.set("x-api-key",t),e&&r.header.set("authorization",e),await n(r))}const C1="yorkie-js-sdk",P1="0.5.0",O1="Yorkie JS SDK",D1="./src/yorkie.ts",R1={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},_1=["dist"],b1={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},L1={node:">=18.0.0",npm:">=7.1.0"},M1={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},F1={name:"hackerwins",email:"susukang98@gmail.com"},B1="Apache-2.0",$1={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},z1="https://github.com/yorkie-team/yorkie-js-sdk#readme",U1={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},j1={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},id={name:C1,version:P1,description:O1,main:D1,publishConfig:R1,files:_1,scripts:b1,engines:L1,repository:M1,author:F1,license:B1,bugs:$1,homepage:z1,devDependencies:U1,dependencies:j1};function V1(){return t=>async e=>(e.header.set("x-yorkie-user-agent",id.name+"/"+id.version),await t(e))}const J1=t=>{try{if(JSON.stringify(t)===void 0)return!1}catch{return!1}return!0};var ao=(t=>(t.Manual="manual",t.Realtime="realtime",t.RealtimePushOnly="realtime-pushonly",t.RealtimeSyncOff="realtime-syncoff",t))(ao||{});const js={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},qa={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Kp{constructor(e,n){m(this,"id");m(this,"key");m(this,"status");m(this,"attachmentMap");m(this,"apiKey");m(this,"conditions");m(this,"syncLoopDuration");m(this,"reconnectStreamDelay");m(this,"retrySyncLoopDelay");m(this,"rpcClient");m(this,"taskQueue");m(this,"processing",!1);n=n||js,this.key=n.key?n.key:Up(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||js.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||js.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||js.retrySyncLoopDelay,this.rpcClient=T0(dw,V0({baseUrl:e,interceptors:[x1(n.apiKey,n.token),V1()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),F.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw F.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),F.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw F.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,n={}){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==yn.Detached)throw new T(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(n.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,u=s.options;try{await this.broadcast(e.getKey(),o,a,u)}catch(f){f instanceof Error&&(l==null||l(f))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ye.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ye.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===yn.Removed||(e.applyStatus(yn.Attached),this.attachmentMap.set(e.getKey(),new m1(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),F.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw F.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,n={}){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:ye.toChangePack(e.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ye.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==yn.Removed&&e.applyStatus(yn.Detached),this.detachInternal(e.getKey()),F.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw F.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,n){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===n?e:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),e):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const n=this.attachmentMap.get(e.getKey());if(!n)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw F.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw F.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=ye.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ye.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),F.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw F.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,n,r,i){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new T(w.ErrDocumentNotAttached,`${e} is not attached`);if(!J1(r))throw new T(w.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??qa.maxRetries,a=qa.maxBackoff;let l=0;const u=f=>Math.min(qa.initialRetryInterval*2**f,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{F.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${n}"`)}).catch(f=>{if(F.error(`[BC] c:"${this.getKey()}" err:`,f),this.handleConnectError(f))if(lc(),u(l-1)),F.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw F.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),f;else throw f}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){F.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{F.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};F.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const n=this.attachmentMap.get(e);if(!n)throw new T(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new T(w.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return n.doc.publish([{type:$e.ConnectionChanged,value:ql.Connected}]),F.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const u of s)this.handleWatchDocumentsResponse(n,u),u.body.case==="initialization"&&o([s,i])}catch(u){n.doc.resetOnlineClients(),n.doc.publish([{type:$e.Initialized,source:G.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:$e.ConnectionChanged,value:ql.Disconnected}]),F.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(u)?r():this.conditions.WatchLoop=!1,a(u)}})()})})}handleWatchDocumentsResponse(e,n){if(n.body.case==="event"&&n.body.value.type===Ri.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[e,n]of this.attachmentMap)this.detachInternal(e),n.doc.applyStatus(yn.Detached)}detachInternal(e){const n=this.attachmentMap.get(e);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,n){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:ye.toChangePack(s),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ye.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Hl.Synced}]),r.getStatus()===yn.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),u=a.getChangeSize();return F.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${u} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Hl.SyncFailed}]),F.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof he?e.code===q.Canceled||e.code===q.Unknown||e.code===q.ResourceExhausted||e.code===q.Unavailable?!0:((Zf(e)===w.ErrClientNotActivated||Zf(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((n,r)=>{this.taskQueue.push(()=>e().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{F.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const sd={Client:Kp,Document:Jp,Primitive:ne,Text:aa,Counter:la,Tree:ua,LogLevel:be,setLogLevel:zp,IntType:qt.IntegerCnt,LongType:qt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Kp,Document:Jp,Primitive:ne,Text:aa,Counter:la,Tree:ua,LogLevel:be,setLogLevel:zp,IntType:qt.IntegerCnt,LongType:qt.LongCnt});var Wp={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see diff --git a/examples/react-todomvc/index.html b/examples/react-todomvc/index.html index d1fb0e0e5..141385b77 100644 --- a/examples/react-todomvc/index.html +++ b/examples/react-todomvc/index.html @@ -5,7 +5,7 @@ Vite + React + TS - + diff --git a/examples/simultaneous-cursors/assets/index-DHuCTpSh.js b/examples/simultaneous-cursors/assets/index-CLm6cX1q.js similarity index 70% rename from examples/simultaneous-cursors/assets/index-DHuCTpSh.js rename to examples/simultaneous-cursors/assets/index-CLm6cX1q.js index 99d4abbcb..1a431f455 100644 --- a/examples/simultaneous-cursors/assets/index-DHuCTpSh.js +++ b/examples/simultaneous-cursors/assets/index-CLm6cX1q.js @@ -58,5 +58,5 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var ut=null;try{ut=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function B(t,e,n){this.low=t|0,this.high=e|0,this.unsigned=!!n}B.prototype.__isLong__;Object.defineProperty(B.prototype,"__isLong__",{value:!0});function De(t){return(t&&t.__isLong__)===!0}function Hf(t){var e=Math.clz32(t&-t);return t?31-e:e}B.isLong=De;var Gf={},Yf={};function pr(t,e){var n,r,i;return e?(t>>>=0,(i=0<=t&&t<256)&&(r=Yf[t],r)?r:(n=K(t,0,!0),i&&(Yf[t]=n),n)):(t|=0,(i=-128<=t&&t<128)&&(r=Gf[t],r)?r:(n=K(t,t<0?-1:0,!1),i&&(Gf[t]=n),n))}B.fromInt=pr;function ct(t,e){if(isNaN(t))return e?rn:kt;if(e){if(t<0)return rn;if(t>=hp)return mp}else{if(t<=-Xf)return Ve;if(t+1>=Xf)return pp}return t<0?ct(-t,e).neg():K(t%Xr|0,t/Xr|0,e)}B.fromNumber=ct;function K(t,e,n){return new B(t,e,n)}B.fromBits=K;var Mo=Math.pow;function Xu(t,e,n){if(t.length===0)throw Error("empty string");if(typeof e=="number"?(n=e,e=!1):e=!!e,t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e?rn:kt;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return Xu(t.substring(1),e,n).neg();for(var i=ct(Mo(n,8)),s=kt,o=0;o>>0:this.low};x.toNumber=function(){return this.unsigned?(this.high>>>0)*Xr+(this.low>>>0):this.high*Xr+(this.low>>>0)};x.toString=function(e){if(e=e||10,e<2||36>>0,c=u.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};x.getHighBits=function(){return this.high};x.getHighBitsUnsigned=function(){return this.high>>>0};x.getLowBits=function(){return this.low};x.getLowBitsUnsigned=function(){return this.low>>>0};x.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ve)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,n=31;n>0&&!(e&1<=0};x.isOdd=function(){return(this.low&1)===1};x.isEven=function(){return(this.low&1)===0};x.equals=function(e){return De(e)||(e=Ot(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};x.eq=x.equals;x.notEquals=function(e){return!this.eq(e)};x.neq=x.notEquals;x.ne=x.notEquals;x.lessThan=function(e){return this.comp(e)<0};x.lt=x.lessThan;x.lessThanOrEqual=function(e){return this.comp(e)<=0};x.lte=x.lessThanOrEqual;x.le=x.lessThanOrEqual;x.greaterThan=function(e){return this.comp(e)>0};x.gt=x.greaterThan;x.greaterThanOrEqual=function(e){return this.comp(e)>=0};x.gte=x.greaterThanOrEqual;x.ge=x.greaterThanOrEqual;x.compare=function(e){if(De(e)||(e=Ot(e)),this.eq(e))return 0;var n=this.isNegative(),r=e.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};x.comp=x.compare;x.negate=function(){return!this.unsigned&&this.eq(Ve)?Ve:this.not().add(Rr)};x.neg=x.negate;x.add=function(e){De(e)||(e=Ot(e));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,u=e.low&65535,c=0,f=0,g=0,h=0;return h+=s+u,g+=h>>>16,h&=65535,g+=i+l,f+=g>>>16,g&=65535,f+=r+a,c+=f>>>16,f&=65535,c+=n+o,c&=65535,K(g<<16|h,c<<16|f,this.unsigned)};x.subtract=function(e){return De(e)||(e=Ot(e)),this.add(e.neg())};x.sub=x.subtract;x.multiply=function(e){if(this.isZero())return this;if(De(e)||(e=Ot(e)),ut){var n=ut.mul(this.low,this.high,e.low,e.high);return K(n,ut.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?rn:kt;if(this.eq(Ve))return e.isOdd()?Ve:kt;if(e.eq(Ve))return this.isOdd()?Ve:kt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Zf)&&e.lt(Zf))return ct(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,u=e.low>>>16,c=e.low&65535,f=0,g=0,h=0,v=0;return v+=o*c,h+=v>>>16,v&=65535,h+=s*c,g+=h>>>16,h&=65535,h+=o*u,g+=h>>>16,h&=65535,g+=i*c,f+=g>>>16,g&=65535,g+=s*u,f+=g>>>16,g&=65535,g+=o*l,f+=g>>>16,g&=65535,f+=r*c+i*u+s*l+o*a,f&=65535,K(h<<16|v,f<<16|g,this.unsigned)};x.mul=x.multiply;x.divide=function(e){if(De(e)||(e=Ot(e)),e.isZero())throw Error("division by zero");if(ut){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var n=(this.unsigned?ut.div_u:ut.div_s)(this.low,this.high,e.low,e.high);return K(n,ut.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?rn:kt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return rn;if(e.gt(this.shru(1)))return gp;s=rn}else{if(this.eq(Ve)){if(e.eq(Rr)||e.eq(ql))return Ve;if(e.eq(Ve))return Rr;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(kt)?e.isNegative()?Rr:ql:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(Ve))return this.unsigned?rn:kt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=kt}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:Mo(2,a-48),u=ct(r),c=u.mul(e);c.isNegative()||c.gt(i);)r-=l,u=ct(r,this.unsigned),c=u.mul(e);u.isZero()&&(u=Rr),s=s.add(u),i=i.sub(c)}return s};x.div=x.divide;x.modulo=function(e){if(De(e)||(e=Ot(e)),ut){var n=(this.unsigned?ut.rem_u:ut.rem_s)(this.low,this.high,e.low,e.high);return K(n,ut.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};x.mod=x.modulo;x.rem=x.modulo;x.not=function(){return K(~this.low,~this.high,this.unsigned)};x.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};x.clz=x.countLeadingZeros;x.countTrailingZeros=function(){return this.low?Hf(this.low):Hf(this.high)+32};x.ctz=x.countTrailingZeros;x.and=function(e){return De(e)||(e=Ot(e)),K(this.low&e.low,this.high&e.high,this.unsigned)};x.or=function(e){return De(e)||(e=Ot(e)),K(this.low|e.low,this.high|e.high,this.unsigned)};x.xor=function(e){return De(e)||(e=Ot(e)),K(this.low^e.low,this.high^e.high,this.unsigned)};x.shiftLeft=function(e){return De(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low<>>32-e,this.unsigned):K(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):K(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};x.shr=x.shiftRight;x.shiftRightUnsigned=function(e){return De(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?K(this.high,0,this.unsigned):K(this.high>>>e-32,0,this.unsigned)};x.shru=x.shiftRightUnsigned;x.shr_u=x.shiftRightUnsigned;x.rotateLeft=function(e){var n;return De(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(n=32-e,K(this.low<>>n,this.high<>>n,this.unsigned)):(e-=32,n=32-e,K(this.high<>>n,this.low<>>n,this.unsigned))};x.rotl=x.rotateLeft;x.rotateRight=function(e){var n;return De(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(n=32-e,K(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,n=32-e,K(this.low<>>e,this.high<>>e,this.unsigned))};x.rotr=x.rotateRight;x.toSigned=function(){return this.unsigned?K(this.low,this.high,!1):this};x.toUnsigned=function(){return this.unsigned?this:K(this.low,this.high,!0)};x.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};x.toBytesLE=function(){var e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};x.toBytesBE=function(){var e=this.high,n=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};B.fromBytes=function(e,n,r){return r?B.fromBytesLE(e,n):B.fromBytesBE(e,n)};B.fromBytesLE=function(e,n){return new B(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)};B.fromBytesBE=function(e,n){return new B(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)};const gw=S.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);S.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:tn}]);S.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:pw,repeated:!0}]);const pw=S.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});S.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:mw,repeated:!0}]);const mw=S.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});S.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:yw,repeated:!0}]);const yw=S.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});S.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);S.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:vw,repeated:!0}]);const vw=S.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});S.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var w=(t=>(t.Ok="ok",t.ErrClientNotActivated="ErrClientNotActivated",t.ErrClientNotFound="ErrClientNotFound",t.ErrUnimplemented="ErrUnimplemented",t.ErrInvalidType="ErrInvalidType",t.ErrDummy="ErrDummy",t.ErrDocumentNotAttached="ErrDocumentNotAttached",t.ErrDocumentNotDetached="ErrDocumentNotDetached",t.ErrDocumentRemoved="ErrDocumentRemoved",t.ErrInvalidObjectKey="ErrInvalidObjectKey",t.ErrInvalidArgument="ErrInvalidArgument",t.ErrNotInitialized="ErrNotInitialized",t.ErrNotReady="ErrNotReady",t.ErrRefused="ErrRefused",t.ErrContextNotProvided="ErrContextNotProvided",t))(w||{});class T extends Error{constructor(n,r){super(r);m(this,"name","YorkieError");m(this,"stack");this.code=n,this.message=r,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function wt(t){if(t instanceof Map){const e=Array.from(t);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(t))}const yp=t=>t?Object.entries(t).length===0:!0,Zr=t=>{const e={};for(const[n,r]of Object.entries(t))e[n]=JSON.stringify(r);return e},Ur=t=>{const e={};for(const[n,r]of Object.entries(t))e[n]=JSON.parse(r);return e};var zn=(t=>(t.Put="put",t.Clear="clear",t))(zn||{});class Ja{constructor(e,n){m(this,"context");m(this,"presence");this.context=e,this.presence=n}set(e,n){for(const r of Object.keys(e))this.presence[r]=e[r];this.context.setPresenceChange({type:"put",presence:wt(this.presence)}),this.context.setReversePresence(e,n)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const sa="000000000000000000000000",ww="FFFFFFFFFFFFFFFFFFFFFFFF";class qe{constructor(e,n,r){m(this,"lamport");m(this,"delimiter");m(this,"actorID");this.lamport=e,this.delimiter=n,this.actorID=r}static of(e,n,r){return new qe(e,n,r)}static fromStruct(e){return qe.of(B.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new qe(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const n=this.actorID.localeCompare(e.actorID);return n!==0?n:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Zu=0,Sw=4294967295,Tw=B.MAX_VALUE,Nt=new qe(B.fromNumber(0),Zu,sa);new qe(B.fromNumber(1),Zu+1,sa);const bi=new qe(Tw,Sw,ww);function Jt(t){return t.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class gs{constructor(e){m(this,"createdAt");m(this,"movedAt");m(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ln extends gs{constructor(e){super(e)}}class ec{constructor(e,n){m(this,"strKey");m(this,"value");this.strKey=e,this.value=n}static of(e,n){return new ec(e,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class rs{constructor(){m(this,"nodeMapByKey");m(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new rs}set(e,n,r){let i;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(r)&&(i=s.getValue());const o=ec.of(e,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),o),(s==null||r.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),n.setMovedAt(r)),i}delete(e,n){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(w.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(n),r.getValue()}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return n.getStrKey()}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(e,n){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(n))return r.getValue()}has(e){const n=this.nodeMapByKey.get(e);return n==null?!1:!n.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const n=this.nodeMapByKey.get(e);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class He extends Ln{constructor(n,r){super(n);m(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new He(n,rs.create());const i=rs.create();for(const[s,o]of Object.entries(r))i.set(s,o.deepcopy(),o.getCreatedAt());return new He(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${Jt(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:s,value:o,type:a}=i.toJSForTest();n[r]={key:r,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[s]of this)n.push(s);const r=[];for(const s of n.sort()){const o=(i=this.memberNodes.get(s))==null?void 0:i.getValue();r.push(`"${Jt(s)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=He.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var G=(t=>(t.Local="local",t.Remote="remote",t.UndoRedo="undoredo",t))(G||{});class Pt{constructor(e,n){m(this,"parentCreatedAt");m(this,"executedAt");this.parentCreatedAt=e,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(w.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class vp{constructor(e){m(this,"value");m(this,"left");m(this,"right");m(this,"parent");m(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class is{constructor(e){m(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&e<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new T(w.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${n.getLength()}`);return[n,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let n=0,r=e,i;for(;r;)(!i||i===r.getRight())&&(n+=r.getLength()+(r.hasLeft()?r.getLeftWeight():0)),i=r,r=r.getParent();return n-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,n){return e?(this.splayNode(e),this.root=n,n.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(n),n.setLeft(e),e.setParent(n),e.setRight(),this.updateWeight(e),this.updateWeight(n),n):(this.root=n,n)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const n=new is(e.getLeft());n.root&&n.root.setParent();const r=new is(e.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,n){if(!n){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(n),n.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const n=[];this.traversePostorder(e.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const n of e)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,n){e&&(this.traverseInorder(e.getLeft(),n),n.push(e),this.traverseInorder(e.getRight(),n))}traversePostorder(e,n){e&&(this.traversePostorder(e.getLeft(),n),this.traversePostorder(e.getRight(),n),n.push(e))}rotateLeft(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setRight(e.getLeft()),n.hasRight()&&n.getRight().setParent(n),e.setLeft(n),e.getLeft().setParent(e),this.updateWeight(n),this.updateWeight(e)}rotateRight(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setLeft(e.getRight()),n.hasLeft()&&n.getLeft().setParent(n),e.setRight(n),e.getRight().setParent(e),this.updateWeight(n),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var me=(t=>(t[t.Null=0]="Null",t[t.Boolean=1]="Boolean",t[t.Integer=2]="Integer",t[t.Long=3]="Long",t[t.Double=4]="Double",t[t.String=5]="String",t[t.Bytes=6]="Bytes",t[t.Date=7]="Date",t))(me||{});class te extends gs{constructor(n,r){super(r);m(this,"valueType");m(this,"value");this.valueType=te.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new te(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return B.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(B.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Jt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=te.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof B)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return te.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=B.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Fo extends vp{constructor(n){super(n);m(this,"prev");m(this,"next");this.value=n}static createAfter(n,r){const i=new Fo(r),s=n.next;return n.next=i,i.prev=n,i.next=s,s&&(s.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class ss{constructor(){m(this,"dummyHead");m(this,"last");m(this,"nodeMapByIndex");m(this,"nodeMapByCreatedAt");const e=te.of(0,Nt);e.setRemovedAt(Nt),this.dummyHead=new Fo(e),this.last=this.dummyHead,this.nodeMapByIndex=new is,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new ss}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,n){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=Fo.createAfter(i,n);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,n,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(n.toIDString());if(!s)throw new T(w.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(e){if(e>=this.length)return;const[n,r]=this.nodeMapByIndex.find(e);let i=n;if(e===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let n=this.nodeMapByCreatedAt.get(e.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(e,n){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,n){const r=this.getByIndex(e);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Ln{constructor(n,r){super(n);m(this,"elements");this.elements=r}static create(n,r){if(!r)return new tt(n,ss.create());const i=ss.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...h,value:h.value?{attributes:Ur(h.value.getAttributes()),content:h.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,g,c,[l,l]]}setStyle(n,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),l=[],u=this.rgaTreeSplit.findBetween(a,o),c=new Map,f=[];for(const h of u){const v=h.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(v)?s.get(v):Nt:bi;if(h.canStyle(i,I)){const O=c.get(v),p=h.getCreatedAt();(!O||p.after(O))&&c.set(v,p),f.push(h)}}const g=[];for(const h of f){if(h.isRemoved())continue;const[v,I]=this.rgaTreeSplit.findIndexesFromRange(h.createPosRange());l.push({type:"style",actor:i.getActorID(),from:v,to:I,value:{attributes:Ur(r)}});for(const[O,p]of Object.entries(r)){const[d]=h.getValue().setAttr(O,p,i);d!==void 0&&g.push({parent:h.getValue(),child:d})}}return[c,g,l]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Ur(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class ms extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"content");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(n,r,i,s,o,a,l){return new ms(n,r,i,s,o,a,l)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u})=>({type:"edit",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${n}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ys extends Pt{constructor(n,r,i,s,o,a){super(n,a);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(n,r,i,s,o,a){return new ys(n,r,i,s,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)n.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:u})=>({type:"style",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const kw=2,Aw="root",on="text";function yi(t,e){let n=0;const r=t.children;for(let i=0;i0)throw new T(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const n=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*n,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===on}get paddedSize(){return this.size+(this.isText?0:kw)}isAncestorOf(e){return Ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e+1];if(n)return n}get prevSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e-1];if(n)return n}splitText(e,n){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+n);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const n of e)n.parent=this,n.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const n of e)n.parent=this}insertBefore(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,n),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new T(w.ErrInvalidArgument,"child not found");this._children.splice(n,1),e.parent=void 0}splitElement(e,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.splice(n,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const n=this._children.indexOf(e);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");let n=e;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function Ew(t,e){if(t===e)return!1;for(;e.parent;){if(e.parent===t)return!0;e=e.parent}return!1}var fe=(t=>(t.Start="Start",t.End="End",t.Text="Text",t))(fe||{});function wp(t,e,n,r){if(e>n)throw new T(w.ErrInvalidArgument,`from is greater than to: ${e} > ${n}`);if(e>t.size)throw new T(w.ErrInvalidArgument,`from is out of range: ${e} > ${t.size}`);if(n>t.size)throw new T(w.ErrInvalidArgument,`to is out of range: ${n} > ${t.size}`);if(e===n)return;let i=0;for(const s of t.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],u),wp(s,Math.max(0,o),Math.min(a,s.size),r),u&&r([s,"End"],u)}i+=s.paddedSize}}function Sp(t,e,n=0){for(const r of t.children)Sp(r,e,n+1);e(t,n)}function oa(t,e,n=0){for(const r of t._children)oa(r,e,n+1);e(t,n)}function Hl(t,e,n=!0){if(e>t.size)throw new T(w.ErrInvalidArgument,`index is out of range: ${e} > ${t.size}`);if(t.isText)return{node:t,offset:e};let r=0,i=0;for(const s of t.children){if(n&&s.isText&&s.size>=e-i)return Hl(s,e-i,n);if(e===i)return{node:t,offset:r};if(!n&&s.paddedSize===e-i)return{node:t,offset:r+1};if(s.paddedSize>e-i)return Hl(s,e-i-1,n);i+=s.paddedSize,r+=1}return{node:t,offset:r}}function Tp(t){return t.isText||t.children.length===0?t:Tp(t.children[0])}function Nw(t,e){if(t.sizet===e?0:t0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,s=n;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,n){for(;n;){const r=this.comparator(e,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(e,n,r){if(!r)return this.counter+=1,new Pw(e,n,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,n,r.left):i>0?r.right=this.putInternal(e,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,n){if(this.comparator(n,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,n);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(n,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(n,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,n)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const n=e.right;return e.right=n.left,n.left=e,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(e){const n=e.left;return e.left=n.right,n.right=e,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class At{constructor(e,n){m(this,"parentID");m(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=n}static of(e,n){return new At(e,n)}static fromTreePos(e){const{offset:n}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],At.of(r.id,Ie.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(e){return At.of(Ie.of(qe.fromStruct(e.parentID.createdAt),e.parentID.offset),Ie.of(qe.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const n=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(n);let s=e.findFloorNode(r);if(!i||!s)throw new T(w.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ie{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Ie(e,n)}static fromStruct(e){return Ie.of(qe.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=n,s}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new T(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new T(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Ze(Ie.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Ze(Ie.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=n.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,n.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new dn);const i=new Array;for(const[s,o]of Object.entries(n))i.push(this.attrs.set(s,o,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function Gl(t){var n;if(t.isText){const r=t;return{type:r.type,value:r.value}}const e={type:t.type,children:t.children.map(Gl)};return t.attrs&&(e.attributes=Ur((n=t.attrs)==null?void 0:n.toObject())),e}function tc(t){if(t.isText)return t.value;let e="";return t.attrs&&t.attrs.size()&&(e=" "+Array.from(t.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Jt(n.getValue())}"`}).join(" ")),`<${t.type}${e}>${t.children.map(n=>tc(n)).join("")}`}function Ap(t){if(t.isText){const e=t;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:t.type,children:t.children.map(Ap),size:t.size,isRemoved:t.isRemoved}}class pt extends gs{constructor(n,r){super(r);m(this,"indexTree");m(this,"nodeMapByID");this.indexTree=new xw(n),this.nodeMapByID=new kp(Ie.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new pt(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,s]=n.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,n.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const u=l.allChildren,c=a?0:u.indexOf(o)+1;for(let f=c;f{const I=v.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Nt:bi;if(v.canStyle(i,O)&&r){const p=g.get(I),d=v.getCreatedAt();(!p||d.after(p))&&g.set(I,d);const y=v.setAttrs(r,i),k=y.reduce((P,[,_])=>(_&&(P[_.getKey()]=f[_.getKey()]),P),{}),N=v.parent,C=v.prevSibling||v.parent;Object.keys(k).length>0&&c.push({type:"style",from:this.toIndex(N,C),to:this.toIndex(v,v),fromPath:this.toPath(N,C),toPath:this.toPath(v,v),actor:i.getActorID(),value:k});for(const[P]of y)P&&h.push({parent:v,child:P})}}),[g,h,c]}removeStyle(n,r,i,s){const[o,a]=this.findNodesAndSplitText(n[0],i),[l,u]=this.findNodesAndSplitText(n[1],i),c=[],f=new Map,g=[];return this.traverseInPosRange(o,a,l,u,([h])=>{const v=h.getCreatedAt().getActorID(),I=s?s.has(v)?s.get(v):Nt:bi;if(h.canStyle(i,I)&&r){const O=f.get(v),p=h.getCreatedAt();(!O||p.after(O))&&f.set(v,p),h.attrs||(h.attrs=new dn);for(const k of r){const N=h.attrs.remove(k,i);for(const C of N)g.push({parent:h,child:C})}const d=h.parent,y=h.prevSibling||h.parent;c.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(d,y),to:this.toIndex(h,h),fromPath:this.toPath(d,y),toPath:this.toPath(h,h),value:r})}}),[f,g,c]}edit(n,r,i,s,o,a){const[l,u]=this.findNodesAndSplitText(n[0],s),[c,f]=this.findNodesAndSplitText(n[1],s),g=this.toIndex(l,u),h=this.toPath(l,u),v=[],I=[],O=[],p=new Map;this.traverseInPosRange(l,u,c,f,([k,N],C)=>{if(N===fe.Start&&!C)for(const W of k.children)O.push(W);const P=k.getCreatedAt().getActorID(),_=a?a.has(P)?a.get(P):Nt:bi;if(k.canDelete(s,_)||v.includes(k.parent)){const W=p.get(P),U=k.getCreatedAt();(!W||U.after(W))&&p.set(P,U),(N===fe.Text||N===fe.Start)&&v.push(k),I.push([k,N])}});const d=this.makeDeletionChanges(I,s),y=[];for(const k of v)k.remove(s),k.isRemoved&&y.push({parent:this,child:k});for(const k of O)k.removedAt||l.append(k);if(i>0){let k=0,N=l,C=u;for(;k{l.isRemoved&&(P.remove(s),y.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),C.isRemoved||k.push(C);if(k.length){const C=k.map(P=>Gl(P));d.length&&d[d.length-1].from===g?d[d.length-1].value=C:d.push({type:"content",from:g,to:g,fromPath:h,toPath:h,actor:s.getActorID(),value:C})}}return[d,y,p]}editT(n,r,i,s,o){const a=this.findPos(n[0]),l=this.findPos(n[1]);this.edit([a,l],r,i,s,o)}move(n,r,i){throw new T(w.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var s;(s=n.parent)==null||s.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return At.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var h,v,I,O;let l,u,c;const f=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;f&&(l=this.indexTree.indexOf(f),u=this.indexTree.treePosToPath(f),c=At.fromTreePos(f).toStruct());const g={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(h=i.removedAt)==null?void 0:h.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Ur((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:u,pos:c};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=d,i[i.length-1].toPath=this.toPath(O,h)):i.push({type:"content",from:p,to:d,fromPath:this.toPath(I,f),toPath:this.toPath(O,h),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===fe.Start){const l=n.allChildren;return l.length>0?[l[0],l[0].isText?fe.Text:fe.Start]:[n,fe.End]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===s.length-1)return[i,fe.End];const a=s[o+1];return[a,a.isText?fe.Text:fe.Start]}findLeftToken([n,r]){if(r===fe.End){const l=n.allChildren;if(l.length>0){const u=l[l.length-1];return[u,u.isText?fe.Text:fe.End]}return[n,fe.Start]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===0)return[i,fe.Start];const a=s[o-1];return[a,a.isText?fe.Text:fe.End]}}class vs extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"contents");m(this,"splitLevel");m(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(n,r,i,s,o,a,l){return new vs(n,r,i,s,o,a,l)}execute(n){var l;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof pt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(u=>u.deepcopy()),this.splitLevel,i,(()=>{let u=i.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>qe.of(i.getLamport(),++u,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)n.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${n}.EDIT(${r},${i},${s.map(o=>tc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class An{constructor(e,n,r,i){m(this,"clientSeq");m(this,"serverSeq");m(this,"lamport");m(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=n,this.actor=r}static of(e,n,r,i){return new An(e,n,r,i)}next(){return new An(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new An(this.clientSeq,e,this.actor):new An(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return qe.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Dw=new An(0,B.fromInt(0,!0),sa);class ei{constructor({id:e,operations:n,presenceChange:r,message:i}){m(this,"id");m(this,"operations");m(this,"presenceChange");m(this,"message");this.id=e,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:e,operations:n,presenceChange:r,message:i}){return new ei({id:e,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const n of this.operations)n.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,n,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:u}=a;i.push(...l),u&&s.unshift(u)}return this.presenceChange&&(this.presenceChange.type===zn.Put?n.set(this.id.getActorID(),wt(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ye.bytesToHex(ye.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ye.bytesToHex(ye.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:n,operations:r,presenceChange:i,message:s}=e;return ei.create({id:ye.bytesToChangeID(ye.hexToBytes(n)),operations:r==null?void 0:r.map(o=>ye.bytesToOperation(ye.hexToBytes(o))),presenceChange:i,message:s})}}class aa{constructor(e,n,r,i,s,o){m(this,"documentKey");m(this,"checkpoint");m(this,"isRemoved");m(this,"changes");m(this,"snapshot");m(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,n,r,i,s,o){return new aa(e,n,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class jr{constructor(e,n){m(this,"serverSeq");m(this,"clientSeq");this.serverSeq=e,this.clientSeq=n}static of(e,n){return new jr(e,n)}increaseClientSeq(e){return e===0?this:new jr(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const n=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return jr.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Rw=new jr(B.fromInt(0,!0),0);class qt{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new qt(e,n)}static fromStruct(e){return qt.of(qe.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new qt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _w=qt.of(Nt,0);class xt{constructor(e,n){m(this,"id");m(this,"relativeOffset");this.id=e,this.relativeOffset=n}static of(e,n){return new xt(e,n)}static fromStruct(e){const n=qt.fromStruct(e.id);return xt.of(n,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Mn extends vp{constructor(n,r,i){super(r);m(this,"id");m(this,"removedAt");m(this,"prev");m(this,"next");m(this,"insPrev");m(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new Mn(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==e.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(e){const n=this.treeByID.floorEntry(e);if(n&&!(!n.key.equals(e)&&!n.key.hasSameCreatedAt(e)))return n.value}findBetween(e,n){const r=[];let i=e;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(e,n){if(n>e.getContentLength())throw new T(w.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return e;if(n===e.getContentLength())return e.getNext();const r=e.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,n,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,n,r),o=new Map,a=new Map,l=this.makeChanges(s,n);for(const u of i){const c=u.getCreatedAt().getActorID();(!o.has(c)||u.getID().getCreatedAt().after(o.get(c)))&&o.set(c,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(n)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,n,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const c=u.getCreatedAt().getActorID(),f=i?r.has(c)?r.get(c):Nt:bi;u.canDelete(n,f)?s.push(u):o.push(u)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,n){const r=[];let i,s;for(let o=0;ot<0?Math.ceil(t):Math.floor(t);var Ht=(t=>(t[t.IntegerCnt=0]="IntegerCnt",t[t.LongCnt=1]="LongCnt",t))(Ht||{});class nt extends gs{constructor(n,r,i){super(i);m(this,"valueType");m(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=B.fromNumber(r).toInt():this.value=ed(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=B.fromNumber(r):this.value=r;break;default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new nt(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return B.fromBytesLE(Array.from(r));default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=nt.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof B?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!nt.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===me.Long?this.value=this.value+n.getValue().toInt():this.value=B.fromNumber(this.value+ed(n.getValue())).toInt(),this}}class ni extends Pt{constructor(n,r,i){super(n,i);m(this,"value");this.value=r}static create(n,r,i){return new ni(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new T(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===me.Long?n.getValue().multiply(-1):n.getValue()*-1;return ni.create(this.getParentCreatedAt(),te.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class an extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");m(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(n,r,i,s,o,a){return new an(n,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(n,r,i,s,o,a){return new an(n,r,i,s,new Map,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof pt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,u])=>a[l]=u),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u,fromPath:c,toPath:f})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:c,toPath:f,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function bw(t){const e=new Qu,n=e.data;for(const[r,i]of Object.entries(t))n[r]=JSON.stringify(i);return e}function Lw(t){if(t.type===zn.Put)return new Wl({type:ns.PUT,presence:bw(t.presence)});if(t.type===zn.Clear)return new Wl({type:ns.CLEAR});throw new T(w.ErrUnimplemented,"unimplemented type")}function Mw(t){return new dp({serverSeq:t.getServerSeqAsString(),clientSeq:t.getClientSeq()})}function Ip(t){return new ra({clientSeq:t.getClientSeq(),lamport:t.getLamportAsString(),actorId:lc(t.getActorID())})}function b(t){if(t)return new M({lamport:t.getLamportAsString(),delimiter:t.getDelimiter(),actorId:lc(t.getActorID())})}function Ep(t){switch(t){case me.Null:return z.NULL;case me.Boolean:return z.BOOLEAN;case me.Integer:return z.INTEGER;case me.Long:return z.LONG;case me.Double:return z.DOUBLE;case me.String:return z.STRING;case me.Bytes:return z.BYTES;case me.Date:return z.DATE;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Np(t){switch(t){case Ht.IntegerCnt:return z.INTEGER_CNT;case Ht.LongCnt:return z.LONG_CNT;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ka(t){if(t instanceof He)return new Qt({type:z.JSON_OBJECT,createdAt:b(t.getCreatedAt()),value:$p(t)});if(t instanceof tt)return new Qt({type:z.JSON_ARRAY,createdAt:b(t.getCreatedAt()),value:f1(t)});if(t instanceof gt)return new Qt({type:z.TEXT,createdAt:b(t.getCreatedAt())});if(t instanceof te)return new Qt({type:Ep(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof nt)return new Qt({type:Np(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof pt)return new Qt({type:z.TREE,createdAt:b(t.getCreatedAt()),value:h1(t)});throw new T(w.ErrUnimplemented,"unimplemented element")}function Fw(t){return new Kl({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function $s(t){return new fr({createdAt:b(t.getID().getCreatedAt()),offset:t.getID().getOffset(),relativeOffset:t.getRelativeOffset()})}function zs(t){return new ts({parentId:Li(t.getParentID()),leftSiblingId:Li(t.getLeftSiblingID())})}function Li(t){return new zr({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function xp(t){const e=new Hu;if(t instanceof dr){const n=t,r=new Hg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.key=n.getKey(),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="set",e.body.value=r}else if(t instanceof ps){const n=t,r=new Gg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="add",e.body.value=r}else if(t instanceof Nn){const n=t,r=new Yg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="move",e.body.value=r}else if(t instanceof Un){const n=t,r=new Qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(t instanceof ms){const n=t,r=new Xg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);r.content=n.getContent();const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(t instanceof ys){const n=t,r=new Zg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="style",e.body.value=r}else if(t instanceof ni){const n=t,r=new ep;r.parentCreatedAt=b(n.getParentCreatedAt()),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(t instanceof vs){const n=t,r=new tp,i=r.createdAtMapByActor;for(const[s,o]of n.getMaxCreatedAtMapByActor())i[s]=b(o);r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=zs(n.getFromPos()),r.to=zs(n.getToPos()),r.contents=Jw(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=b(n.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(t instanceof an){const n=t,r=new np;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=zs(n.getFromPos()),r.to=zs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=n.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of n.getAttributes())o[a]=l}r.executedAt=b(n.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(w.ErrUnimplemented,"unimplemented operation");return e}function Bw(t){const e=[];for(const n of t)e.push(xp(n));return e}function $w(t){const e=new qg({id:Ip(t.getID()),message:t.getMessage()});return t.hasOperations()&&(e.operations=Bw(t.getOperations())),t.hasPresenceChange()&&(e.presenceChange=Lw(t.getPresenceChange())),e}function zw(t){const e=[];for(const n of t)e.push($w(n));return e}function Uw(t){const e=[];for(const n of t)e.push(new up({key:n.getStrKey(),element:rc(n.getValue())}));return e}function jw(t){const e=[];for(const n of t)e.push(new Gu({element:rc(n.getValue())}));return e}function Vw(t){const e=[];for(const n of t){const r=new cp;r.id=Fw(n.getID()),r.value=n.getValue().getContent(),r.removedAt=b(n.getRemovedAt());const i=r.attributes,s=n.getValue().getAttrs();for(const o of s){const a=new ia;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function Jw(t){const e=[];if(!t||!t.length)return e;for(const n of t)e.push(new fp({content:nc(n)}));return e}function Kw(t){const e={};for(const n of t)e[n.getKey()]=new ia({value:n.getValue(),updatedAt:b(n.getUpdatedAt()),isRemoved:n.isRemoved()});return e}function nc(t){if(!t)return[];const e=[];return oa(t,(n,r)=>{const i=new Yu({id:Li(n.id),type:n.type,removedAt:b(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=Li(n.insPrevID)),n.insNextID&&(i.insNextId=Li(n.insNextID)),n.attrs&&(i.attributes=Kw(n.attrs)),e.push(i)}),e}function Ww(t){const e=new mt;return e.body.case="jsonObject",e.body.value=new rp({nodes:Uw(t.getRHT()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Cp(t){const e=new mt;return e.body.case="jsonArray",e.body.value=new ip({nodes:jw(t.getElements()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function qw(t){const e=new mt;return e.body.case="primitive",e.body.value=new sp({type:Ep(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Hw(t){const e=new mt;return e.body.case="text",e.body.value=new op({nodes:Vw(t.getRGATreeSplit()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Gw(t){const e=new mt;return e.body.case="counter",e.body.value=new ap({type:Np(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Pp(t){const e=new mt;return e.body.case="tree",e.body.value=new lp({nodes:nc(t.getRoot()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function rc(t){if(t instanceof He)return Ww(t);if(t instanceof tt)return Cp(t);if(t instanceof te)return qw(t);if(t instanceof gt)return Hw(t);if(t instanceof nt)return Gw(t);if(t instanceof pt)return Pp(t);throw new T(w.ErrUnimplemented,"unimplemented element")}function Yw(t){return new gn({documentKey:t.getDocumentKey(),checkpoint:Mw(t.getCheckpoint()),isRemoved:t.getIsRemoved(),changes:zw(t.getChanges()),snapshot:t.getSnapshot(),minSyncedTicket:b(t.getMinSyncedTicket())})}function td(t){const e=t.findDetails(gw);for(const n of e)if(n.metadata.code)return n.metadata.code;return""}function Op(t){let e;return t.serverSeq&&(e=B.fromString(t.serverSeq,!0)),An.of(t.clientSeq,B.fromString(t.lamport,!0),ac(t.actorId),e)}function L(t){if(t)return qe.of(B.fromString(t.lamport,!0),t.delimiter,ac(t.actorId))}function ic(t){const e={};return Object.entries(t.data).forEach(([n,r])=>{e[n]=JSON.parse(r)}),e}function Qw(t){const e=t.type;if(e===ns.PUT){const n=ic(t.presence);return{type:zn.Put,presence:n}}if(e===ns.CLEAR)return{type:zn.Clear};throw new T(w.ErrInvalidType,`unsupported type: ${e}`)}function Xw(t){const e=new Map;return Object.entries(t).forEach(([n,r])=>{e.set(n,ic(r))}),e}function Dp(t){switch(t){case z.NULL:return me.Null;case z.BOOLEAN:return me.Boolean;case z.INTEGER:return me.Integer;case z.LONG:return me.Long;case z.DOUBLE:return me.Double;case z.STRING:return me.String;case z.BYTES:return me.Bytes;case z.DATE:return me.Date}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Bo(t){switch(t){case z.INTEGER_CNT:return Ht.IntegerCnt;case z.LONG_CNT:return Ht.LongCnt}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Wa(t){switch(t.type){case z.JSON_OBJECT:return t.value?Bp(t.value):He.create(L(t.createdAt));case z.JSON_ARRAY:return t.value?c1(t.value):tt.create(L(t.createdAt));case z.TEXT:return gt.create(ti.create(),L(t.createdAt));case z.TREE:return d1(t.value);case z.NULL:case z.BOOLEAN:case z.INTEGER:case z.LONG:case z.DOUBLE:case z.STRING:case z.BYTES:case z.DATE:return te.of(te.valueFromBytes(Dp(t.type),t.value),L(t.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return nt.create(Bo(t.type),nt.valueFromBytes(Bo(t.type),t.value),L(t.createdAt))}}function Us(t){return xt.of(qt.of(L(t.createdAt),t.offset),t.relativeOffset)}function Rp(t){return qt.of(L(t.createdAt),t.offset)}function Zw(t){const e=os.create(t.value);Object.entries(t.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,L(i.updatedAt))});const n=Mn.create(Rp(t.id),e);return n.remove(L(t.removedAt)),n}function vr(t){return At.of(Mi(t.parentId),Mi(t.leftSiblingId))}function Mi(t){return Ie.of(L(t.createdAt),t.offset)}function e1(t){if(!t.length)return;const e=[];return t.forEach(n=>{const r=sc(n.content);e.push(r)}),e}function sc(t){if(t.length===0)return;const e=[];for(const i of t)e.push(n1(i));const n=e[e.length-1],r=new Map;r.set(t[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(t[i].depth-1).prepend(e[i]),r.set(t[i].depth,e[i]);return n.updateDescendantsSize(),pt.create(n,Nt).getRoot()}function t1(t){const e=dn.create();for(const[n,r]of Object.entries(t))e.setInternal(n,r.value,L(r.updatedAt),r.isRemoved);return e}function n1(t){const e=Mi(t.id),n=Ze.create(e,t.type),r=Object.entries(t.attributes);return n.isText?n.value=t.value:r.length&&(n.attrs=t1(t.attributes)),t.insPrevId&&(n.insPrevID=Mi(t.insPrevId)),t.insNextId&&(n.insNextID=Mi(t.insNextId)),n.removedAt=L(t.removedAt),n}function _p(t){if(t.body.case==="set"){const e=t.body.value;return dr.create(e.key,Wa(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(t.body.case==="add"){const e=t.body.value;return ps.create(L(e.parentCreatedAt),L(e.prevCreatedAt),Wa(e.value),L(e.executedAt))}else if(t.body.case==="move"){const e=t.body.value;return Nn.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="remove"){const e=t.body.value;return Un.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="edit"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ms.create(L(e.parentCreatedAt),Us(e.from),Us(e.to),n,e.content,r,L(e.executedAt))}else if(t.body.case==="style"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ys.create(L(e.parentCreatedAt),Us(e.from),Us(e.to),n,r,L(e.executedAt))}else{if(t.body.case==="select")return;if(t.body.case==="increase"){const e=t.body.value;return ni.create(L(e.parentCreatedAt),Wa(e.value),L(e.executedAt))}else if(t.body.case==="treeEdit"){const e=t.body.value,n=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{n.set(r,L(i))}),vs.create(L(e.parentCreatedAt),vr(e.from),vr(e.to),e1(e.contents),e.splitLevel,n,L(e.executedAt))}else if(t.body.case==="treeStyle"){const e=t.body.value,n=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,L(o))}),(r==null?void 0:r.length)>0?an.createTreeRemoveStyleOperation(L(e.parentCreatedAt),vr(e.from),vr(e.to),i,r,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{n.set(s,o)}),an.create(L(e.parentCreatedAt),vr(e.from),vr(e.to),i,n,L(e.executedAt)))}else throw new T(w.ErrUnimplemented,"unimplemented operation")}}function r1(t){const e=[];for(const n of t){const r=_p(n);r&&e.push(r)}return e}function bp(t){const e=[];for(const n of t)e.push(ei.create({id:Op(n.id),operations:r1(n.operations),presenceChange:n.presenceChange?Qw(n.presenceChange):void 0,message:n.message}));return e}function i1(t){return jr.of(B.fromString(t.serverSeq,!0),t.clientSeq)}function s1(t){return aa.create(t.documentKey,i1(t.checkpoint),t.isRemoved,bp(t.changes),t.snapshot,L(t.minSyncedTicket))}function Lp(t){const e=new rs;for(const r of t.nodes){const i=oc(r.element);e.set(r.key,i,i.getPositionedAt())}const n=new He(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function Mp(t){const e=new ss;for(const r of t.nodes)e.insert(oc(r.element));const n=new tt(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function o1(t){const e=te.of(te.valueFromBytes(Dp(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function a1(t){const e=new ti;let n=e.getHead();for(const i of t.nodes){const s=e.insertAfter(n,Zw(i));i.insPrevId&&s.setInsPrev(e.findNode(Rp(i.insPrevId))),n=s}const r=new gt(e,L(t.createdAt));return r.setMovedAt(L(t.movedAt)),r.setRemovedAt(L(t.removedAt)),r}function l1(t){const e=nt.create(Bo(t.type),nt.valueFromBytes(Bo(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function Fp(t){const e=sc(t.nodes);return pt.create(e,L(t.createdAt))}function oc(t){if(t.body.case==="jsonObject")return Lp(t.body.value);if(t.body.case==="jsonArray")return Mp(t.body.value);if(t.body.case==="primitive")return o1(t.body.value);if(t.body.case==="text")return a1(t.body.value);if(t.body.case==="counter")return l1(t.body.value);if(t.body.case==="tree")return Fp(t.body.value);throw new T(w.ErrUnimplemented,"unimplemented element")}function u1(t){if(!t)return{root:He.create(Nt),presences:new Map};const e=J0.fromBinary(t);return{root:oc(e.root),presences:Xw(e.presences)}}function Bp(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Lp(e.body.value)}function $p(t){return rc(t).toBinary()}function c1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Mp(e.body.value)}function f1(t){return Cp(t).toBinary()}function d1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Fp(e.body.value)}function h1(t){return Pp(t).toBinary()}function zp(t){return t?Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ac(t){return zp(t)}function Up(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lc(t){return Up(t)}function g1(t){const e=ra.fromBinary(t);return Op(e)}function p1(t){const e=Hu.fromBinary(t);return _p(e)}const ye={fromPresence:ic,toChangePack:Yw,fromChangePack:s1,fromChanges:bp,toTreeNodes:nc,fromTreeNodes:sc,objectToBytes:$p,bytesToObject:Bp,bytesToSnapshot:u1,bytesToHex:zp,hexToBytes:Up,toHexString:ac,toUint8Array:lc,toOperation:xp,toChangeID:Ip,PbChangeID:ra,bytesToChangeID:g1,bytesToOperation:p1};var be=(t=>(t[t.Trivial=0]="Trivial",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.Fatal=5]="Fatal",t))(be||{});let Yn=3;function jp(t){Yn=t}const F={trivial:(...t)=>{Yn>0||typeof console<"u"&&console.log("YORKIE T:",...t)},debug:(...t)=>{Yn>1||typeof console<"u"&&console.log("YORKIE D:",...t)},info:(...t)=>{Yn>2||typeof console<"u"&&console.log("YORKIE I:",...t)},warn:(...t)=>{Yn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:(...t)=>{Yn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:(...t)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...t):console.log("YORKIE F:",...t))},isEnabled:t=>Yn<=t};function Vp(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class m1{constructor(e,n,r,i,s){m(this,"reconnectStreamDelay");m(this,"doc");m(this,"docID");m(this,"syncMode");m(this,"remoteChangeEventReceived");m(this,"watchStream");m(this,"watchLoopTimerID");m(this,"watchAbortController");m(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===lo.RealtimeSyncOff?!1:this.syncMode===lo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==lo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const qa=()=>{};class y1{constructor(e){m(this,"finalized",!1);m(this,"observers",[]);m(this,"finalError");try{e(this)}catch(n){this.error(n)}}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(!e)throw new T(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=qa),i.error===void 0&&(i.error=qa),i.complete===void 0&&(i.complete=qa);const s=Vp(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){F.warn(a)}return o}unsubscribeOne(e){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let n=0;ne}}class _r{constructor(e,n,r,i){m(this,"id");m(this,"delimiter");m(this,"message");m(this,"root");m(this,"operations");m(this,"presenceChange");m(this,"previousPresence");m(this,"reversePresenceKeys");this.id=e,this.delimiter=Zu,this.root=n,this.operations=[],this.previousPresence=wt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,n,r,i){return new _r(e,n,r,i)}push(e){this.operations.push(e)}registerElement(e,n){this.root.registerElement(e,n)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ei.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,n){for(const r of Object.keys(e))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const n of this.reversePresenceKeys)e[n]=this.previousPresence[n];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class as{constructor(e){m(this,"rootObject");m(this,"elementPairMapByCreatedAt");m(this,"gcElementSetByCreatedAt");m(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof gt||n instanceof pt)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new as(He.create(Nt))}findByCreatedAt(e){const n=this.elementPairMapByCreatedAt.get(e.toIDString());if(n)return n.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let n=this.elementPairMapByCreatedAt.get(e.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),s=n.parent.subPathOf(i);if(s===void 0)throw new T(w.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,n){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:n,element:e}),e instanceof Ln&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let n=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),n++};return r(e),e instanceof Ln&&e.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const n of this.gcElementSetByCreatedAt){e.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof Ln&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new as(this.rootObject.deepcopy())}garbageCollect(e){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Jp(t,e){const n=new ls(t);return new Proxy(e,n.getHandlers())}class ls{constructor(e){m(this,"context");m(this,"handlers");this.context=e,this.handlers={set:(n,r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]=${JSON.stringify(i)}`),ls.setInternal(e,n,r,i),!0),get:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Qn(e,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),ls.deleteInternal(e,n,r),!0)}}static setInternal(e,n,r,i){if(r.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=$o(e,i,s),a=n.set(r,o,s);e.registerElement(o,n),a&&e.registerRemovedElement(a),e.push(dr.create(r,o.deepcopy(),n.getCreatedAt(),s))}static buildObjectMembers(e,n){const r={};for(const[i,s]of Object.entries(n)){if(i.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=$o(e,s,o);r[i]=a}return r}static deleteInternal(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByKey(r,i);s&&(e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function w1(t,e){const n=new ie(t,e);return new Proxy(e,n.getHandlers())}function S1(t){return typeof t=="string"||t instanceof String?!isNaN(t):!1}function T1(t){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(t)}class ie{constructor(e,n){m(this,"context");m(this,"handlers");m(this,"array");this.context=e,this.array=n,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return yn(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return yn(e,a)}:i==="getLast"?()=>yn(e,r.getLast()):i==="deleteByID"?o=>{const a=ie.deleteInternalByID(e,r,o);return yn(e,a)}:i==="insertAfter"?(o,a)=>{const l=ie.insertAfterInternal(e,r,o,a);return yn(e,l)}:i==="insertBefore"?(o,a)=>{const l=ie.insertBeforeInternal(e,r,o,a);return yn(e,l)}:i==="moveBefore"?(o,a)=>{ie.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ie.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ie.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ie.moveLastInternal(e,r,o)}:S1(i)?Qn(e,r.get(Number(i))):i==="push"?o=>ie.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ie.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ie.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ie.includes(e,r,o,a):i==="indexOf"?(o,a)=>ie.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ie.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ie.toTestString(r):typeof i=="string"&&T1(i)?(...o)=>{const a=Array.from(r).map(l=>Qn(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`array[${i}]`),ie.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,n){for(const r of n)yield yn(e,r)}static buildArrayElements(e,n){const r=[];for(const i of n){const s=e.issueTimeTicket(),o=$o(e,i,s);r.push(o)}return r}static pushInternal(e,n,r){return ie.insertAfterInternal(e,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(e,n,r,i){const s=e.issueTimeTicket(),o=n.getPrevCreatedAt(r);n.moveAfter(o,i,s),e.push(Nn.create(n.getCreatedAt(),o,i,s))}static moveAfterInternal(e,n,r,i){const s=e.issueTimeTicket();n.moveAfter(r,i,s),e.push(Nn.create(n.getCreatedAt(),r,i,s))}static moveFrontInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getHead();n.moveAfter(s.getCreatedAt(),r,i),e.push(Nn.create(n.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getLastCreatedAt();n.moveAfter(s,r,i),e.push(Nn.create(n.getCreatedAt(),s,r,i))}static insertAfterInternal(e,n,r,i){const s=e.issueTimeTicket(),o=$o(e,i,s);return n.insertAfter(r,o),e.registerElement(o,n),e.push(ps.create(n.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,n,r,i){return ie.insertAfterInternal(e,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByIndex(r,i);if(s)return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,n,r){const i=e.issueTimeTicket(),s=n.delete(r,i);return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,n,r,i,...s){const o=n.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),u=[];for(let c=a;c=s)return!1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).includes(r,o);for(let l=o;l=s)return-1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=n.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class la{constructor(e,n){m(this,"context");m(this,"text");this.context=e,this.text=n}initialize(e,n){this.context=e,this.text=n}getID(){return this.text.getID()}edit(e,n,r,i){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${n}->${s[1].toTestString()} c:${r}`);const o=i?Zr(i):void 0,a=this.context.issueTimeTicket(),[l,,u,c]=this.text.edit(s,r,a,o);for(const f of u)this.context.registerGCPair(f);return this.context.push(new ms(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,n){return this.edit(e,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,n,r){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=Zr(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const u of l)this.context.registerGCPair(u);return this.context.push(new ys(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(e[0],e[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([xt.fromStruct(e[0]),xt.fromStruct(e[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,n){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,n)}}class ua{constructor(e,n){m(this,"valueType");m(this,"value");m(this,"context");m(this,"counter");this.valueType=e,this.value=n}initialize(e,n){this.valueType=n.getValueType(),this.context=e,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=te.of(e,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ni.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function uc(t,e,n){const{type:r}=t,i=n.issueTimeTicket();if(r===on){Kp(t);const{value:s}=t,o=Ze.create(Ie.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=t,{attributes:o}=t;let a;if(typeof o=="object"&&!yp(o)){const u=Zr(o);a=new dn;for(const[c,f]of Object.entries(u))a.set(c,f,i)}const l=Ze.create(Ie.of(i,0),r,void 0,a);e.append(l);for(const u of s)uc(u,l,n)}}function k1(t,e){const{type:n}=e,r=t.issueTimeTicket();let i;if(e.type===on){const{value:s}=e;i=Ze.create(Ie.of(r,0),n,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!yp(o)){const l=Zr(o);a=new dn;for(const[u,c]of Object.entries(l))a.set(u,c,r)}i=Ze.create(Ie.of(t.issueTimeTicket(),0),n,void 0,a);for(const l of s)uc(l,i,t)}return i}function Kp(t){if(!t.value.length)throw new T(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function nd(t){if(!t.length)return!0;if(t[0].type===on)for(const n of t){const{type:r}=n;if(r!==on)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together");Kp(n)}else for(const n of t){const{type:r}=n;if(r===on)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ca{constructor(e){m(this,"initialRoot");m(this,"context");m(this,"tree");this.initialRoot=e}initialize(e,n){this.context=e,this.tree=n}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ze.create(Ie.of(e.issueTimeTicket(),0),Aw);const n=Ze.create(Ie.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)uc(r,n,e);return n}getSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,n){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=n?Zr(n):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(an.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),a=r?Zr(r):void 0,[l,u]=this.tree.style([i,s],a,o);for(const c of u)this.context.registerGCPair(c);this.context.push(an.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const u of l)this.context.registerGCPair(u);this.context.push(an.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,n,r,i=0){var u;if(r.length!==0&&r[0]&&(nd(r),r[0].type!==on))for(const c of r){const{children:f=[]}=c;nd(f)}const s=this.context.getLastTimeTicket();let o=new Array;if(((u=r[0])==null?void 0:u.type)===on){let c="";for(const f of r){const{value:g}=f;c+=g}o.push(Ze.create(Ie.of(this.context.issueTimeTicket(),0),on,c))}else o=r.map(c=>c&&k1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,n],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(vs.create(this.tree.getCreatedAt(),e,n,o.length?o:void 0,i,l,s)),!0}editByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r,i)}edit(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[At.fromStruct(e[0]),At.fromStruct(e[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[At.fromStruct(e[0]),At.fromStruct(e[1])];return this.tree.posRangeToPathRange(n)}}function rd(t,e){return Jp(t,e)}function yn(t,e){if(e){if(e instanceof te)return e;if(e instanceof He)return Jp(t,e);if(e instanceof tt)return w1(t,e);if(e instanceof gt)return new la(t,e);if(e instanceof nt){const n=new ua(Ht.IntegerCnt,0);return n.initialize(t,e),n}else if(e instanceof pt){const n=new ca;return n.initialize(t,e),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Qn(t,e){const n=yn(t,e);return n instanceof te?n.getValue():n}function $o(t,e,n){let r;if(te.isSupport(e))r=te.of(e,n);else if(Array.isArray(e))r=tt.create(n,ie.buildArrayElements(t,e));else if(typeof e=="object")e instanceof la?(r=gt.create(ti.create(),n),e.initialize(t,r)):e instanceof ua?(r=nt.create(e.getValueType(),e.getValue(),n),e.initialize(t,r)):e instanceof ca?(r=pt.create(e.buildRoot(t),n),e.initialize(t,r)):r=He.create(n,ls.buildObjectMembers(t,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const id=50;class A1{constructor(){m(this,"undoStack",[]);m(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=id&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=id&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const I1="yorkie-devtools-panel",E1="yorkie-devtools-sdk";let wr="disconnected";const sd=new Map,ao=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ao);function js(t,e){(e!=null&&e.force||wr!=="disconnected")&&window.postMessage({source:E1,...t},"*")}function N1(t){if(!t.isEnableDevtools()||typeof window>"u"||sd.has(t.getKey()))return;ao.set(t.getKey(),[]);const e=t.subscribe("all",n=>{n.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(ao.get(t.getKey()).push(n),wr==="synced"&&js({msg:"doc::sync::partial",docKey:t.getKey(),event:n}))});sd.set(t.getKey(),[e]),js({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==I1)return;switch(n.data.msg){case"devtools::connect":if(wr!=="disconnected")break;wr="connected",js({msg:"doc::available",docKey:t.getKey()}),F.info(`[YD] Devtools connected. Doc: ${t.getKey()}`);break;case"devtools::disconnect":wr="disconnected",F.info(`[YD] Devtools disconnected. Doc: ${t.getKey()}`);break;case"devtools::subscribe":wr="synced",js({msg:"doc::sync::full",docKey:t.getKey(),events:ao.get(t.getKey())}),F.info(`[YD] Devtools subscribed. Doc: ${t.getKey()}`);break}})}var vn=(t=>(t.Detached="detached",t.Attached="attached",t.Removed="removed",t))(vn||{}),$e=(t=>(t.StatusChanged="status-changed",t.ConnectionChanged="connection-changed",t.SyncStatusChanged="sync-status-changed",t.Snapshot="snapshot",t.LocalChange="local-change",t.RemoteChange="remote-change",t.Initialized="initialized",t.Watched="watched",t.Unwatched="unwatched",t.PresenceChanged="presence-changed",t.Broadcast="broadcast",t.LocalBroadcast="local-broadcast",t))($e||{}),Yl=(t=>(t.Connected="connected",t.Disconnected="disconnected",t))(Yl||{}),Ql=(t=>(t.Synced="synced",t.SyncFailed="sync-failed",t))(Ql||{});class Wp{constructor(e,n){m(this,"key");m(this,"status");m(this,"opts");m(this,"changeID");m(this,"checkpoint");m(this,"localChanges");m(this,"root");m(this,"clone");m(this,"eventStream");m(this,"eventStreamObserver");m(this,"onlineClients");m(this,"presences");m(this,"history");m(this,"internalHistory");m(this,"isUpdating");this.opts=n||{},this.key=e,this.status="detached",this.root=as.create(),this.changeID=Dw,this.checkpoint=Rw,this.localChanges=[],this.eventStream=v1(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new A1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},N1(this)}update(e,n){if(this.getStatus()==="removed")throw new T(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const s=rd(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Ja(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){F.isEnabled(be.Trivial)&&F.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,G.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const u=[];o.length>0&&u.push({type:"local-change",source:G.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&u.push({type:"presence-changed",source:G.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(u),F.isEnabled(be.Trivial)&&F.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,n,r,i){if(typeof e=="string"){if(typeof n!="function")throw new T(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},r,i)}if(e==="my-presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},r,i)}if(e==="others"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},r,i)}if(e==="connection"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="connection-changed"&&a(u)},r,i)}if(e==="status"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="status-changed"&&a(u)},r,i)}if(e==="sync"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="sync-status-changed"&&a(u)},r,i)}if(e==="local-broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="local-broadcast"&&a(u)},r)}if(e==="broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="broadcast"&&a(u)},r)}if(e==="all"){const a=n;return this.eventStream.subscribe(a,r,i)}const s=e,o=n;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const u=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&u.push(c);u.length&&o({...l,value:{...l.value,operations:u}})}},r,i)}if(typeof e=="function"){const s=e,o=n,a=r;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||s(u)},o,a)}throw new T(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,n){if(n===e)return!0;const r=e.split(".");return n.split(".").every((s,o)=>s===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),G.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,G.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),F.isEnabled(be.Trivial)&&F.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(e.length);return aa.create(this.key,n,!1,e)}setActor(e){for(const n of this.localChanges)n.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return rd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,n){const{root:r,presences:i}=ye.bytesToSnapshot(n);this.root=new as(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:G.Remote,value:{snapshot:this.isEnableDevtools()?ye.bytesToHex(n):void 0,serverSeq:e.toString()}}])}applyChanges(e,n){F.isEnabled(be.Debug)&&F.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),F.isEnabled(be.Trivial)&&F.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class gs{constructor(e){m(this,"createdAt");m(this,"movedAt");m(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class Ln extends gs{constructor(e){super(e)}}class ec{constructor(e,n){m(this,"strKey");m(this,"value");this.strKey=e,this.value=n}static of(e,n){return new ec(e,n)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class rs{constructor(){m(this,"nodeMapByKey");m(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new rs}set(e,n,r){let i;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(r)&&(i=s.getValue());const o=ec.of(e,n);return this.nodeMapByCreatedAt.set(n.getCreatedAt().toIDString(),o),(s==null||r.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),n.setMovedAt(r)),i}delete(e,n){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(w.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(n),r.getValue()}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return n.getStrKey()}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(n.getStrKey());n===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(n.getValue().getCreatedAt().toIDString())}deleteByKey(e,n){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(n))return r.getValue()}has(e){const n=this.nodeMapByKey.get(e);return n==null?!1:!n.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const n=this.nodeMapByKey.get(e);if(!(!n||n.isRemoved()))return n}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class He extends Ln{constructor(n,r){super(n);m(this,"memberNodes");this.memberNodes=r}static create(n,r){if(!r)return new He(n,rs.create());const i=rs.create();for(const[s,o]of Object.entries(r))i.set(s,o.deepcopy(),o.getCreatedAt());return new He(n,i)}subPathOf(n){return this.memberNodes.subPathOf(n)}purge(n){this.memberNodes.purge(n)}set(n,r,i){return this.memberNodes.set(n,r,i)}delete(n,r){return this.memberNodes.delete(n,r)}deleteByKey(n,r){return this.memberNodes.deleteByKey(n,r)}get(n){const r=this.memberNodes.get(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.memberNodes.getByID(n);return r==null?void 0:r.getValue()}has(n){return this.memberNodes.has(n)}toJSON(){const n=[];for(const[r,i]of this)n.push(`"${Jt(r)}":${i.toJSON()}`);return`{${n.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(const[r,i]of this){const{createdAt:s,value:o,type:a}=i.toJSForTest();n[r]={key:r,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:n,type:"YORKIE_OBJECT"}}getKeys(){const n=Array();for(const[r]of this)n.push(r);return n}toSortedJSON(){var i;const n=Array();for(const[s]of this)n.push(s);const r=[];for(const s of n.sort()){const o=(i=this.memberNodes.get(s))==null?void 0:i.getValue();r.push(`"${Jt(s)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const n=He.create(this.getCreatedAt());for(const r of this.memberNodes)n.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return n.remove(this.getRemovedAt()),n}getDescendants(n){for(const r of this.memberNodes){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}*[Symbol.iterator](){const n=new Set;for(const r of this.memberNodes)n.has(r.getStrKey())||(n.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var G=(t=>(t.Local="local",t.Remote="remote",t.UndoRedo="undoredo",t))(G||{});class Pt{constructor(e,n){m(this,"parentCreatedAt");m(this,"executedAt");this.parentCreatedAt=e,this.executedAt=n}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(w.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class vp{constructor(e){m(this,"value");m(this,"left");m(this,"right");m(this,"parent");m(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class is{constructor(e){m(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let n=this.root;for(;;)if(n.hasLeft()&&e<=n.getLeftWeight())n=n.getLeft();else if(n.hasRight()&&n.getLeftWeight()+n.getLength()n.getLength())throw new T(w.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${n.getLength()}`);return this.splayNode(n),[n,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,n){return e?(this.splayNode(e),this.root=n,n.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(n),n.setLeft(e),e.setParent(n),e.setRight(),this.updateWeight(e),this.updateWeight(n),n):(this.root=n,n)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const n=new is(e.getLeft());n.root&&n.root.setParent();const r=new is(e.getRight());if(r.root&&r.root.setParent(),n.root){const i=n.getRightmost();n.splayNode(i),n.root.setRight(r.root),r.root&&r.root.setParent(n.root),this.root=n.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,n){if(!n){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(n),n.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const n=[];this.traversePostorder(e.getRight(),n);for(const r of n)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(n=>`[${n.getWeight()},${n.getLength()}]${n.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const n of e)if(n.getWeight()!=n.getLength()+n.getLeftWeight()+n.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,n){e&&(this.traverseInorder(e.getLeft(),n),n.push(e),this.traverseInorder(e.getRight(),n))}traversePostorder(e,n){e&&(this.traversePostorder(e.getLeft(),n),this.traversePostorder(e.getRight(),n),n.push(e))}rotateLeft(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setRight(e.getLeft()),n.hasRight()&&n.getRight().setParent(n),e.setLeft(n),e.getLeft().setParent(e),this.updateWeight(n),this.updateWeight(e)}rotateRight(e){const n=e.getParent();n.hasParent()?n===n.getParent().getLeft()?n.getParent().setLeft(e):n.getParent().setRight(e):this.root=e,e.setParent(n.getParent()),n.setLeft(e.getRight()),n.hasLeft()&&n.getLeft().setParent(n),e.setRight(n),e.getRight().setParent(e),this.updateWeight(n),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var me=(t=>(t[t.Null=0]="Null",t[t.Boolean=1]="Boolean",t[t.Integer=2]="Integer",t[t.Long=3]="Long",t[t.Double=4]="Double",t[t.String=5]="String",t[t.Bytes=6]="Bytes",t[t.Date=7]="Date",t))(me||{});class te extends gs{constructor(n,r){super(r);m(this,"valueType");m(this,"value");this.valueType=te.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new te(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return B.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(B.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Jt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=te.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof B)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return te.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=B.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Fo extends vp{constructor(n){super(n);m(this,"prev");m(this,"next");this.value=n}static createAfter(n,r){const i=new Fo(r),s=n.next;return n.next=i,i.prev=n,i.next=s,s&&(s.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class ss{constructor(){m(this,"dummyHead");m(this,"last");m(this,"nodeMapByIndex");m(this,"nodeMapByCreatedAt");const e=te.of(0,Nt);e.setRemovedAt(Nt),this.dummyHead=new Fo(e),this.last=this.dummyHead,this.nodeMapByIndex=new is,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new ss}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,n){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=Fo.createAfter(i,n);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,n,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new T(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(n.toIDString());if(!s)throw new T(w.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new T(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(e){if(e>=this.length)return;const[n,r]=this.nodeMapByIndex.find(e);let i=n;if(e===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let n=this.nodeMapByCreatedAt.get(e.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(e,n){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,n){const r=this.getByIndex(e);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Ln{constructor(n,r){super(n);m(this,"elements");this.elements=r}static create(n,r){if(!r)return new tt(n,ss.create());const i=ss.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof Ln&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...h,value:h.value?{attributes:Ur(h.value.getAttributes()),content:h.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[u,g,c,[l,l]]}setStyle(n,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),l=[],u=this.rgaTreeSplit.findBetween(a,o),c=new Map,f=[];for(const h of u){const v=h.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(v)?s.get(v):Nt:bi;if(h.canStyle(i,I)){const O=c.get(v),p=h.getCreatedAt();(!O||p.after(O))&&c.set(v,p),f.push(h)}}const g=[];for(const h of f){if(h.isRemoved())continue;const[v,I]=this.rgaTreeSplit.findIndexesFromRange(h.createPosRange());l.push({type:"style",actor:i.getActorID(),from:v,to:I,value:{attributes:Ur(r)}});for(const[O,p]of Object.entries(r)){const[d]=h.getValue().setAttr(O,p,i);d!==void 0&&g.push({parent:h.getValue(),child:d})}}return[c,g,l]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Ur(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class ms extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"content");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(n,r,i,s,o,a,l){return new ms(n,r,i,s,o,a,l)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u})=>({type:"edit",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${n}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ys extends Pt{constructor(n,r,i,s,o,a){super(n,a);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(n,r,i,s,o,a){return new ys(n,r,i,s,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof gt))throw new T(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)n.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:u})=>({type:"style",from:a,to:l,value:u,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const kw=2,Aw="root",on="text";function yi(t,e){let n=0;const r=t.children;for(let i=0;i0)throw new T(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const n=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*n,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===on}get paddedSize(){return this.size+(this.isText?0:kw)}isAncestorOf(e){return Ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e+1];if(n)return n}get prevSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e-1];if(n)return n}splitText(e,n){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+n);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const n of e)n.parent=this,n.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const n of e)n.parent=this}insertBefore(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,n),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new T(w.ErrInvalidArgument,"child not found");this._children.splice(n,1),e.parent=void 0}splitElement(e,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new T(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,n){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");this._children.splice(n,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const n=this._children.indexOf(e);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(w.ErrRefused,"Text node cannot have children");let n=e;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function Ew(t,e){if(t===e)return!1;for(;e.parent;){if(e.parent===t)return!0;e=e.parent}return!1}var fe=(t=>(t.Start="Start",t.End="End",t.Text="Text",t))(fe||{});function wp(t,e,n,r){if(e>n)throw new T(w.ErrInvalidArgument,`from is greater than to: ${e} > ${n}`);if(e>t.size)throw new T(w.ErrInvalidArgument,`from is out of range: ${e} > ${t.size}`);if(n>t.size)throw new T(w.ErrInvalidArgument,`to is out of range: ${n} > ${t.size}`);if(e===n)return;let i=0;for(const s of t.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],u),wp(s,Math.max(0,o),Math.min(a,s.size),r),u&&r([s,"End"],u)}i+=s.paddedSize}}function Sp(t,e,n=0){for(const r of t.children)Sp(r,e,n+1);e(t,n)}function oa(t,e,n=0){for(const r of t._children)oa(r,e,n+1);e(t,n)}function Hl(t,e,n=!0){if(e>t.size)throw new T(w.ErrInvalidArgument,`index is out of range: ${e} > ${t.size}`);if(t.isText)return{node:t,offset:e};let r=0,i=0;for(const s of t.children){if(n&&s.isText&&s.size>=e-i)return Hl(s,e-i,n);if(e===i)return{node:t,offset:r};if(!n&&s.paddedSize===e-i)return{node:t,offset:r+1};if(s.paddedSize>e-i)return Hl(s,e-i-1,n);i+=s.paddedSize,r+=1}return{node:t,offset:r}}function Tp(t){return t.isText||t.children.length===0?t:Tp(t.children[0])}function Nw(t,e){if(t.sizet===e?0:t0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,s=n;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,n){for(;n;){const r=this.comparator(e,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(e,n,r){if(!r)return this.counter+=1,new Pw(e,n,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,n,r.left):i>0?r.right=this.putInternal(e,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,n){if(this.comparator(n,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,n);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(n,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(n,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,n)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const n=e.right;return e.right=n.left,n.left=e,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(e){const n=e.left;return e.left=n.right,n.right=e,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class At{constructor(e,n){m(this,"parentID");m(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=n}static of(e,n){return new At(e,n)}static fromTreePos(e){const{offset:n}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],At.of(r.id,Ie.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(e){return At.of(Ie.of(qe.fromStruct(e.parentID.createdAt),e.parentID.offset),Ie.of(qe.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const n=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(n);let s=e.findFloorNode(r);if(!i||!s)throw new T(w.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ie{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Ie(e,n)}static fromStruct(e){return Ie.of(qe.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=n,s}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new T(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new T(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Ze(Ie.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Ze(Ie.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=n.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,n.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new dn);const i=new Array;for(const[s,o]of Object.entries(n))i.push(this.attrs.set(s,o,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function Gl(t){var n;if(t.isText){const r=t;return{type:r.type,value:r.value}}const e={type:t.type,children:t.children.map(Gl)};return t.attrs&&(e.attributes=Ur((n=t.attrs)==null?void 0:n.toObject())),e}function tc(t){if(t.isText)return t.value;let e="";return t.attrs&&t.attrs.size()&&(e=" "+Array.from(t.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Jt(n.getValue())}"`}).join(" ")),`<${t.type}${e}>${t.children.map(n=>tc(n)).join("")}`}function Ap(t){if(t.isText){const e=t;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:t.type,children:t.children.map(Ap),size:t.size,isRemoved:t.isRemoved}}class pt extends gs{constructor(n,r){super(r);m(this,"indexTree");m(this,"nodeMapByID");this.indexTree=new xw(n),this.nodeMapByID=new kp(Ie.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new pt(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,s]=n.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,n.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const u=l.allChildren,c=a?0:u.indexOf(o)+1;for(let f=c;f{const I=v.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Nt:bi;if(v.canStyle(i,O)&&r){const p=g.get(I),d=v.getCreatedAt();(!p||d.after(p))&&g.set(I,d);const y=v.setAttrs(r,i),k=y.reduce((P,[,_])=>(_&&(P[_.getKey()]=f[_.getKey()]),P),{}),N=v.parent,C=v.prevSibling||v.parent;Object.keys(k).length>0&&c.push({type:"style",from:this.toIndex(N,C),to:this.toIndex(v,v),fromPath:this.toPath(N,C),toPath:this.toPath(v,v),actor:i.getActorID(),value:k});for(const[P]of y)P&&h.push({parent:v,child:P})}}),[g,h,c]}removeStyle(n,r,i,s){const[o,a]=this.findNodesAndSplitText(n[0],i),[l,u]=this.findNodesAndSplitText(n[1],i),c=[],f=new Map,g=[];return this.traverseInPosRange(o,a,l,u,([h])=>{const v=h.getCreatedAt().getActorID(),I=s?s.has(v)?s.get(v):Nt:bi;if(h.canStyle(i,I)&&r){const O=f.get(v),p=h.getCreatedAt();(!O||p.after(O))&&f.set(v,p),h.attrs||(h.attrs=new dn);for(const k of r){const N=h.attrs.remove(k,i);for(const C of N)g.push({parent:h,child:C})}const d=h.parent,y=h.prevSibling||h.parent;c.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(d,y),to:this.toIndex(h,h),fromPath:this.toPath(d,y),toPath:this.toPath(h,h),value:r})}}),[f,g,c]}edit(n,r,i,s,o,a){const[l,u]=this.findNodesAndSplitText(n[0],s),[c,f]=this.findNodesAndSplitText(n[1],s),g=this.toIndex(l,u),h=this.toPath(l,u),v=[],I=[],O=[],p=new Map;this.traverseInPosRange(l,u,c,f,([k,N],C)=>{if(N===fe.Start&&!C)for(const W of k.children)O.push(W);const P=k.getCreatedAt().getActorID(),_=a?a.has(P)?a.get(P):Nt:bi;if(k.canDelete(s,_)||v.includes(k.parent)){const W=p.get(P),U=k.getCreatedAt();(!W||U.after(W))&&p.set(P,U),(N===fe.Text||N===fe.Start)&&v.push(k),I.push([k,N])}});const d=this.makeDeletionChanges(I,s),y=[];for(const k of v)k.remove(s),k.isRemoved&&y.push({parent:this,child:k});for(const k of O)k.removedAt||l.append(k);if(i>0){let k=0,N=l,C=u;for(;k{l.isRemoved&&(P.remove(s),y.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),C.isRemoved||k.push(C);if(k.length){const C=k.map(P=>Gl(P));d.length&&d[d.length-1].from===g?d[d.length-1].value=C:d.push({type:"content",from:g,to:g,fromPath:h,toPath:h,actor:s.getActorID(),value:C})}}return[d,y,p]}editT(n,r,i,s,o){const a=this.findPos(n[0]),l=this.findPos(n[1]);this.edit([a,l],r,i,s,o)}move(n,r,i){throw new T(w.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var s;(s=n.parent)==null||s.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return At.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var h,v,I,O;let l,u,c;const f=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;f&&(l=this.indexTree.indexOf(f),u=this.indexTree.treePosToPath(f),c=At.fromTreePos(f).toStruct());const g={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(h=i.removedAt)==null?void 0:h.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Ur((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:u,pos:c};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=d,i[i.length-1].toPath=this.toPath(O,h)):i.push({type:"content",from:p,to:d,fromPath:this.toPath(I,f),toPath:this.toPath(O,h),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===fe.Start){const l=n.allChildren;return l.length>0?[l[0],l[0].isText?fe.Text:fe.Start]:[n,fe.End]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===s.length-1)return[i,fe.End];const a=s[o+1];return[a,a.isText?fe.Text:fe.Start]}findLeftToken([n,r]){if(r===fe.End){const l=n.allChildren;if(l.length>0){const u=l[l.length-1];return[u,u.isText?fe.Text:fe.End]}return[n,fe.Start]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===0)return[i,fe.Start];const a=s[o-1];return[a,a.isText?fe.Text:fe.End]}}class vs extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"contents");m(this,"splitLevel");m(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(n,r,i,s,o,a,l){return new vs(n,r,i,s,o,a,l)}execute(n){var l;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof pt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(u=>u.deepcopy()),this.splitLevel,i,(()=>{let u=i.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>qe.of(i.getLamport(),++u,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const u of a)n.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:u,to:c,value:f,splitLevel:g,fromPath:h,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${n}.EDIT(${r},${i},${s.map(o=>tc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class An{constructor(e,n,r,i){m(this,"clientSeq");m(this,"serverSeq");m(this,"lamport");m(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=n,this.actor=r}static of(e,n,r,i){return new An(e,n,r,i)}next(){return new An(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new An(this.clientSeq,e,this.actor):new An(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return qe.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Dw=new An(0,B.fromInt(0,!0),sa);class ei{constructor({id:e,operations:n,presenceChange:r,message:i}){m(this,"id");m(this,"operations");m(this,"presenceChange");m(this,"message");this.id=e,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:e,operations:n,presenceChange:r,message:i}){return new ei({id:e,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const n of this.operations)n.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,n,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:u}=a;i.push(...l),u&&s.unshift(u)}return this.presenceChange&&(this.presenceChange.type===zn.Put?n.set(this.id.getActorID(),wt(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ye.bytesToHex(ye.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ye.bytesToHex(ye.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:n,operations:r,presenceChange:i,message:s}=e;return ei.create({id:ye.bytesToChangeID(ye.hexToBytes(n)),operations:r==null?void 0:r.map(o=>ye.bytesToOperation(ye.hexToBytes(o))),presenceChange:i,message:s})}}class aa{constructor(e,n,r,i,s,o){m(this,"documentKey");m(this,"checkpoint");m(this,"isRemoved");m(this,"changes");m(this,"snapshot");m(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,n,r,i,s,o){return new aa(e,n,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class jr{constructor(e,n){m(this,"serverSeq");m(this,"clientSeq");this.serverSeq=e,this.clientSeq=n}static of(e,n){return new jr(e,n)}increaseClientSeq(e){return e===0?this:new jr(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const n=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return jr.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Rw=new jr(B.fromInt(0,!0),0);class qt{constructor(e,n){m(this,"createdAt");m(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new qt(e,n)}static fromStruct(e){return qt.of(qe.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new qt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _w=qt.of(Nt,0);class xt{constructor(e,n){m(this,"id");m(this,"relativeOffset");this.id=e,this.relativeOffset=n}static of(e,n){return new xt(e,n)}static fromStruct(e){const n=qt.fromStruct(e.id);return xt.of(n,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Mn extends vp{constructor(n,r,i){super(r);m(this,"id");m(this,"removedAt");m(this,"prev");m(this,"next");m(this,"insPrev");m(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new Mn(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==e.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(e){const n=this.treeByID.floorEntry(e);if(n&&!(!n.key.equals(e)&&!n.key.hasSameCreatedAt(e)))return n.value}findBetween(e,n){const r=[];let i=e;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(e,n){if(n>e.getContentLength())throw new T(w.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return e;if(n===e.getContentLength())return e.getNext();const r=e.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,n,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,n,r),o=new Map,a=new Map,l=this.makeChanges(s,n);for(const u of i){const c=u.getCreatedAt().getActorID();(!o.has(c)||u.getID().getCreatedAt().after(o.get(c)))&&o.set(c,u.getID().getCreatedAt()),a.set(u.getID().toIDString(),u),u.remove(n)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,n,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const u of e){const c=u.getCreatedAt().getActorID(),f=i?r.has(c)?r.get(c):Nt:bi;u.canDelete(n,f)?s.push(u):o.push(u)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,n){const r=[];let i,s;for(let o=0;ot<0?Math.ceil(t):Math.floor(t);var Ht=(t=>(t[t.IntegerCnt=0]="IntegerCnt",t[t.LongCnt=1]="LongCnt",t))(Ht||{});class nt extends gs{constructor(n,r,i){super(i);m(this,"valueType");m(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=B.fromNumber(r).toInt():this.value=ed(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=B.fromNumber(r):this.value=r;break;default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new nt(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return B.fromBytesLE(Array.from(r));default:throw new T(w.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=nt.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof B?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!nt.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===me.Long?this.value=this.value+n.getValue().toInt():this.value=B.fromNumber(this.value+ed(n.getValue())).toInt(),this}}class ni extends Pt{constructor(n,r,i){super(n,i);m(this,"value");this.value=r}static create(n,r,i){return new ni(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new T(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===me.Long?n.getValue().multiply(-1):n.getValue()*-1;return ni.create(this.getParentCreatedAt(),te.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class an extends Pt{constructor(n,r,i,s,o,a,l){super(n,l);m(this,"fromPos");m(this,"toPos");m(this,"maxCreatedAtMapByActor");m(this,"attributes");m(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(n,r,i,s,o,a){return new an(n,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(n,r,i,s,o,a){return new an(n,r,i,s,new Map,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof pt))throw new T(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,u])=>a[l]=u),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:u,fromPath:c,toPath:f})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:c,toPath:f,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function bw(t){const e=new Qu,n=e.data;for(const[r,i]of Object.entries(t))n[r]=JSON.stringify(i);return e}function Lw(t){if(t.type===zn.Put)return new Wl({type:ns.PUT,presence:bw(t.presence)});if(t.type===zn.Clear)return new Wl({type:ns.CLEAR});throw new T(w.ErrUnimplemented,"unimplemented type")}function Mw(t){return new dp({serverSeq:t.getServerSeqAsString(),clientSeq:t.getClientSeq()})}function Ip(t){return new ra({clientSeq:t.getClientSeq(),lamport:t.getLamportAsString(),actorId:lc(t.getActorID())})}function b(t){if(t)return new M({lamport:t.getLamportAsString(),delimiter:t.getDelimiter(),actorId:lc(t.getActorID())})}function Ep(t){switch(t){case me.Null:return z.NULL;case me.Boolean:return z.BOOLEAN;case me.Integer:return z.INTEGER;case me.Long:return z.LONG;case me.Double:return z.DOUBLE;case me.String:return z.STRING;case me.Bytes:return z.BYTES;case me.Date:return z.DATE;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Np(t){switch(t){case Ht.IntegerCnt:return z.INTEGER_CNT;case Ht.LongCnt:return z.LONG_CNT;default:throw new T(w.ErrInvalidType,`unsupported type: ${t}`)}}function Ka(t){if(t instanceof He)return new Qt({type:z.JSON_OBJECT,createdAt:b(t.getCreatedAt()),value:$p(t)});if(t instanceof tt)return new Qt({type:z.JSON_ARRAY,createdAt:b(t.getCreatedAt()),value:f1(t)});if(t instanceof gt)return new Qt({type:z.TEXT,createdAt:b(t.getCreatedAt())});if(t instanceof te)return new Qt({type:Ep(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof nt)return new Qt({type:Np(t.getType()),createdAt:b(t.getCreatedAt()),value:t.toBytes()});if(t instanceof pt)return new Qt({type:z.TREE,createdAt:b(t.getCreatedAt()),value:h1(t)});throw new T(w.ErrUnimplemented,"unimplemented element")}function Fw(t){return new Kl({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function $s(t){return new fr({createdAt:b(t.getID().getCreatedAt()),offset:t.getID().getOffset(),relativeOffset:t.getRelativeOffset()})}function zs(t){return new ts({parentId:Li(t.getParentID()),leftSiblingId:Li(t.getLeftSiblingID())})}function Li(t){return new zr({createdAt:b(t.getCreatedAt()),offset:t.getOffset()})}function xp(t){const e=new Hu;if(t instanceof dr){const n=t,r=new Hg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.key=n.getKey(),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="set",e.body.value=r}else if(t instanceof ps){const n=t,r=new Gg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="add",e.body.value=r}else if(t instanceof Nn){const n=t,r=new Yg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.prevCreatedAt=b(n.getPrevCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="move",e.body.value=r}else if(t instanceof Un){const n=t,r=new Qg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.createdAt=b(n.getCreatedAt()),r.executedAt=b(n.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(t instanceof ms){const n=t,r=new Xg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);r.content=n.getContent();const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(t instanceof ys){const n=t,r=new Zg;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=$s(n.getFromPos()),r.to=$s(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=b(n.getExecutedAt()),e.body.case="style",e.body.value=r}else if(t instanceof ni){const n=t,r=new ep;r.parentCreatedAt=b(n.getParentCreatedAt()),r.value=Ka(n.getValue()),r.executedAt=b(n.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(t instanceof vs){const n=t,r=new tp,i=r.createdAtMapByActor;for(const[s,o]of n.getMaxCreatedAtMapByActor())i[s]=b(o);r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=zs(n.getFromPos()),r.to=zs(n.getToPos()),r.contents=Jw(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=b(n.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(t instanceof an){const n=t,r=new np;r.parentCreatedAt=b(n.getParentCreatedAt()),r.from=zs(n.getFromPos()),r.to=zs(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=b(a);const s=n.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of n.getAttributes())o[a]=l}r.executedAt=b(n.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(w.ErrUnimplemented,"unimplemented operation");return e}function Bw(t){const e=[];for(const n of t)e.push(xp(n));return e}function $w(t){const e=new qg({id:Ip(t.getID()),message:t.getMessage()});return t.hasOperations()&&(e.operations=Bw(t.getOperations())),t.hasPresenceChange()&&(e.presenceChange=Lw(t.getPresenceChange())),e}function zw(t){const e=[];for(const n of t)e.push($w(n));return e}function Uw(t){const e=[];for(const n of t)e.push(new up({key:n.getStrKey(),element:rc(n.getValue())}));return e}function jw(t){const e=[];for(const n of t)e.push(new Gu({element:rc(n.getValue())}));return e}function Vw(t){const e=[];for(const n of t){const r=new cp;r.id=Fw(n.getID()),r.value=n.getValue().getContent(),r.removedAt=b(n.getRemovedAt());const i=r.attributes,s=n.getValue().getAttrs();for(const o of s){const a=new ia;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function Jw(t){const e=[];if(!t||!t.length)return e;for(const n of t)e.push(new fp({content:nc(n)}));return e}function Kw(t){const e={};for(const n of t)e[n.getKey()]=new ia({value:n.getValue(),updatedAt:b(n.getUpdatedAt()),isRemoved:n.isRemoved()});return e}function nc(t){if(!t)return[];const e=[];return oa(t,(n,r)=>{const i=new Yu({id:Li(n.id),type:n.type,removedAt:b(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=Li(n.insPrevID)),n.insNextID&&(i.insNextId=Li(n.insNextID)),n.attrs&&(i.attributes=Kw(n.attrs)),e.push(i)}),e}function Ww(t){const e=new mt;return e.body.case="jsonObject",e.body.value=new rp({nodes:Uw(t.getRHT()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Cp(t){const e=new mt;return e.body.case="jsonArray",e.body.value=new ip({nodes:jw(t.getElements()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function qw(t){const e=new mt;return e.body.case="primitive",e.body.value=new sp({type:Ep(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Hw(t){const e=new mt;return e.body.case="text",e.body.value=new op({nodes:Vw(t.getRGATreeSplit()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Gw(t){const e=new mt;return e.body.case="counter",e.body.value=new ap({type:Np(t.getType()),value:t.toBytes(),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function Pp(t){const e=new mt;return e.body.case="tree",e.body.value=new lp({nodes:nc(t.getRoot()),createdAt:b(t.getCreatedAt()),movedAt:b(t.getMovedAt()),removedAt:b(t.getRemovedAt())}),e}function rc(t){if(t instanceof He)return Ww(t);if(t instanceof tt)return Cp(t);if(t instanceof te)return qw(t);if(t instanceof gt)return Hw(t);if(t instanceof nt)return Gw(t);if(t instanceof pt)return Pp(t);throw new T(w.ErrUnimplemented,"unimplemented element")}function Yw(t){return new gn({documentKey:t.getDocumentKey(),checkpoint:Mw(t.getCheckpoint()),isRemoved:t.getIsRemoved(),changes:zw(t.getChanges()),snapshot:t.getSnapshot(),minSyncedTicket:b(t.getMinSyncedTicket())})}function td(t){const e=t.findDetails(gw);for(const n of e)if(n.metadata.code)return n.metadata.code;return""}function Op(t){let e;return t.serverSeq&&(e=B.fromString(t.serverSeq,!0)),An.of(t.clientSeq,B.fromString(t.lamport,!0),ac(t.actorId),e)}function L(t){if(t)return qe.of(B.fromString(t.lamport,!0),t.delimiter,ac(t.actorId))}function ic(t){const e={};return Object.entries(t.data).forEach(([n,r])=>{e[n]=JSON.parse(r)}),e}function Qw(t){const e=t.type;if(e===ns.PUT){const n=ic(t.presence);return{type:zn.Put,presence:n}}if(e===ns.CLEAR)return{type:zn.Clear};throw new T(w.ErrInvalidType,`unsupported type: ${e}`)}function Xw(t){const e=new Map;return Object.entries(t).forEach(([n,r])=>{e.set(n,ic(r))}),e}function Dp(t){switch(t){case z.NULL:return me.Null;case z.BOOLEAN:return me.Boolean;case z.INTEGER:return me.Integer;case z.LONG:return me.Long;case z.DOUBLE:return me.Double;case z.STRING:return me.String;case z.BYTES:return me.Bytes;case z.DATE:return me.Date}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Bo(t){switch(t){case z.INTEGER_CNT:return Ht.IntegerCnt;case z.LONG_CNT:return Ht.LongCnt}throw new T(w.ErrUnimplemented,`unimplemented value type: ${t}`)}function Wa(t){switch(t.type){case z.JSON_OBJECT:return t.value?Bp(t.value):He.create(L(t.createdAt));case z.JSON_ARRAY:return t.value?c1(t.value):tt.create(L(t.createdAt));case z.TEXT:return gt.create(ti.create(),L(t.createdAt));case z.TREE:return d1(t.value);case z.NULL:case z.BOOLEAN:case z.INTEGER:case z.LONG:case z.DOUBLE:case z.STRING:case z.BYTES:case z.DATE:return te.of(te.valueFromBytes(Dp(t.type),t.value),L(t.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return nt.create(Bo(t.type),nt.valueFromBytes(Bo(t.type),t.value),L(t.createdAt))}}function Us(t){return xt.of(qt.of(L(t.createdAt),t.offset),t.relativeOffset)}function Rp(t){return qt.of(L(t.createdAt),t.offset)}function Zw(t){const e=os.create(t.value);Object.entries(t.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,L(i.updatedAt))});const n=Mn.create(Rp(t.id),e);return n.remove(L(t.removedAt)),n}function vr(t){return At.of(Mi(t.parentId),Mi(t.leftSiblingId))}function Mi(t){return Ie.of(L(t.createdAt),t.offset)}function e1(t){if(!t.length)return;const e=[];return t.forEach(n=>{const r=sc(n.content);e.push(r)}),e}function sc(t){if(t.length===0)return;const e=[];for(const i of t)e.push(n1(i));const n=e[e.length-1],r=new Map;r.set(t[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(t[i].depth-1).prepend(e[i]),r.set(t[i].depth,e[i]);return n.updateDescendantsSize(),pt.create(n,Nt).getRoot()}function t1(t){const e=dn.create();for(const[n,r]of Object.entries(t))e.setInternal(n,r.value,L(r.updatedAt),r.isRemoved);return e}function n1(t){const e=Mi(t.id),n=Ze.create(e,t.type),r=Object.entries(t.attributes);return n.isText?n.value=t.value:r.length&&(n.attrs=t1(t.attributes)),t.insPrevId&&(n.insPrevID=Mi(t.insPrevId)),t.insNextId&&(n.insNextID=Mi(t.insNextId)),n.removedAt=L(t.removedAt),n}function _p(t){if(t.body.case==="set"){const e=t.body.value;return dr.create(e.key,Wa(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(t.body.case==="add"){const e=t.body.value;return ps.create(L(e.parentCreatedAt),L(e.prevCreatedAt),Wa(e.value),L(e.executedAt))}else if(t.body.case==="move"){const e=t.body.value;return Nn.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="remove"){const e=t.body.value;return Un.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(t.body.case==="edit"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ms.create(L(e.parentCreatedAt),Us(e.from),Us(e.to),n,e.content,r,L(e.executedAt))}else if(t.body.case==="style"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,L(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),ys.create(L(e.parentCreatedAt),Us(e.from),Us(e.to),n,r,L(e.executedAt))}else{if(t.body.case==="select")return;if(t.body.case==="increase"){const e=t.body.value;return ni.create(L(e.parentCreatedAt),Wa(e.value),L(e.executedAt))}else if(t.body.case==="treeEdit"){const e=t.body.value,n=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{n.set(r,L(i))}),vs.create(L(e.parentCreatedAt),vr(e.from),vr(e.to),e1(e.contents),e.splitLevel,n,L(e.executedAt))}else if(t.body.case==="treeStyle"){const e=t.body.value,n=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,L(o))}),(r==null?void 0:r.length)>0?an.createTreeRemoveStyleOperation(L(e.parentCreatedAt),vr(e.from),vr(e.to),i,r,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{n.set(s,o)}),an.create(L(e.parentCreatedAt),vr(e.from),vr(e.to),i,n,L(e.executedAt)))}else throw new T(w.ErrUnimplemented,"unimplemented operation")}}function r1(t){const e=[];for(const n of t){const r=_p(n);r&&e.push(r)}return e}function bp(t){const e=[];for(const n of t)e.push(ei.create({id:Op(n.id),operations:r1(n.operations),presenceChange:n.presenceChange?Qw(n.presenceChange):void 0,message:n.message}));return e}function i1(t){return jr.of(B.fromString(t.serverSeq,!0),t.clientSeq)}function s1(t){return aa.create(t.documentKey,i1(t.checkpoint),t.isRemoved,bp(t.changes),t.snapshot,L(t.minSyncedTicket))}function Lp(t){const e=new rs;for(const r of t.nodes){const i=oc(r.element);e.set(r.key,i,i.getPositionedAt())}const n=new He(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function Mp(t){const e=new ss;for(const r of t.nodes)e.insert(oc(r.element));const n=new tt(L(t.createdAt),e);return n.setMovedAt(L(t.movedAt)),n.setRemovedAt(L(t.removedAt)),n}function o1(t){const e=te.of(te.valueFromBytes(Dp(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function a1(t){const e=new ti;let n=e.getHead();for(const i of t.nodes){const s=e.insertAfter(n,Zw(i));i.insPrevId&&s.setInsPrev(e.findNode(Rp(i.insPrevId))),n=s}const r=new gt(e,L(t.createdAt));return r.setMovedAt(L(t.movedAt)),r.setRemovedAt(L(t.removedAt)),r}function l1(t){const e=nt.create(Bo(t.type),nt.valueFromBytes(Bo(t.type),t.value),L(t.createdAt));return e.setMovedAt(L(t.movedAt)),e.setRemovedAt(L(t.removedAt)),e}function Fp(t){const e=sc(t.nodes);return pt.create(e,L(t.createdAt))}function oc(t){if(t.body.case==="jsonObject")return Lp(t.body.value);if(t.body.case==="jsonArray")return Mp(t.body.value);if(t.body.case==="primitive")return o1(t.body.value);if(t.body.case==="text")return a1(t.body.value);if(t.body.case==="counter")return l1(t.body.value);if(t.body.case==="tree")return Fp(t.body.value);throw new T(w.ErrUnimplemented,"unimplemented element")}function u1(t){if(!t)return{root:He.create(Nt),presences:new Map};const e=J0.fromBinary(t);return{root:oc(e.root),presences:Xw(e.presences)}}function Bp(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Lp(e.body.value)}function $p(t){return rc(t).toBinary()}function c1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Mp(e.body.value)}function f1(t){return Cp(t).toBinary()}function d1(t){if(!t)throw new T(w.ErrInvalidArgument,"bytes is empty");const e=mt.fromBinary(t);return Fp(e.body.value)}function h1(t){return Pp(t).toBinary()}function zp(t){return t?Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ac(t){return zp(t)}function Up(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lc(t){return Up(t)}function g1(t){const e=ra.fromBinary(t);return Op(e)}function p1(t){const e=Hu.fromBinary(t);return _p(e)}const ye={fromPresence:ic,toChangePack:Yw,fromChangePack:s1,fromChanges:bp,toTreeNodes:nc,fromTreeNodes:sc,objectToBytes:$p,bytesToObject:Bp,bytesToSnapshot:u1,bytesToHex:zp,hexToBytes:Up,toHexString:ac,toUint8Array:lc,toOperation:xp,toChangeID:Ip,PbChangeID:ra,bytesToChangeID:g1,bytesToOperation:p1};var be=(t=>(t[t.Trivial=0]="Trivial",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.Fatal=5]="Fatal",t))(be||{});let Yn=3;function jp(t){Yn=t}const F={trivial:(...t)=>{Yn>0||typeof console<"u"&&console.log("YORKIE T:",...t)},debug:(...t)=>{Yn>1||typeof console<"u"&&console.log("YORKIE D:",...t)},info:(...t)=>{Yn>2||typeof console<"u"&&console.log("YORKIE I:",...t)},warn:(...t)=>{Yn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:(...t)=>{Yn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:(...t)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...t):console.log("YORKIE F:",...t))},isEnabled:t=>Yn<=t};function Vp(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class m1{constructor(e,n,r,i,s){m(this,"reconnectStreamDelay");m(this,"doc");m(this,"docID");m(this,"syncMode");m(this,"remoteChangeEventReceived");m(this,"watchStream");m(this,"watchLoopTimerID");m(this,"watchAbortController");m(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===lo.RealtimeSyncOff?!1:this.syncMode===lo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==lo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const qa=()=>{};class y1{constructor(e){m(this,"finalized",!1);m(this,"observers",[]);m(this,"finalError");try{e(this)}catch(n){this.error(n)}}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(!e)throw new T(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:n,complete:r},i.next===void 0&&(i.next=qa),i.error===void 0&&(i.error=qa),i.complete===void 0&&(i.complete=qa);const s=Vp(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){F.warn(a)}return o}unsubscribeOne(e){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let n=0;ne}}class _r{constructor(e,n,r,i){m(this,"id");m(this,"delimiter");m(this,"message");m(this,"root");m(this,"operations");m(this,"presenceChange");m(this,"previousPresence");m(this,"reversePresenceKeys");this.id=e,this.delimiter=Zu,this.root=n,this.operations=[],this.previousPresence=wt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,n,r,i){return new _r(e,n,r,i)}push(e){this.operations.push(e)}registerElement(e,n){this.root.registerElement(e,n)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ei.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,n){for(const r of Object.keys(e))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const n of this.reversePresenceKeys)e[n]=this.previousPresence[n];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class as{constructor(e){m(this,"rootObject");m(this,"elementPairMapByCreatedAt");m(this,"gcElementSetByCreatedAt");m(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof gt||n instanceof pt)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new as(He.create(Nt))}findByCreatedAt(e){const n=this.elementPairMapByCreatedAt.get(e.toIDString());if(n)return n.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let n=this.elementPairMapByCreatedAt.get(e.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),s=n.parent.subPathOf(i);if(s===void 0)throw new T(w.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,n){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:n,element:e}),e instanceof Ln&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let n=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),n++};return r(e),e instanceof Ln&&e.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const n of this.gcElementSetByCreatedAt){e.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof Ln&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new as(this.rootObject.deepcopy())}garbageCollect(e){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Jp(t,e){const n=new ls(t);return new Proxy(e,n.getHandlers())}class ls{constructor(e){m(this,"context");m(this,"handlers");this.context=e,this.handlers={set:(n,r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]=${JSON.stringify(i)}`),ls.setInternal(e,n,r,i),!0),get:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():Qn(e,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(F.isEnabled(be.Trivial)&&F.trivial(`obj[${r}]`),ls.deleteInternal(e,n,r),!0)}}static setInternal(e,n,r,i){if(r.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=$o(e,i,s),a=n.set(r,o,s);e.registerElement(o,n),a&&e.registerRemovedElement(a),e.push(dr.create(r,o.deepcopy(),n.getCreatedAt(),s))}static buildObjectMembers(e,n){const r={};for(const[i,s]of Object.entries(n)){if(i.includes("."))throw new T(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=$o(e,s,o);r[i]=a}return r}static deleteInternal(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByKey(r,i);s&&(e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function w1(t,e){const n=new ie(t,e);return new Proxy(e,n.getHandlers())}function S1(t){return typeof t=="string"||t instanceof String?!isNaN(t):!1}function T1(t){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(t)}class ie{constructor(e,n){m(this,"context");m(this,"handlers");m(this,"array");this.context=e,this.array=n,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return yn(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return yn(e,a)}:i==="getLast"?()=>yn(e,r.getLast()):i==="deleteByID"?o=>{const a=ie.deleteInternalByID(e,r,o);return yn(e,a)}:i==="insertAfter"?(o,a)=>{const l=ie.insertAfterInternal(e,r,o,a);return yn(e,l)}:i==="insertBefore"?(o,a)=>{const l=ie.insertBeforeInternal(e,r,o,a);return yn(e,l)}:i==="moveBefore"?(o,a)=>{ie.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ie.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ie.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ie.moveLastInternal(e,r,o)}:S1(i)?Qn(e,r.get(Number(i))):i==="push"?o=>ie.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ie.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ie.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ie.includes(e,r,o,a):i==="indexOf"?(o,a)=>ie.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ie.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ie.toTestString(r):typeof i=="string"&&T1(i)?(...o)=>{const a=Array.from(r).map(l=>Qn(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(F.isEnabled(be.Trivial)&&F.trivial(`array[${i}]`),ie.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,n){for(const r of n)yield yn(e,r)}static buildArrayElements(e,n){const r=[];for(const i of n){const s=e.issueTimeTicket(),o=$o(e,i,s);r.push(o)}return r}static pushInternal(e,n,r){return ie.insertAfterInternal(e,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(e,n,r,i){const s=e.issueTimeTicket(),o=n.getPrevCreatedAt(r);n.moveAfter(o,i,s),e.push(Nn.create(n.getCreatedAt(),o,i,s))}static moveAfterInternal(e,n,r,i){const s=e.issueTimeTicket();n.moveAfter(r,i,s),e.push(Nn.create(n.getCreatedAt(),r,i,s))}static moveFrontInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getHead();n.moveAfter(s.getCreatedAt(),r,i),e.push(Nn.create(n.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getLastCreatedAt();n.moveAfter(s,r,i),e.push(Nn.create(n.getCreatedAt(),s,r,i))}static insertAfterInternal(e,n,r,i){const s=e.issueTimeTicket(),o=$o(e,i,s);return n.insertAfter(r,o),e.registerElement(o,n),e.push(ps.create(n.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,n,r,i){return ie.insertAfterInternal(e,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByIndex(r,i);if(s)return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,n,r){const i=e.issueTimeTicket(),s=n.delete(r,i);return e.push(Un.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,n,r,i,...s){const o=n.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),u=[];for(let c=a;c=s)return!1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).includes(r,o);for(let l=o;l=s)return-1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(te.isSupport(r))return Array.from(n).map(u=>Qn(e,u)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=n.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class la{constructor(e,n){m(this,"context");m(this,"text");this.context=e,this.text=n}initialize(e,n){this.context=e,this.text=n}getID(){return this.text.getID()}edit(e,n,r,i){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${n}->${s[1].toTestString()} c:${r}`);const o=i?Zr(i):void 0,a=this.context.issueTimeTicket(),[l,,u,c]=this.text.edit(s,r,a,o);for(const f of u)this.context.registerGCPair(f);return this.context.push(new ms(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,n){return this.edit(e,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,n,r){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,n);F.isEnabled(be.Debug)&&F.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=Zr(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const u of l)this.context.registerGCPair(u);return this.context.push(new ys(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(e[0],e[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([xt.fromStruct(e[0]),xt.fromStruct(e[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,n){if(!this.context||!this.text)throw new T(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,n)}}class ua{constructor(e,n){m(this,"valueType");m(this,"value");m(this,"context");m(this,"counter");this.valueType=e,this.value=n}initialize(e,n){this.valueType=n.getValueType(),this.context=e,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=te.of(e,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ni.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function uc(t,e,n){const{type:r}=t,i=n.issueTimeTicket();if(r===on){Kp(t);const{value:s}=t,o=Ze.create(Ie.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=t,{attributes:o}=t;let a;if(typeof o=="object"&&!yp(o)){const u=Zr(o);a=new dn;for(const[c,f]of Object.entries(u))a.set(c,f,i)}const l=Ze.create(Ie.of(i,0),r,void 0,a);e.append(l);for(const u of s)uc(u,l,n)}}function k1(t,e){const{type:n}=e,r=t.issueTimeTicket();let i;if(e.type===on){const{value:s}=e;i=Ze.create(Ie.of(r,0),n,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!yp(o)){const l=Zr(o);a=new dn;for(const[u,c]of Object.entries(l))a.set(u,c,r)}i=Ze.create(Ie.of(t.issueTimeTicket(),0),n,void 0,a);for(const l of s)uc(l,i,t)}return i}function Kp(t){if(!t.value.length)throw new T(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function nd(t){if(!t.length)return!0;if(t[0].type===on)for(const n of t){const{type:r}=n;if(r!==on)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together");Kp(n)}else for(const n of t){const{type:r}=n;if(r===on)throw new T(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ca{constructor(e){m(this,"initialRoot");m(this,"context");m(this,"tree");this.initialRoot=e}initialize(e,n){this.context=e,this.tree=n}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ze.create(Ie.of(e.issueTimeTicket(),0),Aw);const n=Ze.create(Ie.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)uc(r,n,e);return n}getSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,n){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=n?Zr(n):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(an.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),a=r?Zr(r):void 0,[l,u]=this.tree.style([i,s],a,o);for(const c of u)this.context.registerGCPair(c);this.context.push(an.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,n,r){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const u of l)this.context.registerGCPair(u);this.context.push(an.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,n,r,i=0){var u;if(r.length!==0&&r[0]&&(nd(r),r[0].type!==on))for(const c of r){const{children:f=[]}=c;nd(f)}const s=this.context.getLastTimeTicket();let o=new Array;if(((u=r[0])==null?void 0:u.type)===on){let c="";for(const f of r){const{value:g}=f;c+=g}o.push(Ze.create(Ie.of(this.context.issueTimeTicket(),0),on,c))}else o=r.map(c=>c&&k1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,n],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(vs.create(this.tree.getCreatedAt(),e,n,o.length?o:void 0,i,l,s)),!0}editByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new T(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new T(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r,i)}edit(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,n,r,i=0){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new T(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[At.fromStruct(e[0]),At.fromStruct(e[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(w.ErrNotInitialized,"Tree is not initialized yet");const n=[At.fromStruct(e[0]),At.fromStruct(e[1])];return this.tree.posRangeToPathRange(n)}}function rd(t,e){return Jp(t,e)}function yn(t,e){if(e){if(e instanceof te)return e;if(e instanceof He)return Jp(t,e);if(e instanceof tt)return w1(t,e);if(e instanceof gt)return new la(t,e);if(e instanceof nt){const n=new ua(Ht.IntegerCnt,0);return n.initialize(t,e),n}else if(e instanceof pt){const n=new ca;return n.initialize(t,e),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Qn(t,e){const n=yn(t,e);return n instanceof te?n.getValue():n}function $o(t,e,n){let r;if(te.isSupport(e))r=te.of(e,n);else if(Array.isArray(e))r=tt.create(n,ie.buildArrayElements(t,e));else if(typeof e=="object")e instanceof la?(r=gt.create(ti.create(),n),e.initialize(t,r)):e instanceof ua?(r=nt.create(e.getValueType(),e.getValue(),n),e.initialize(t,r)):e instanceof ca?(r=pt.create(e.buildRoot(t),n),e.initialize(t,r)):r=He.create(n,ls.buildObjectMembers(t,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const id=50;class A1{constructor(){m(this,"undoStack",[]);m(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=id&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=id&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const I1="yorkie-devtools-panel",E1="yorkie-devtools-sdk";let wr="disconnected";const sd=new Map,ao=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ao);function js(t,e){(e!=null&&e.force||wr!=="disconnected")&&window.postMessage({source:E1,...t},"*")}function N1(t){if(!t.isEnableDevtools()||typeof window>"u"||sd.has(t.getKey()))return;ao.set(t.getKey(),[]);const e=t.subscribe("all",n=>{n.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(ao.get(t.getKey()).push(n),wr==="synced"&&js({msg:"doc::sync::partial",docKey:t.getKey(),event:n}))});sd.set(t.getKey(),[e]),js({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==I1)return;switch(n.data.msg){case"devtools::connect":if(wr!=="disconnected")break;wr="connected",js({msg:"doc::available",docKey:t.getKey()}),F.info(`[YD] Devtools connected. Doc: ${t.getKey()}`);break;case"devtools::disconnect":wr="disconnected",F.info(`[YD] Devtools disconnected. Doc: ${t.getKey()}`);break;case"devtools::subscribe":wr="synced",js({msg:"doc::sync::full",docKey:t.getKey(),events:ao.get(t.getKey())}),F.info(`[YD] Devtools subscribed. Doc: ${t.getKey()}`);break}})}var vn=(t=>(t.Detached="detached",t.Attached="attached",t.Removed="removed",t))(vn||{}),$e=(t=>(t.StatusChanged="status-changed",t.ConnectionChanged="connection-changed",t.SyncStatusChanged="sync-status-changed",t.Snapshot="snapshot",t.LocalChange="local-change",t.RemoteChange="remote-change",t.Initialized="initialized",t.Watched="watched",t.Unwatched="unwatched",t.PresenceChanged="presence-changed",t.Broadcast="broadcast",t.LocalBroadcast="local-broadcast",t))($e||{}),Yl=(t=>(t.Connected="connected",t.Disconnected="disconnected",t))(Yl||{}),Ql=(t=>(t.Synced="synced",t.SyncFailed="sync-failed",t))(Ql||{});class Wp{constructor(e,n){m(this,"key");m(this,"status");m(this,"opts");m(this,"changeID");m(this,"checkpoint");m(this,"localChanges");m(this,"root");m(this,"clone");m(this,"eventStream");m(this,"eventStreamObserver");m(this,"onlineClients");m(this,"presences");m(this,"history");m(this,"internalHistory");m(this,"isUpdating");this.opts=n||{},this.key=e,this.status="detached",this.root=as.create(),this.changeID=Dw,this.checkpoint=Rw,this.localChanges=[],this.eventStream=v1(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new A1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},N1(this)}update(e,n){if(this.getStatus()==="removed")throw new T(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const s=rd(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Ja(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){F.isEnabled(be.Trivial)&&F.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,G.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const u=[];o.length>0&&u.push({type:"local-change",source:G.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&u.push({type:"presence-changed",source:G.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(u),F.isEnabled(be.Trivial)&&F.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,n,r,i){if(typeof e=="string"){if(typeof n!="function")throw new T(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||a(u)},r,i)}if(e==="my-presence"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="initialized"&&u.type!=="presence-changed"||u.type==="presence-changed"&&u.value.clientID!==this.changeID.getActorID()||a(u)},r,i)}if(e==="others"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="watched"&&u.type!=="unwatched"&&u.type!=="presence-changed"||u.value.clientID!==this.changeID.getActorID()&&a(u)},r,i)}if(e==="connection"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="connection-changed"&&a(u)},r,i)}if(e==="status"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="status-changed"&&a(u)},r,i)}if(e==="sync"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="sync-status-changed"&&a(u)},r,i)}if(e==="local-broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="local-broadcast"&&a(u)},r)}if(e==="broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const u of l)u.type==="broadcast"&&a(u)},r)}if(e==="all"){const a=n;return this.eventStream.subscribe(a,r,i)}const s=e,o=n;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const u=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&u.push(c);u.length&&o({...l,value:{...l.value,operations:u}})}},r,i)}if(typeof e=="function"){const s=e,o=n,a=r;return this.eventStream.subscribe(l=>{for(const u of l)u.type!=="snapshot"&&u.type!=="local-change"&&u.type!=="remote-change"||s(u)},o,a)}throw new T(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,n){if(n===e)return!0;const r=e.split(".");return n.split(".").every((s,o)=>s===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),G.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,G.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),F.isEnabled(be.Trivial)&&F.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(e.length);return aa.create(this.key,n,!1,e)}setActor(e){for(const n of this.localChanges)n.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return rd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,n){const{root:r,presences:i}=ye.bytesToSnapshot(n);this.root=new as(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:G.Remote,value:{snapshot:this.isEnableDevtools()?ye.bytesToHex(n):void 0,serverSeq:e.toString()}}])}applyChanges(e,n){F.isEnabled(be.Debug)&&F.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),F.isEnabled(be.Trivial)&&F.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of e)this.applyChange(r,n);F.isEnabled(be.Debug)&&F.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,n){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,n);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case zn.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:o.presence}}:{type:"watched",source:G.Remote,value:{clientID:i,presence:o.presence}});break;case zn.Clear:r.push({type:"unwatched",source:G.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(n===G.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const n=e.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:G.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:n,publisher:r}=e.body.value,i=[];if(n===_i.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:G.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===_i.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:G.Remote,value:{clientID:r,presence:s}})}else if(n===_i.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(sa),this.publish([{source:e==="removed"?G.Remote:G.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:n,serverSeq:r}=e.value;if(!n)return;this.applySnapshot(B.fromString(r),ye.hexToBytes(n));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const n=ei.fromStruct(e.rawChange);this.applyChange(n,e.source)}if(e.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of e.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(e.type==="watched"){const{clientID:n,presence:r}=e.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(e.type==="unwatched"){const{clientID:n}=e.value;this.removeOnlineClient(n),this.presences.delete(n)}if(e.type==="presence-changed"){const{clientID:n,presence:r}=e.value;this.presences.set(n,r)}}applyTransactionEvent(e){for(const n of e)this.applyDocEvent(n)}getValueByPath(e){if(!e.startsWith("$"))throw new T(w.ErrInvalidArgument,'path must start with "$"');const n=e.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?wt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const n=this.presences.get(e);return n?wt(n):void 0}getPresenceForTest(e){const n=this.presences.get(e);return n?wt(n):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:wt(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&e.push({clientID:n,presence:wt(this.presences.get(n))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==e).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new T(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new T(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof Pt)){new Ja(n,wt(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const c=n.issueTimeTicket();u.setExecutedAt(c),n.push(u)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,G.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,G.UndoRedo),o=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:G.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:G.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new T(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new T(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=_r.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const u of e){if(!(u instanceof Pt)){new Ja(n,wt(this.clone.presences.get(this.changeID.getActorID()))).set(u.value,{addToHistory:!0});continue}const c=n.issueTimeTicket();u.setExecutedAt(c),n.push(u)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,G.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,G.UndoRedo),o=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:G.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:G.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,n,r){const i={type:"local-broadcast",value:{topic:e,payload:n},options:r};this.publish([i])}}function x1(t,e){return n=>async r=>(t&&r.header.set("x-api-key",t),e&&r.header.set("authorization",e),await n(r))}const C1="yorkie-js-sdk",P1="0.5.0",O1="Yorkie JS SDK",D1="./src/yorkie.ts",R1={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},_1=["dist"],b1={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},L1={node:">=18.0.0",npm:">=7.1.0"},M1={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},F1={name:"hackerwins",email:"susukang98@gmail.com"},B1="Apache-2.0",$1={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},z1="https://github.com/yorkie-team/yorkie-js-sdk#readme",U1={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},j1={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},od={name:C1,version:P1,description:O1,main:D1,publishConfig:R1,files:_1,scripts:b1,engines:L1,repository:M1,author:F1,license:B1,bugs:$1,homepage:z1,devDependencies:U1,dependencies:j1};function V1(){return t=>async e=>(e.header.set("x-yorkie-user-agent",od.name+"/"+od.version),await t(e))}const J1=t=>{try{if(JSON.stringify(t)===void 0)return!1}catch{return!1}return!0};var lo=(t=>(t.Manual="manual",t.Realtime="realtime",t.RealtimePushOnly="realtime-pushonly",t.RealtimeSyncOff="realtime-syncoff",t))(lo||{});const Vs={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ha={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class qp{constructor(e,n){m(this,"id");m(this,"key");m(this,"status");m(this,"attachmentMap");m(this,"apiKey");m(this,"conditions");m(this,"syncLoopDuration");m(this,"reconnectStreamDelay");m(this,"retrySyncLoopDelay");m(this,"rpcClient");m(this,"taskQueue");m(this,"processing",!1);n=n||Vs,this.key=n.key?n.key:Vp(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Vs.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Vs.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Vs.retrySyncLoopDelay,this.rpcClient=T0(dw,V0({baseUrl:e,interceptors:[x1(n.apiKey,n.token),V1()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),F.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw F.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),F.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw F.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,n={}){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==vn.Detached)throw new T(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(n.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,u=s.options;try{await this.broadcast(e.getKey(),o,a,u)}catch(f){f instanceof Error&&(l==null||l(f))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ye.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ye.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===vn.Removed||(e.applyStatus(vn.Attached),this.attachmentMap.set(e.getKey(),new m1(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),F.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw F.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,n={}){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:ye.toChangePack(e.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ye.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==vn.Removed&&e.applyStatus(vn.Detached),this.detachInternal(e.getKey()),F.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw F.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,n){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===n?e:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),e):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const n=this.attachmentMap.get(e.getKey());if(!n)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw F.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw F.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new T(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=ye.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ye.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),F.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw F.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,n,r,i){if(!this.isActive())throw new T(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new T(w.ErrDocumentNotAttached,`${e} is not attached`);if(!J1(r))throw new T(w.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Ha.maxRetries,a=Ha.maxBackoff;let l=0;const u=f=>Math.min(Ha.initialRetryInterval*2**f,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{F.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${n}"`)}).catch(f=>{if(F.error(`[BC] c:"${this.getKey()}" err:`,f),this.handleConnectError(f))if(lc(),u(l-1)),F.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw F.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),f;else throw f}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){F.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{F.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};F.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const n=this.attachmentMap.get(e);if(!n)throw new T(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new T(w.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return n.doc.publish([{type:$e.ConnectionChanged,value:Yl.Connected}]),F.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const u of s)this.handleWatchDocumentsResponse(n,u),u.body.case==="initialization"&&o([s,i])}catch(u){n.doc.resetOnlineClients(),n.doc.publish([{type:$e.Initialized,source:G.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:$e.ConnectionChanged,value:Yl.Disconnected}]),F.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(u)?r():this.conditions.WatchLoop=!1,a(u)}})()})})}handleWatchDocumentsResponse(e,n){if(n.body.case==="event"&&n.body.value.type===_i.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[e,n]of this.attachmentMap)this.detachInternal(e),n.doc.applyStatus(vn.Detached)}detachInternal(e){const n=this.attachmentMap.get(e);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,n){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:ye.toChangePack(s),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ye.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Ql.Synced}]),r.getStatus()===vn.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),u=a.getChangeSize();return F.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${u} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Ql.SyncFailed}]),F.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof he?e.code===q.Canceled||e.code===q.Unknown||e.code===q.ResourceExhausted||e.code===q.Unavailable?!0:((td(e)===w.ErrClientNotActivated||td(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((n,r)=>{this.taskQueue.push(()=>e().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{F.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Hp={Client:qp,Document:Wp,Primitive:te,Text:la,Counter:ua,Tree:ca,LogLevel:be,setLogLevel:jp,IntType:Ht.IntegerCnt,LongType:Ht.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:qp,Document:Wp,Primitive:te,Text:la,Counter:ua,Tree:ca,LogLevel:be,setLogLevel:jp,IntType:Ht.IntegerCnt,LongType:Ht.LongCnt});class K1{constructor(e,n){this.x=e,this.y=n,this.lifetime=0}}const W1=({xPos:t,yPos:e})=>{const[n,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,u)=>{const c=new K1(l,u);s.push(c),o(s),n.push(c),r(n)};return Ue.useEffect(()=>{const u=i.current.getContext("2d"),c=()=>{u.clearRect(0,0,u.canvas.width,u.canvas.height);const f=.7*(1*4e3)/60;for(let g=0;gf)s.shift();else{u.lineWidth=5,u.lineJoin="round";const I=0,O=0,p=0;u.strokeStyle=`rgb(${I},${O},${p})`,u.beginPath(),u.moveTo(v.x,v.y),u.lineTo(h.x,h.y),u.stroke(),u.closePath()}}requestAnimationFrame(c)};c()},[s]),Ue.useEffect(()=>{a(t,e)},[t,e]),ae.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},q1="_goUp0_1lnal_1",H1="_goUpAnimation0_1lnal_1",G1="_fadeOut_1lnal_1",Y1="_goUp1_1lnal_16",Q1="_goUpAnimation1_1lnal_1",X1="_goUp2_1lnal_31",Z1="_goUpAnimation2_1lnal_1",eS="_leftRight0_1lnal_46",tS="_leftRightAnimation0_1lnal_1",nS="_leftRight1_1lnal_60",rS="_leftRightAnimation1_1lnal_1",iS="_leftRight2_1lnal_74",sS="_leftRightAnimation2_1lnal_1",Ga={goUp0:q1,goUpAnimation0:H1,fadeOut:G1,goUp1:Y1,goUpAnimation1:Q1,goUp2:X1,goUpAnimation2:Z1,leftRight0:eS,leftRightAnimation0:tS,leftRight1:nS,leftRightAnimation1:rS,leftRight2:iS,leftRightAnimation2:sS};function oS({x:t,y:e,timestamp:n,selectedCursorShape:r}){return ae.jsx("div",{className:"single-animation-container",children:ae.jsx("div",{className:`absolute select-none pointer-events-none ${Ga.disappear} text-${n%5+2}xl ${Ga["goUp"+n%3]}`,style:{left:t,top:e},children:ae.jsx("div",{className:Ga["leftRight"+n%3],children:ae.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ae.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function ad(t,e){const n=Ue.useRef(t);Ue.useEffect(()=>{n.current=t},[t]),Ue.useEffect(()=>{function r(){n.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const aS=({pointerDown:t,xPos:e,yPos:n,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return ad(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),ad(()=>{t&&s(a=>a.concat([{point:{x:e,y:n},timestamp:Date.now()}]))},o),ae.jsx("div",{style:{transform:`translateX(${e}px) translateY(${n}px)`},children:i.map(a=>ae.jsx(oS,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},lS=({selectedCursorShape:t,x:e,y:n,pointerDown:r})=>ae.jsxs(ae.Fragment,{children:[ae.jsx("img",{src:`./icons/icon_${t}.svg`,className:`${t}-cursor`,style:{transform:`translate3d(${e}px, ${n}px, 0)`}}),(t==="heart"||t==="thumbs")&&ae.jsx(aS,{pointerDown:r,xPos:e,yPos:n,selectedCursorShape:t}),t==="pen"&&r&&ae.jsx(W1,{xPos:e,yPos:n})]}),uS=({handleCursorShapeSelect:t,clientsLength:e})=>{const[n,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ae.jsxs("div",{className:"cursor-selector-container",children:[ae.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ae.jsx("img",{onClick:()=>{t(s),r(s)},className:`${n===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ae.jsx("div",{className:"num-users-container",children:ae.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Ya=new Hp.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),qn=new Hp.Document("simultaneous-cursors",{enableDevtools:!0}),cS=()=>{const[t,e]=Ue.useState([]),n=r=>{qn.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Ya.activate(),qn.subscribe("presence",a=>{e(qn.getPresences())}),await Ya.attach(qn,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Ya.deactivate()})})();const i=()=>{qn.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{qn.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{qn.update((l,u)=>{u.set({cursor:{xPos:a.clientX,yPos:a.clientY}})})};return window.addEventListener("mousedown",s),window.addEventListener("mouseup",i),window.addEventListener("mousemove",o),()=>{window.removeEventListener("mousedown",s),window.removeEventListener("mouseup",i),window.removeEventListener("mousemove",o)}},[]),ae.jsxs("div",{className:"general-container",children:[t.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ae.jsx(lS,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ae.jsx(uS,{handleCursorShapeSelect:n,clientsLength:t.length})]})};Qa.createRoot(document.getElementById("root")).render(ae.jsx(cS,{})); diff --git a/examples/simultaneous-cursors/index.html b/examples/simultaneous-cursors/index.html index 2222a9ceb..4bd54da48 100644 --- a/examples/simultaneous-cursors/index.html +++ b/examples/simultaneous-cursors/index.html @@ -5,7 +5,7 @@ Simultaneous Cursors - Yorkie Example - + diff --git a/examples/vanilla-codemirror6/assets/index-DBK0GrON.js b/examples/vanilla-codemirror6/assets/index-Bph-qp4N.js similarity index 85% rename from examples/vanilla-codemirror6/assets/index-DBK0GrON.js rename to examples/vanilla-codemirror6/assets/index-Bph-qp4N.js index 08a0984d2..f039f87bc 100644 --- a/examples/vanilla-codemirror6/assets/index-DBK0GrON.js +++ b/examples/vanilla-codemirror6/assets/index-Bph-qp4N.js @@ -19,7 +19,7 @@ var Iy=Object.defineProperty;var Ey=(i,e,t)=>e in i?Iy(i,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Ot=null;try{Ot=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Z(i,e,t){this.low=i|0,this.high=e|0,this.unsigned=!!t}Z.prototype.__isLong__;Object.defineProperty(Z.prototype,"__isLong__",{value:!0});function Ze(i){return(i&&i.__isLong__)===!0}function Qu(i){var e=Math.clz32(i&-i);return i?31-e:e}Z.isLong=Ze;var Pu={},Au={};function Pi(i,e){var t,n,r;return e?(i>>>=0,(r=0<=i&&i<256)&&(n=Au[i],n)?n:(t=K(i,0,!0),r&&(Au[i]=t),t)):(i|=0,(r=-128<=i&&i<128)&&(n=Pu[i],n)?n:(t=K(i,i<0?-1:0,!1),r&&(Pu[i]=t),t))}Z.fromInt=Pi;function yt(i,e){if(isNaN(i))return e?kn:Nt;if(e){if(i<0)return kn;if(i>=cg)return dg}else{if(i<=-Cu)return tt;if(i+1>=Cu)return fg}return i<0?yt(-i,e).neg():K(i%Ji|0,i/Ji|0,e)}Z.fromNumber=yt;function K(i,e,t){return new Z(i,e,t)}Z.fromBits=K;var Uo=Math.pow;function Hh(i,e,t){if(i.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return e?kn:Nt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return Hh(i.substring(1),e,t).neg();for(var r=yt(Uo(t,8)),s=Nt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*Ji+(this.low>>>0):this.high*Ji+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,c=h.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Ze(e)||(e=Ut(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Ze(e)||(e=Ut(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Mi)};C.neg=C.negate;C.add=function(e){Ze(e)||(e=Ut(e));var t=this.high>>>16,n=this.high&65535,r=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,h=e.low&65535,c=0,u=0,f=0,d=0;return d+=s+h,f+=d>>>16,d&=65535,f+=r+l,u+=f>>>16,f&=65535,u+=n+a,c+=u>>>16,u&=65535,c+=t+o,c&=65535,K(f<<16|d,c<<16|u,this.unsigned)};C.subtract=function(e){return Ze(e)||(e=Ut(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Ze(e)||(e=Ut(e)),Ot){var t=Ot.mul(this.low,this.high,e.low,e.high);return K(t,Ot.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?kn:Nt;if(this.eq(tt))return e.isOdd()?tt:Nt;if(e.eq(tt))return this.isOdd()?tt:Nt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Ru)&&e.lt(Ru))return yt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,h=e.low>>>16,c=e.low&65535,u=0,f=0,d=0,p=0;return p+=o*c,d+=p>>>16,p&=65535,d+=s*c,f+=d>>>16,d&=65535,d+=o*h,f+=d>>>16,d&=65535,f+=r*c,u+=f>>>16,f&=65535,f+=s*h,u+=f>>>16,f&=65535,f+=o*l,u+=f>>>16,f&=65535,u+=n*c+r*h+s*l+o*a,u&=65535,K(d<<16|p,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Ze(e)||(e=Ut(e)),e.isZero())throw Error("division by zero");if(Ot){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Ot.div_u:Ot.div_s)(this.low,this.high,e.low,e.high);return K(t,Ot.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?kn:Nt;var n,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return kn;if(e.gt(this.shru(1)))return ug;s=kn}else{if(this.eq(tt)){if(e.eq(Mi)||e.eq(Ul))return tt;if(e.eq(tt))return Mi;var o=this.shr(1);return n=o.div(e).shl(1),n.eq(Nt)?e.isNegative()?Mi:Ul:(r=this.sub(e.mul(n)),s=n.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?kn:Nt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Nt}for(r=this;r.gte(e);){n=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),l=a<=48?1:Uo(2,a-48),h=yt(n),c=h.mul(e);c.isNegative()||c.gt(r);)n-=l,h=yt(n,this.unsigned),c=h.mul(e);h.isZero()&&(h=Mi),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(Ze(e)||(e=Ut(e)),Ot){var t=(this.unsigned?Ot.rem_u:Ot.rem_s)(this.low,this.high,e.low,e.high);return K(t,Ot.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return K(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Qu(this.low):Qu(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Ze(e)||(e=Ut(e)),K(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Ze(e)||(e=Ut(e)),K(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Ze(e)||(e=Ut(e)),K(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Ze(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low<>>32-e,this.unsigned):K(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):K(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Ze(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?K(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?K(this.high,0,this.unsigned):K(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Ze(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(t=32-e,K(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,K(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Ze(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?K(this.high,this.low,this.unsigned):e<32?(t=32-e,K(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,K(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?K(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:K(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};Z.fromBytes=function(e,t,n){return n?Z.fromBytesLE(e,t):Z.fromBytesBE(e,t)};Z.fromBytesLE=function(e,t){return new Z(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Z.fromBytesBE=function(e,t){return new Z(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const xS=w.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);w.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:wn}]);w.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);w.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:QS,repeated:!0}]);const QS=w.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});w.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:PS,repeated:!0}]);const PS=w.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});w.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:AS,repeated:!0}]);const AS=w.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});w.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);w.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);w.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:$S,repeated:!0}]);const $S=w.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});w.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var S=(i=>(i.Ok="ok",i.ErrClientNotActivated="ErrClientNotActivated",i.ErrClientNotFound="ErrClientNotFound",i.ErrUnimplemented="ErrUnimplemented",i.ErrInvalidType="ErrInvalidType",i.ErrDummy="ErrDummy",i.ErrDocumentNotAttached="ErrDocumentNotAttached",i.ErrDocumentNotDetached="ErrDocumentNotDetached",i.ErrDocumentRemoved="ErrDocumentRemoved",i.ErrInvalidObjectKey="ErrInvalidObjectKey",i.ErrInvalidArgument="ErrInvalidArgument",i.ErrNotInitialized="ErrNotInitialized",i.ErrNotReady="ErrNotReady",i.ErrRefused="ErrRefused",i.ErrContextNotProvided="ErrContextNotProvided",i))(S||{});class v extends Error{constructor(t,n){super(n);b(this,"name","YorkieError");b(this,"stack");this.code=t,this.message=n,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function It(i){if(i instanceof Map){const e=Array.from(i);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(i))}const pg=i=>i?Object.entries(i).length===0:!0,Hi=i=>{const e={};for(const[t,n]of Object.entries(i))e[t]=JSON.stringify(n);return e},Ui=i=>{const e={};for(const[t,n]of Object.entries(i))e[t]=JSON.parse(n);return e};var Kn=(i=>(i.Put="put",i.Clear="clear",i))(Kn||{});class Ha{constructor(e,t){b(this,"context");b(this,"presence");this.context=e,this.presence=t}set(e,t){for(const n of Object.keys(e))this.presence[n]=e[n];this.context.setPresenceChange({type:"put",presence:It(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const xa="000000000000000000000000",CS="FFFFFFFFFFFFFFFFFFFFFFFF";class it{constructor(e,t,n){b(this,"lamport");b(this,"delimiter");b(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=n}static of(e,t,n){return new it(e,t,n)}static fromStruct(e){return it.of(Z.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new it(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Kh=0,RS=4294967295,IS=Z.MAX_VALUE,_t=new it(Z.fromNumber(0),Kh,xa);new it(Z.fromNumber(1),Kh+1,xa);const Vr=new it(IS,RS,CS);function hn(i){return i.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ks{constructor(e){b(this,"createdAt");b(this,"movedAt");b(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class zn extends ks{constructor(e){super(e)}}class ec{constructor(e,t){b(this,"strKey");b(this,"value");this.strKey=e,this.value=t}static of(e,t){return new ec(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Hr{constructor(){b(this,"nodeMapByKey");b(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Hr}set(e,t,n){let r;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(n)&&(r=s.getValue());const o=ec.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(s==null||n.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(n)),r}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new v(S.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(S.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class rt extends zn{constructor(t,n){super(t);b(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new rt(t,Hr.create());const r=Hr.create();for(const[s,o]of Object.entries(n))r.set(s,o.deepcopy(),o.getCreatedAt());return new rt(t,r)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,r){return this.memberNodes.set(t,n,r)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,r]of this)t.push(`"${hn(n)}":${r.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,r]of this){const{createdAt:s,value:o,type:a}=r.toJSForTest();t[n]={key:n,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var r;const t=Array();for(const[s]of this)t.push(s);const n=[];for(const s of t.sort()){const o=(r=this.memberNodes.get(s))==null?void 0:r.getValue();n.push(`"${hn(s)}":${o.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=rt.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const r=n.getValue();if(t(r,this))return;r instanceof zn&&r.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var re=(i=>(i.Local="local",i.Remote="remote",i.UndoRedo="undoredo",i))(re||{});class qt{constructor(e,t){b(this,"parentCreatedAt");b(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new v(S.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class gg{constructor(e){b(this,"value");b(this,"left");b(this,"right");b(this,"parent");b(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Kr{constructor(e){b(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new v(S.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return[t,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let t=0,n=e,r;for(;n;)(!r||r===n.getRight())&&(t+=n.getLength()+(n.hasLeft()?n.getLeftWeight():0)),r=n,n=n.getParent();return t-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Kr(e.getLeft());t.root&&t.root.setParent();const n=new Kr(e.getRight());if(n.root&&n.root.setParent(),t.root){const r=t.getRightmost();t.splayNode(r),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var Pe=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(Pe||{});class fe extends ks{constructor(t,n){super(n);b(this,"valueType");b(this,"value");this.valueType=fe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new fe(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Z.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Z.fromBytesLE(Array.from(n),!0).toNumber());default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${hn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=fe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Z)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return fe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=Z.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new v(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Lo extends gg{constructor(t){super(t);b(this,"prev");b(this,"next");this.value=t}static createAfter(t,n){const r=new Lo(n),s=t.next;return t.next=r,r.prev=t,r.next=s,s&&(s.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class es{constructor(){b(this,"dummyHead");b(this,"last");b(this,"nodeMapByIndex");b(this,"nodeMapByCreatedAt");const e=fe.of(0,_t);e.setRemovedAt(_t),this.dummyHead=new Lo(e),this.last=this.dummyHead,this.nodeMapByIndex=new Kr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new es}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new v(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,n),s=Lo.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,n){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||n.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),n),s.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),r=n.isRemoved();return n.remove(t)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class dt extends zn{constructor(t,n){super(t);b(this,"elements");this.elements=n}static create(t,n){if(!n)return new dt(t,es.create());const r=es.create();for(const s of n)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new dt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,r){this.elements.moveAfter(t,n,r)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const r=n.getValue();if(t(r,this))return;r instanceof zn&&r.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...d,value:d.value?{attributes:Ui(d.value.getAttributes()),content:d.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,n,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const d of h){const p=d.getCreatedAt().getActorID(),m=s!=null&&s.size?s.has(p)?s.get(p):_t:Vr;if(d.canStyle(r,m)){const g=c.get(p),y=d.getCreatedAt();(!g||y.after(g))&&c.set(p,y),u.push(d)}}const f=[];for(const d of u){if(d.isRemoved())continue;const[p,m]=this.rgaTreeSplit.findIndexesFromRange(d.createPosRange());l.push({type:"style",actor:r.getActorID(),from:p,to:m,value:{attributes:Ui(n)}});for(const[g,y]of Object.entries(n)){const[k]=d.getValue().setAttr(g,y,r);k!==void 0&&f.push({parent:d.getValue(),child:k})}}return[c,f,l]}indexRangeToPosRange(t,n){const r=this.rgaTreeSplit.indexToPos(t);return t===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();t.push({attributes:Ui(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Tt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())t.push(r)}return t}}class xs extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"content");b(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,n,r,s,o,a,l){return new xs(t,n,r,s,o,a,l)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Tt))throw new v(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${n},${r},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Qs extends qt{constructor(t,n,r,s,o,a){super(t,a);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,n,r,s,o,a){return new Qs(t,n,r,s,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Tt))throw new v(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${n},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const ES=2,DS="root",Tn="text";function br(i,e){let t=0;const n=i.children;for(let r=0;r0)throw new v(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Tn}get paddedSize(){return this.size+(this.isText?0:ES)}isAncestorOf(e){return MS(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=n;const s=this.cloneText(e+t);return s.value=r,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,n._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function MS(i,e){if(i===e)return!1;for(;e.parent;){if(e.parent===i)return!0;e=e.parent}return!1}var we=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(we||{});function mg(i,e,t,n){if(e>t)throw new v(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>i.size)throw new v(S.ErrInvalidArgument,`from is out of range: ${e} > ${i.size}`);if(t>i.size)throw new v(S.ErrInvalidArgument,`to is out of range: ${t} > ${i.size}`);if(e===t)return;let r=0;for(const s of i.children){if(e-s.paddedSizes.size;(s.isText||l)&&n([s,s.isText?"Text":"Start"],h),mg(s,Math.max(0,o),Math.min(a,s.size),n),h&&n([s,"End"],h)}r+=s.paddedSize}}function Og(i,e,t=0){for(const n of i.children)Og(n,e,t+1);e(i,t)}function Qa(i,e,t=0){for(const n of i._children)Qa(n,e,t+1);e(i,t)}function Ll(i,e,t=!0){if(e>i.size)throw new v(S.ErrInvalidArgument,`index is out of range: ${e} > ${i.size}`);if(i.isText)return{node:i,offset:e};let n=0,r=0;for(const s of i.children){if(t&&s.isText&&s.size>=e-r)return Ll(s,e-r,t);if(e===r)return{node:i,offset:n};if(!t&&s.paddedSize===e-r)return{node:i,offset:n+1};if(s.paddedSize>e-r)return Ll(s,e-r-1,t);r+=s.paddedSize,n+=1}return{node:i,offset:n}}function yg(i){return i.isText||i.children.length===0?i:yg(i.children[0])}function _S(i,e){if(i.sizei===e?0:i0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,s=t;for(;r&&s===r.left;)s=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new XS(e,t,!0);const r=this.comparator(e,n.key);return r<0?n.left=this.putInternal(e,t,n.left):r>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Mt{constructor(e,t){b(this,"parentID");b(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Mt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,r;return n.isText?(n.parent.children[0]===n&&t===0?r=n.parent:r=n,n=n.parent):t===0?r=n:r=n.children[t-1],Mt.of(n.id,_e.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Mt.of(_e.of(it.fromStruct(e.parentID.createdAt),e.parentID.offset),_e.of(it.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(n);if(!r||!s)throw new v(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[r,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class _e{constructor(e,t){b(this,"createdAt");b(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new _e(e,t)}static fromStruct(e){return _e.of(it.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=r.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new v(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ut(_e.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(_e.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,r){const s=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new An);const r=new Array;for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,n));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function Zl(i){var t;if(i.isText){const n=i;return{type:n.type,value:n.value}}const e={type:i.type,children:i.children.map(Zl)};return i.attrs&&(e.attributes=Ui((t=i.attrs)==null?void 0:t.toObject())),e}function tc(i){if(i.isText)return i.value;let e="";return i.attrs&&i.attrs.size()&&(e=" "+Array.from(i.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${hn(t.getValue())}"`}).join(" ")),`<${i.type}${e}>${i.children.map(t=>tc(t)).join("")}`}function Sg(i){if(i.isText){const e=i;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:i.type,children:i.children.map(Sg),size:i.size,isRemoved:i.isRemoved}}class xt extends ks{constructor(t,n){super(n);b(this,"indexTree");b(this,"nodeMapByID");this.indexTree=new VS(t),this.nodeMapByID=new bg(_e.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,n){return new xt(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[r,s]=t.toTreeNodePair(this);let o=s;const a=r===o,l=o.parent&&!a?o.parent:r;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const m=p.getCreatedAt().getActorID(),g=s?s.has(m)?s.get(m):_t:Vr;if(p.canStyle(r,g)&&n){const y=f.get(m),k=p.getCreatedAt();(!y||k.after(y))&&f.set(m,k);const $=p.setAttrs(n,r),T=$.reduce((I,[,W])=>(W&&(I[W.getKey()]=u[W.getKey()]),I),{}),Q=p.parent,A=p.prevSibling||p.parent;Object.keys(T).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(p,p),fromPath:this.toPath(Q,A),toPath:this.toPath(p,p),actor:r.getActorID(),value:T});for(const[I]of $)I&&d.push({parent:p,child:I})}}),[f,d,c]}removeStyle(t,n,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([d])=>{const p=d.getCreatedAt().getActorID(),m=s?s.has(p)?s.get(p):_t:Vr;if(d.canStyle(r,m)&&n){const g=u.get(p),y=d.getCreatedAt();(!g||y.after(g))&&u.set(p,y),d.attrs||(d.attrs=new An);for(const T of n){const Q=d.attrs.remove(T,r);for(const A of Q)f.push({parent:d,child:A})}const k=d.parent,$=d.prevSibling||d.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(d,d),fromPath:this.toPath(k,$),toPath:this.toPath(d,d),value:n})}}),[u,f,c]}edit(t,n,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),d=this.toPath(l,h),p=[],m=[],g=[],y=new Map;this.traverseInPosRange(l,h,c,u,([T,Q],A)=>{if(Q===we.Start&&!A)for(const L of T.children)g.push(L);const I=T.getCreatedAt().getActorID(),W=a?a.has(I)?a.get(I):_t:Vr;if(T.canDelete(s,W)||p.includes(T.parent)){const L=y.get(I),F=T.getCreatedAt();(!L||F.after(L))&&y.set(I,F),(Q===we.Text||Q===we.Start)&&p.push(T),m.push([T,Q])}});const k=this.makeDeletionChanges(m,s),$=[];for(const T of p)T.remove(s),T.isRemoved&&$.push({parent:this,child:T});for(const T of g)T.removedAt||l.append(T);if(r>0){let T=0,Q=l,A=h;for(;T{l.isRemoved&&(I.remove(s),$.push({parent:this,child:I})),this.nodeMapByID.put(I.id,I)}),A.isRemoved||T.push(A);if(T.length){const A=T.map(I=>Zl(I));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:d,toPath:d,actor:s.getActorID(),value:A})}}return[k,$,y]}editT(t,n,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],n,r,s,o)}move(t,n,r){throw new v(S.ErrUnimplemented,`not implemented: ${t}, ${n}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,r=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const r of n.getGCPairs())t.push(r)}),t}findPos(t,n=!0){const r=this.indexTree.findTreePos(t,n);return Mt.fromTreePos(r)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(r,s=void 0,o=void 0,a=0)=>{var d,p,m,g;let l,h,c;const u=r.isText?{node:r,offset:0}:s&&o?this.toTreePos(s,o):null;u&&(l=this.indexTree.indexOf(u),h=this.indexTree.treePosToPath(u),c=Mt.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(d=r.removedAt)==null?void 0:d.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(m=r.insNextID)==null?void 0:m.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?Ui((g=r.attrs)==null?void 0:g.toObject()):void 0,index:l,path:h,pos:c};for(let y=0;y0&&y===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(g,d)):r.push({type:"content",from:y,to:k,fromPath:this.toPath(m,u),toPath:this.toPath(g,d),actor:n.getActorID()}))}return r.reverse()}findRightToken([t,n]){if(n===we.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?we.Text:we.Start]:[t,we.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,we.End];const a=s[o+1];return[a,a.isText?we.Text:we.Start]}findLeftToken([t,n]){if(n===we.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?we.Text:we.End]}return[t,we.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,we.Start];const a=s[o-1];return[a,a.isText?we.Text:we.End]}}class Ps extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"contents");b(this,"splitLevel");b(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,r,s,o,a,l){return new Ps(t,n,r,s,o,a,l)}execute(t){var l;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof xt))throw new v(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=n,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>it.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:d,toPath:p})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:d,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${n},${r},${s.map(o=>tc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Bn{constructor(e,t,n,r){b(this,"clientSeq");b(this,"serverSeq");b(this,"lamport");b(this,"actor");this.clientSeq=e,this.serverSeq=r,this.lamport=t,this.actor=n}static of(e,t,n,r){return new Bn(e,t,n,r)}next(){return new Bn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new Bn(this.clientSeq,e,this.actor):new Bn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return it.of(this.lamport,e,this.actor)}setActor(e){return new Bn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const US=new Bn(0,Z.fromInt(0,!0),xa);class Ki{constructor({id:e,operations:t,presenceChange:n,message:r}){b(this,"id");b(this,"operations");b(this,"presenceChange");b(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=r}static create({id:e,operations:t,presenceChange:n,message:r}){return new Ki({id:e,operations:t,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===Kn.Put?t.set(this.id.getActorID(),It(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:Ae.bytesToHex(Ae.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>Ae.bytesToHex(Ae.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:r,message:s}=e;return Ki.create({id:Ae.bytesToChangeID(Ae.hexToBytes(t)),operations:n==null?void 0:n.map(o=>Ae.bytesToOperation(Ae.hexToBytes(o))),presenceChange:r,message:s})}}class Pa{constructor(e,t,n,r,s,o){b(this,"documentKey");b(this,"checkpoint");b(this,"isRemoved");b(this,"changes");b(this,"snapshot");b(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=o}static create(e,t,n,r,s,o){return new Pa(e,t,n,r,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Li{constructor(e,t){b(this,"serverSeq");b(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new Li(e,t)}increaseClientSeq(e){return e===0?this:new Li(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return Li.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const LS=new Li(Z.fromInt(0,!0),0);class dn{constructor(e,t){b(this,"createdAt");b(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new dn(e,t)}static fromStruct(e){return dn.of(it.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new dn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const ZS=dn.of(_t,0);class Vt{constructor(e,t){b(this,"id");b(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Vt(e,t)}static fromStruct(e){const t=dn.fromStruct(e.id);return Vt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return dn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Fn extends gg{constructor(t,n,r){super(n);b(this,"id");b(this,"removedAt");b(this,"prev");b(this,"next");b(this,"insPrev");b(this,"insNext");this.id=t,this.removedAt=r}static create(t,n){return new Fn(t,n)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let r=e;for(;r&&r!==t;)n.push(r),r=r.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new v(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const r=e.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,n),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,n){const r=!!n,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?n.has(c)?n.get(c):_t:Vr;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let r,s;for(let o=0;oi<0?Math.ceil(i):Math.floor(i);var gn=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(gn||{});class pt extends ks{constructor(t,n,r){super(r);b(this,"valueType");b(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Z.fromNumber(n).toInt():this.value=Iu(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Z.fromNumber(n):this.value=n;break;default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,r){return new pt(t,n,r)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Z.fromBytesLE(Array.from(n));default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=pt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Z?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!pt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new v(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===Pe.Long?this.value=this.value+t.getValue().toInt():this.value=Z.fromNumber(this.value+Iu(t.getValue())).toInt(),this}}class tr extends qt{constructor(t,n,r){super(t,r);b(this,"value");this.value=n}static create(t,n,r){return new tr(t,n,r)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof pt))throw new v(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,s=this.value.deepcopy();return r.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===Pe.Long?t.getValue().multiply(-1):t.getValue()*-1;return tr.create(this.getParentCreatedAt(),fe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class xn extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"attributes");b(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,n,r,s,o,a){return new xn(t,n,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,r,s,o,a){return new xn(t,n,r,s,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof xt))throw new v(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function WS(i){const e=new Jh,t=e.data;for(const[n,r]of Object.entries(i))t[n]=JSON.stringify(r);return e}function jS(i){if(i.type===Kn.Put)return new Bl({type:Jr.PUT,presence:WS(i.presence)});if(i.type===Kn.Clear)return new Bl({type:Jr.CLEAR});throw new v(S.ErrUnimplemented,"unimplemented type")}function zS(i){return new hg({serverSeq:i.getServerSeqAsString(),clientSeq:i.getClientSeq()})}function wg(i){return new ka({clientSeq:i.getClientSeq(),lamport:i.getLamportAsString(),actorId:lc(i.getActorID())})}function V(i){if(i)return new X({lamport:i.getLamportAsString(),delimiter:i.getDelimiter(),actorId:lc(i.getActorID())})}function vg(i){switch(i){case Pe.Null:return G.NULL;case Pe.Boolean:return G.BOOLEAN;case Pe.Integer:return G.INTEGER;case Pe.Long:return G.LONG;case Pe.Double:return G.DOUBLE;case Pe.String:return G.STRING;case Pe.Bytes:return G.BYTES;case Pe.Date:return G.DATE;default:throw new v(S.ErrInvalidType,`unsupported type: ${i}`)}}function kg(i){switch(i){case gn.IntegerCnt:return G.INTEGER_CNT;case gn.LongCnt:return G.LONG_CNT;default:throw new v(S.ErrInvalidType,`unsupported type: ${i}`)}}function Ka(i){if(i instanceof rt)return new yn({type:G.JSON_OBJECT,createdAt:V(i.getCreatedAt()),value:Mg(i)});if(i instanceof dt)return new yn({type:G.JSON_ARRAY,createdAt:V(i.getCreatedAt()),value:v1(i)});if(i instanceof Tt)return new yn({type:G.TEXT,createdAt:V(i.getCreatedAt())});if(i instanceof fe)return new yn({type:vg(i.getType()),createdAt:V(i.getCreatedAt()),value:i.toBytes()});if(i instanceof pt)return new yn({type:kg(i.getType()),createdAt:V(i.getCreatedAt()),value:i.toBytes()});if(i instanceof xt)return new yn({type:G.TREE,createdAt:V(i.getCreatedAt()),value:T1(i)});throw new v(S.ErrUnimplemented,"unimplemented element")}function FS(i){return new Xl({createdAt:V(i.getCreatedAt()),offset:i.getOffset()})}function Xs(i){return new wi({createdAt:V(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function Bs(i){return new Yr({parentId:qr(i.getParentID()),leftSiblingId:qr(i.getLeftSiblingID())})}function qr(i){return new Bi({createdAt:V(i.getCreatedAt()),offset:i.getOffset()})}function Tg(i){const e=new Fh;if(i instanceof vi){const t=i,n=new Wp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.key=t.getKey(),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(i instanceof Ts){const t=i,n=new jp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.prevCreatedAt=V(t.getPrevCreatedAt()),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(i instanceof Ln){const t=i,n=new zp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.prevCreatedAt=V(t.getPrevCreatedAt()),n.createdAt=V(t.getCreatedAt()),n.executedAt=V(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(i instanceof ei){const t=i,n=new Fp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.createdAt=V(t.getCreatedAt()),n.executedAt=V(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(i instanceof xs){const t=i,n=new Gp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Xs(t.getFromPos()),n.to=Xs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);n.content=t.getContent();const s=n.attributes;for(const[o,a]of t.getAttributes())s[o]=a;n.executedAt=V(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(i instanceof Qs){const t=i,n=new Yp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Xs(t.getFromPos()),n.to=Xs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);const s=n.attributes;for(const[o,a]of t.getAttributes())s[o]=a;n.executedAt=V(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(i instanceof tr){const t=i,n=new Jp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(i instanceof Ps){const t=i,n=new Hp,r=n.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=V(o);n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Bs(t.getFromPos()),n.to=Bs(t.getToPos()),n.contents=t1(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=V(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(i instanceof xn){const t=i,n=new Kp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Bs(t.getFromPos()),n.to=Bs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);const s=t.getAttributesToRemove();if(s.length>0)n.attributesToRemove=s;else{const o=n.attributes;for(const[a,l]of t.getAttributes())o[a]=l}n.executedAt=V(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new v(S.ErrUnimplemented,"unimplemented operation");return e}function GS(i){const e=[];for(const t of i)e.push(Tg(t));return e}function YS(i){const e=new Zp({id:wg(i.getID()),message:i.getMessage()});return i.hasOperations()&&(e.operations=GS(i.getOperations())),i.hasPresenceChange()&&(e.presenceChange=jS(i.getPresenceChange())),e}function JS(i){const e=[];for(const t of i)e.push(YS(t));return e}function HS(i){const e=[];for(const t of i)e.push(new og({key:t.getStrKey(),element:ic(t.getValue())}));return e}function KS(i){const e=[];for(const t of i)e.push(new Gh({element:ic(t.getValue())}));return e}function e1(i){const e=[];for(const t of i){const n=new ag;n.id=FS(t.getID()),n.value=t.getValue().getContent(),n.removedAt=V(t.getRemovedAt());const r=n.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new Ta;a.value=o.getValue(),a.updatedAt=V(o.getUpdatedAt()),r[o.getKey()]=a}e.push(n)}return e}function t1(i){const e=[];if(!i||!i.length)return e;for(const t of i)e.push(new lg({content:nc(t)}));return e}function n1(i){const e={};for(const t of i)e[t.getKey()]=new Ta({value:t.getValue(),updatedAt:V(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function nc(i){if(!i)return[];const e=[];return Qa(i,(t,n)=>{const r=new Yh({id:qr(t.id),type:t.type,removedAt:V(t.removedAt),depth:n});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=qr(t.insPrevID)),t.insNextID&&(r.insNextId=qr(t.insNextID)),t.attrs&&(r.attributes=n1(t.attrs)),e.push(r)}),e}function i1(i){const e=new Pt;return e.body.case="jsonObject",e.body.value=new eg({nodes:HS(i.getRHT()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function xg(i){const e=new Pt;return e.body.case="jsonArray",e.body.value=new tg({nodes:KS(i.getElements()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function r1(i){const e=new Pt;return e.body.case="primitive",e.body.value=new ng({type:vg(i.getType()),value:i.toBytes(),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function s1(i){const e=new Pt;return e.body.case="text",e.body.value=new ig({nodes:e1(i.getRGATreeSplit()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function o1(i){const e=new Pt;return e.body.case="counter",e.body.value=new rg({type:kg(i.getType()),value:i.toBytes(),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function Qg(i){const e=new Pt;return e.body.case="tree",e.body.value=new sg({nodes:nc(i.getRoot()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function ic(i){if(i instanceof rt)return i1(i);if(i instanceof dt)return xg(i);if(i instanceof fe)return r1(i);if(i instanceof Tt)return s1(i);if(i instanceof pt)return o1(i);if(i instanceof xt)return Qg(i);throw new v(S.ErrUnimplemented,"unimplemented element")}function a1(i){return new En({documentKey:i.getDocumentKey(),checkpoint:zS(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:JS(i.getChanges()),snapshot:i.getSnapshot(),minSyncedTicket:V(i.getMinSyncedTicket())})}function Eu(i){const e=i.findDetails(xS);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Pg(i){let e;return i.serverSeq&&(e=Z.fromString(i.serverSeq,!0)),Bn.of(i.clientSeq,Z.fromString(i.lamport,!0),ac(i.actorId),e)}function q(i){if(i)return it.of(Z.fromString(i.lamport,!0),i.delimiter,ac(i.actorId))}function rc(i){const e={};return Object.entries(i.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function l1(i){const e=i.type;if(e===Jr.PUT){const t=rc(i.presence);return{type:Kn.Put,presence:t}}if(e===Jr.CLEAR)return{type:Kn.Clear};throw new v(S.ErrInvalidType,`unsupported type: ${e}`)}function h1(i){const e=new Map;return Object.entries(i).forEach(([t,n])=>{e.set(t,rc(n))}),e}function Ag(i){switch(i){case G.NULL:return Pe.Null;case G.BOOLEAN:return Pe.Boolean;case G.INTEGER:return Pe.Integer;case G.LONG:return Pe.Long;case G.DOUBLE:return Pe.Double;case G.STRING:return Pe.String;case G.BYTES:return Pe.Bytes;case G.DATE:return Pe.Date}throw new v(S.ErrUnimplemented,`unimplemented value type: ${i}`)}function Zo(i){switch(i){case G.INTEGER_CNT:return gn.IntegerCnt;case G.LONG_CNT:return gn.LongCnt}throw new v(S.ErrUnimplemented,`unimplemented value type: ${i}`)}function el(i){switch(i.type){case G.JSON_OBJECT:return i.value?Ng(i.value):rt.create(q(i.createdAt));case G.JSON_ARRAY:return i.value?w1(i.value):dt.create(q(i.createdAt));case G.TEXT:return Tt.create(er.create(),q(i.createdAt));case G.TREE:return k1(i.value);case G.NULL:case G.BOOLEAN:case G.INTEGER:case G.LONG:case G.DOUBLE:case G.STRING:case G.BYTES:case G.DATE:return fe.of(fe.valueFromBytes(Ag(i.type),i.value),q(i.createdAt));case G.INTEGER_CNT:case G.LONG_CNT:return pt.create(Zo(i.type),pt.valueFromBytes(Zo(i.type),i.value),q(i.createdAt))}}function Us(i){return Vt.of(dn.of(q(i.createdAt),i.offset),i.relativeOffset)}function $g(i){return dn.of(q(i.createdAt),i.offset)}function c1(i){const e=ts.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{e.setAttr(n,r.value,q(r.updatedAt))});const t=Fn.create($g(i.id),e);return t.remove(q(i.removedAt)),t}function Ri(i){return Mt.of(Xr(i.parentId),Xr(i.leftSiblingId))}function Xr(i){return _e.of(q(i.createdAt),i.offset)}function u1(i){if(!i.length)return;const e=[];return i.forEach(t=>{const n=sc(t.content);e.push(n)}),e}function sc(i){if(i.length===0)return;const e=[];for(const r of i)e.push(d1(r));const t=e[e.length-1],n=new Map;n.set(i[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(e[r]),n.set(i[r].depth,e[r]);return t.updateDescendantsSize(),xt.create(t,_t).getRoot()}function f1(i){const e=An.create();for(const[t,n]of Object.entries(i))e.setInternal(t,n.value,q(n.updatedAt),n.isRemoved);return e}function d1(i){const e=Xr(i.id),t=ut.create(e,i.type),n=Object.entries(i.attributes);return t.isText?t.value=i.value:n.length&&(t.attrs=f1(i.attributes)),i.insPrevId&&(t.insPrevID=Xr(i.insPrevId)),i.insNextId&&(t.insNextID=Xr(i.insNextId)),t.removedAt=q(i.removedAt),t}function Cg(i){if(i.body.case==="set"){const e=i.body.value;return vi.create(e.key,el(e.value),q(e.parentCreatedAt),q(e.executedAt))}else if(i.body.case==="add"){const e=i.body.value;return Ts.create(q(e.parentCreatedAt),q(e.prevCreatedAt),el(e.value),q(e.executedAt))}else if(i.body.case==="move"){const e=i.body.value;return Ln.create(q(e.parentCreatedAt),q(e.prevCreatedAt),q(e.createdAt),q(e.executedAt))}else if(i.body.case==="remove"){const e=i.body.value;return ei.create(q(e.parentCreatedAt),q(e.createdAt),q(e.executedAt))}else if(i.body.case==="edit"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,q(s))});const n=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{n.set(r,s)}),xs.create(q(e.parentCreatedAt),Us(e.from),Us(e.to),t,e.content,n,q(e.executedAt))}else if(i.body.case==="style"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,q(s))});const n=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{n.set(r,s)}),Qs.create(q(e.parentCreatedAt),Us(e.from),Us(e.to),t,n,q(e.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const e=i.body.value;return tr.create(q(e.parentCreatedAt),el(e.value),q(e.executedAt))}else if(i.body.case==="treeEdit"){const e=i.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,r])=>{t.set(n,q(r))}),Ps.create(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),u1(e.contents),e.splitLevel,t,q(e.executedAt))}else if(i.body.case==="treeStyle"){const e=i.body.value,t=new Map,n=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,q(o))}),(n==null?void 0:n.length)>0?xn.createTreeRemoveStyleOperation(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),r,n,q(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),xn.create(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),r,t,q(e.executedAt)))}else throw new v(S.ErrUnimplemented,"unimplemented operation")}}function p1(i){const e=[];for(const t of i){const n=Cg(t);n&&e.push(n)}return e}function Rg(i){const e=[];for(const t of i)e.push(Ki.create({id:Pg(t.id),operations:p1(t.operations),presenceChange:t.presenceChange?l1(t.presenceChange):void 0,message:t.message}));return e}function g1(i){return Li.of(Z.fromString(i.serverSeq,!0),i.clientSeq)}function m1(i){return Pa.create(i.documentKey,g1(i.checkpoint),i.isRemoved,Rg(i.changes),i.snapshot,q(i.minSyncedTicket))}function Ig(i){const e=new Hr;for(const n of i.nodes){const r=oc(n.element);e.set(n.key,r,r.getPositionedAt())}const t=new rt(q(i.createdAt),e);return t.setMovedAt(q(i.movedAt)),t.setRemovedAt(q(i.removedAt)),t}function Eg(i){const e=new es;for(const n of i.nodes)e.insert(oc(n.element));const t=new dt(q(i.createdAt),e);return t.setMovedAt(q(i.movedAt)),t.setRemovedAt(q(i.removedAt)),t}function O1(i){const e=fe.of(fe.valueFromBytes(Ag(i.type),i.value),q(i.createdAt));return e.setMovedAt(q(i.movedAt)),e.setRemovedAt(q(i.removedAt)),e}function y1(i){const e=new er;let t=e.getHead();for(const r of i.nodes){const s=e.insertAfter(t,c1(r));r.insPrevId&&s.setInsPrev(e.findNode($g(r.insPrevId))),t=s}const n=new Tt(e,q(i.createdAt));return n.setMovedAt(q(i.movedAt)),n.setRemovedAt(q(i.removedAt)),n}function b1(i){const e=pt.create(Zo(i.type),pt.valueFromBytes(Zo(i.type),i.value),q(i.createdAt));return e.setMovedAt(q(i.movedAt)),e.setRemovedAt(q(i.removedAt)),e}function Dg(i){const e=sc(i.nodes);return xt.create(e,q(i.createdAt))}function oc(i){if(i.body.case==="jsonObject")return Ig(i.body.value);if(i.body.case==="jsonArray")return Eg(i.body.value);if(i.body.case==="primitive")return O1(i.body.value);if(i.body.case==="text")return y1(i.body.value);if(i.body.case==="counter")return b1(i.body.value);if(i.body.case==="tree")return Dg(i.body.value);throw new v(S.ErrUnimplemented,"unimplemented element")}function S1(i){if(!i)return{root:rt.create(_t),presences:new Map};const e=tS.fromBinary(i);return{root:oc(e.root),presences:h1(e.presences)}}function Ng(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Ig(e.body.value)}function Mg(i){return ic(i).toBinary()}function w1(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Eg(e.body.value)}function v1(i){return xg(i).toBinary()}function k1(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Dg(e.body.value)}function T1(i){return Qg(i).toBinary()}function _g(i){return i?Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ac(i){return _g(i)}function Vg(i){return new Uint8Array(i.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lc(i){return Vg(i)}function x1(i){const e=ka.fromBinary(i);return Pg(e)}function Q1(i){const e=Fh.fromBinary(i);return Cg(e)}const Ae={fromPresence:rc,toChangePack:a1,fromChangePack:m1,fromChanges:Rg,toTreeNodes:nc,fromTreeNodes:sc,objectToBytes:Mg,bytesToObject:Ng,bytesToSnapshot:S1,bytesToHex:_g,hexToBytes:Vg,toHexString:ac,toUint8Array:lc,toOperation:Tg,toChangeID:wg,PbChangeID:ka,bytesToChangeID:x1,bytesToOperation:Q1};var Fe=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(Fe||{});let ui=3;function qg(i){ui=i}const B={trivial:(...i)=>{ui>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{ui>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{ui>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{ui>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{ui>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>ui<=i};function Xg(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}class P1{constructor(e,t,n,r,s){b(this,"reconnectStreamDelay");b(this,"doc");b(this,"docID");b(this,"syncMode");b(this,"remoteChangeEventReceived");b(this,"watchStream");b(this,"watchLoopTimerID");b(this,"watchAbortController");b(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===xo.RealtimeSyncOff?!1:this.syncMode===xo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==xo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const tl=()=>{};class A1{constructor(e){b(this,"finalized",!1);b(this,"observers",[]);b(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(!e)throw new v(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:n},r.next===void 0&&(r.next=tl),r.error===void 0&&(r.error=tl),r.complete===void 0&&(r.complete=tl);const s=Xg(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(a){B.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class _i{constructor(e,t,n,r){b(this,"id");b(this,"delimiter");b(this,"message");b(this,"root");b(this,"operations");b(this,"presenceChange");b(this,"previousPresence");b(this,"reversePresenceKeys");this.id=e,this.delimiter=Kh,this.root=t,this.operations=[],this.previousPresence=It(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,n,r){return new _i(e,t,n,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Ki.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class ns{constructor(e){b(this,"rootObject");b(this,"elementPairMapByCreatedAt");b(this,"gcElementSetByCreatedAt");b(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Tt||t instanceof xt)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new ns(rt.create(_t))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(S.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof zn&&e.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(e){let t=0;const n=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return n(e),e instanceof zn&&e.getDescendants(r=>(n(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof zn&&n.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new ns(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n);r.element.getRemovedAt()&&e.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r!==void 0&&e.compare(r)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Bg(i,e){const t=new is(i);return new Proxy(e,t.getHandlers())}class is{constructor(e){b(this,"context");b(this,"handlers");this.context=e,this.handlers={set:(t,n,r)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]=${JSON.stringify(r)}`),is.setInternal(e,t,n,r),!0),get:(t,n)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():fi(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]`),is.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,r){if(n.includes("."))throw new v(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=Wo(e,r,s),a=t.set(n,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(vi.create(n,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const n={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Wo(e,s,o);n[r]=a}return n}static deleteInternal(e,t,n){const r=e.issueTimeTicket(),s=t.deleteByKey(n,r);s&&(e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function C1(i,e){const t=new pe(i,e);return new Proxy(e,t.getHandlers())}function R1(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function I1(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class pe{constructor(e,t){b(this,"context");b(this,"handlers");b(this,"array");this.context=e,this.array=t,this.handlers={get:(n,r,s)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=n.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,n.getLast()):r==="deleteByID"?o=>{const a=pe.deleteInternalByID(e,n,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=pe.insertAfterInternal(e,n,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=pe.insertBeforeInternal(e,n,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{pe.moveBeforeInternal(e,n,o,a)}:r==="moveAfter"?(o,a)=>{pe.moveAfterInternal(e,n,o,a)}:r==="moveFront"?o=>{pe.moveFrontInternal(e,n,o)}:r==="moveLast"?o=>{pe.moveLastInternal(e,n,o)}:R1(r)?fi(e,n.get(Number(r))):r==="push"?o=>pe.pushInternal(e,n,o):r==="splice"?(o,a,...l)=>pe.splice(e,n,o,a,...l):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?pe.iteratorInternal.bind(this,e,n):r==="includes"?(o,a)=>pe.includes(e,n,o,a):r==="indexOf"?(o,a)=>pe.indexOf(e,n,o,a):r==="lastIndexOf"?(o,a)=>pe.lastIndexOf(e,n,o,a):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>pe.toTestString(n):typeof r=="string"&&I1(r)?(...o)=>{const a=Array.from(n).map(l=>fi(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(n,r,s),deleteProperty:(n,r)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`array[${r}]`),pe.deleteInternalByIndex(e,n,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield _n(e,n)}static buildArrayElements(e,t){const n=[];for(const r of t){const s=e.issueTimeTicket(),o=Wo(e,r,s);n.push(o)}return n}static pushInternal(e,t,n){return pe.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,r,s),e.push(Ln.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,n,r){const s=e.issueTimeTicket();t.moveAfter(n,r,s),e.push(Ln.create(t.getCreatedAt(),n,r,s))}static moveFrontInternal(e,t,n){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),n,r),e.push(Ln.create(t.getCreatedAt(),s.getCreatedAt(),n,r))}static moveLastInternal(e,t,n){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,n,r),e.push(Ln.create(t.getCreatedAt(),s,n,r))}static insertAfterInternal(e,t,n,r){const s=e.issueTimeTicket(),o=Wo(e,r,s);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Ts.create(t.getCreatedAt(),n,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,n,r){return pe.insertAfterInternal(e,t,t.getPrevCreatedAt(n),r)}static deleteInternalByIndex(e,t,n){const r=e.issueTimeTicket(),s=t.deleteByIndex(n,r);if(s)return e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,n){const r=e.issueTimeTicket(),s=t.delete(n,r);return e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,n,r,...s){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).includes(n,o);for(let l=o;l=s)return-1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).indexOf(n,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).lastIndexOf(n,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===n.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let Aa=class{constructor(e,t){b(this,"context");b(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,r){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);B.isEnabled(Fe.Debug)&&B.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${n}`);const o=r?Hi(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,n,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new xs(this.text.getCreatedAt(),s[0],s[1],l,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);B.isEnabled(Fe.Debug)&&B.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const s=Hi(n),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(r,s,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Qs(this.text.getCreatedAt(),r[0],r[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Vt.fromStruct(e[0]),Vt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class $a{constructor(e,t){b(this,"valueType");b(this,"value");b(this,"context");b(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new v(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=fe.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(tr.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function hc(i,e,t){const{type:n}=i,r=t.issueTimeTicket();if(n===Tn){Ug(i);const{value:s}=i,o=ut.create(_e.of(r,0),n,s);e.append(o)}else{const{children:s=[]}=i,{attributes:o}=i;let a;if(typeof o=="object"&&!pg(o)){const h=Hi(o);a=new An;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(_e.of(r,0),n,void 0,a);e.append(l);for(const h of s)hc(h,l,t)}}function E1(i,e){const{type:t}=e,n=i.issueTimeTicket();let r;if(e.type===Tn){const{value:s}=e;r=ut.create(_e.of(n,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!pg(o)){const l=Hi(o);a=new An;for(const[h,c]of Object.entries(l))a.set(h,c,n)}r=ut.create(_e.of(i.issueTimeTicket(),0),t,void 0,a);for(const l of s)hc(l,r,i)}return r}function Ug(i){if(!i.value.length)throw new v(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function Du(i){if(!i.length)return!0;if(i[0].type===Tn)for(const t of i){const{type:n}=t;if(n!==Tn)throw new v(S.ErrInvalidArgument,"element node and text node cannot be passed together");Ug(t)}else for(const t of i){const{type:n}=t;if(n===Tn)throw new v(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let Ca=class{constructor(e){b(this,"initialRoot");b(this,"context");b(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ut.create(_e.of(e.issueTimeTicket(),0),DS);const t=ut.create(_e.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)hc(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?Hi(t):void 0,[a]=this.tree.style([n,r],o,s);this.context.push(xn.create(this.tree.getCreatedAt(),n,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,n){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?Hi(n):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(xn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([r,s],n,o);for(const h of l)this.context.registerGCPair(h);this.context.push(xn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,n,o))}editInternal(e,t,n,r=0){var h;if(n.length!==0&&n[0]&&(Du(n),n[0].type!==Tn))for(const c of n){const{children:u=[]}=c;Du(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=n[0])==null?void 0:h.type)===Tn){let c="";for(const u of n){const{value:f}=u;c+=f}o.push(ut.create(_e.of(this.context.issueTimeTicket(),0),Tn,c))}else o=n.map(c=>c&&E1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,t],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,r,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(Ps.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,n?[n]:[],r)}editBulkByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,n,r)}edit(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,n?[n]:[],r)}editBulk(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,n,r)}toXML(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Mt.fromStruct(e[0]),Mt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Mt.fromStruct(e[0]),Mt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Nu(i,e){return Bg(i,e)}function _n(i,e){if(e){if(e instanceof fe)return e;if(e instanceof rt)return Bg(i,e);if(e instanceof dt)return C1(i,e);if(e instanceof Tt)return new Aa(i,e);if(e instanceof pt){const t=new $a(gn.IntegerCnt,0);return t.initialize(i,e),t}else if(e instanceof xt){const t=new Ca;return t.initialize(i,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function fi(i,e){const t=_n(i,e);return t instanceof fe?t.getValue():t}function Wo(i,e,t){let n;if(fe.isSupport(e))n=fe.of(e,t);else if(Array.isArray(e))n=dt.create(t,pe.buildArrayElements(i,e));else if(typeof e=="object")e instanceof Aa?(n=Tt.create(er.create(),t),e.initialize(i,n)):e instanceof $a?(n=pt.create(e.getValueType(),e.getValue(),t),e.initialize(i,n)):e instanceof Ca?(n=xt.create(e.buildRoot(i),t),e.initialize(i,n)):n=rt.create(t,is.buildObjectMembers(i,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Mu=50;class D1{constructor(){b(this,"undoStack",[]);b(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Mu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Mu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const N1="yorkie-devtools-panel",M1="yorkie-devtools-sdk";let Ei="disconnected";const _u=new Map,To=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=To);function Ls(i,e){(e!=null&&e.force||Ei!=="disconnected")&&window.postMessage({source:M1,...i},"*")}function _1(i){if(!i.isEnableDevtools()||typeof window>"u"||_u.has(i.getKey()))return;To.set(i.getKey(),[]);const e=i.subscribe("all",t=>{t.some(n=>n.type!==ze.StatusChanged&&n.type!==ze.Snapshot&&n.type!==ze.LocalChange&&n.type!==ze.RemoteChange&&n.type!==ze.Initialized&&n.type!==ze.Watched&&n.type!==ze.Unwatched&&n.type!==ze.PresenceChanged)||(To.get(i.getKey()).push(t),Ei==="synced"&&Ls({msg:"doc::sync::partial",docKey:i.getKey(),event:t}))});_u.set(i.getKey(),[e]),Ls({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==N1)return;switch(t.data.msg){case"devtools::connect":if(Ei!=="disconnected")break;Ei="connected",Ls({msg:"doc::available",docKey:i.getKey()}),B.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Ei="disconnected",B.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Ei="synced",Ls({msg:"doc::sync::full",docKey:i.getKey(),events:To.get(i.getKey())}),B.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var Vn=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(Vn||{}),ze=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(ze||{}),rs=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(rs||{}),Wl=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(Wl||{});class Lg{constructor(e,t){b(this,"key");b(this,"status");b(this,"opts");b(this,"changeID");b(this,"checkpoint");b(this,"localChanges");b(this,"root");b(this,"clone");b(this,"eventStream");b(this,"eventStreamObserver");b(this,"onlineClients");b(this,"presences");b(this,"history");b(this,"internalHistory");b(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=ns.create(),this.changeID=US,this.checkpoint=LS,this.localChanges=[],this.eventStream=$1(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new D1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},_1(this)}update(e,t){if(this.getStatus()==="removed")throw new v(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const s=Nu(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(s,new Ha(r,this.clone.presences.get(n)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){B.isEnabled(Fe.Trivial)&&B.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,re.Local),l=r.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const h=[];o.length>0&&h.push({type:"local-change",source:re.Local,value:{message:s.getMessage()||"",operations:o,actor:n,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:re.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(h),B.isEnabled(Fe.Trivial)&&B.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,r){if(typeof e=="string"){if(typeof t!="function")throw new v(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||a(h)},n,r)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||a(h)},n,r)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&a(h)},n,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},n,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},n,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},n,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,r)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&h.push(c);h.length&&o({...l,value:{...l.value,operations:h}})}},n,r)}if(typeof e=="function"){const s=e,o=t,a=n;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||s(h)},o,a)}throw new v(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((s,o)=>s===n[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),re.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,re.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),B.isEnabled(Fe.Trivial)&&B.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:It(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Pa.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Nu(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:r}=Ae.bytesToSnapshot(t);this.root=new ns(n),this.presences=r,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:re.Remote,value:{snapshot:this.isEnableDevtools()?Ae.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){B.isEnabled(Fe.Debug)&&B.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),B.isEnabled(Fe.Trivial)&&B.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ks{constructor(e){b(this,"createdAt");b(this,"movedAt");b(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class zn extends ks{constructor(e){super(e)}}class ec{constructor(e,t){b(this,"strKey");b(this,"value");this.strKey=e,this.value=t}static of(e,t){return new ec(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Hr{constructor(){b(this,"nodeMapByKey");b(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Hr}set(e,t,n){let r;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(n)&&(r=s.getValue());const o=ec.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(s==null||n.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(n)),r}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new v(S.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(S.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class rt extends zn{constructor(t,n){super(t);b(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new rt(t,Hr.create());const r=Hr.create();for(const[s,o]of Object.entries(n))r.set(s,o.deepcopy(),o.getCreatedAt());return new rt(t,r)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,r){return this.memberNodes.set(t,n,r)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,r]of this)t.push(`"${hn(n)}":${r.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,r]of this){const{createdAt:s,value:o,type:a}=r.toJSForTest();t[n]={key:n,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var r;const t=Array();for(const[s]of this)t.push(s);const n=[];for(const s of t.sort()){const o=(r=this.memberNodes.get(s))==null?void 0:r.getValue();n.push(`"${hn(s)}":${o.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=rt.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const r=n.getValue();if(t(r,this))return;r instanceof zn&&r.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var re=(i=>(i.Local="local",i.Remote="remote",i.UndoRedo="undoredo",i))(re||{});class qt{constructor(e,t){b(this,"parentCreatedAt");b(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new v(S.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class gg{constructor(e){b(this,"value");b(this,"left");b(this,"right");b(this,"parent");b(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Kr{constructor(e){b(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new v(S.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return this.splayNode(t),[t,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Kr(e.getLeft());t.root&&t.root.setParent();const n=new Kr(e.getRight());if(n.root&&n.root.setParent(),t.root){const r=t.getRightmost();t.splayNode(r),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var Pe=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(Pe||{});class fe extends ks{constructor(t,n){super(n);b(this,"valueType");b(this,"value");this.valueType=fe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new fe(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Z.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Z.fromBytesLE(Array.from(n),!0).toNumber());default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${hn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=fe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Z)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return fe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=Z.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new v(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Lo extends gg{constructor(t){super(t);b(this,"prev");b(this,"next");this.value=t}static createAfter(t,n){const r=new Lo(n),s=t.next;return t.next=r,r.prev=t,r.next=s,s&&(s.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class es{constructor(){b(this,"dummyHead");b(this,"last");b(this,"nodeMapByIndex");b(this,"nodeMapByCreatedAt");const e=fe.of(0,_t);e.setRemovedAt(_t),this.dummyHead=new Lo(e),this.last=this.dummyHead,this.nodeMapByIndex=new Kr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new es}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new v(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,n),s=Lo.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,n){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||n.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),n),s.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),r=n.isRemoved();return n.remove(t)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class dt extends zn{constructor(t,n){super(t);b(this,"elements");this.elements=n}static create(t,n){if(!n)return new dt(t,es.create());const r=es.create();for(const s of n)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new dt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,r){this.elements.moveAfter(t,n,r)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const r=n.getValue();if(t(r,this))return;r instanceof zn&&r.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...d,value:d.value?{attributes:Ui(d.value.getAttributes()),content:d.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,n,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const d of h){const p=d.getCreatedAt().getActorID(),m=s!=null&&s.size?s.has(p)?s.get(p):_t:Vr;if(d.canStyle(r,m)){const g=c.get(p),y=d.getCreatedAt();(!g||y.after(g))&&c.set(p,y),u.push(d)}}const f=[];for(const d of u){if(d.isRemoved())continue;const[p,m]=this.rgaTreeSplit.findIndexesFromRange(d.createPosRange());l.push({type:"style",actor:r.getActorID(),from:p,to:m,value:{attributes:Ui(n)}});for(const[g,y]of Object.entries(n)){const[k]=d.getValue().setAttr(g,y,r);k!==void 0&&f.push({parent:d.getValue(),child:k})}}return[c,f,l]}indexRangeToPosRange(t,n){const r=this.rgaTreeSplit.indexToPos(t);return t===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();t.push({attributes:Ui(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Tt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())t.push(r)}return t}}class xs extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"content");b(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,n,r,s,o,a,l){return new xs(t,n,r,s,o,a,l)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Tt))throw new v(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${n},${r},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Qs extends qt{constructor(t,n,r,s,o,a){super(t,a);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,n,r,s,o,a){return new Qs(t,n,r,s,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Tt))throw new v(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${n},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const ES=2,DS="root",Tn="text";function br(i,e){let t=0;const n=i.children;for(let r=0;r0)throw new v(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Tn}get paddedSize(){return this.size+(this.isText?0:ES)}isAncestorOf(e){return MS(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=n;const s=this.cloneText(e+t);return s.value=r,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,n._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new v(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new v(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function MS(i,e){if(i===e)return!1;for(;e.parent;){if(e.parent===i)return!0;e=e.parent}return!1}var we=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(we||{});function mg(i,e,t,n){if(e>t)throw new v(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>i.size)throw new v(S.ErrInvalidArgument,`from is out of range: ${e} > ${i.size}`);if(t>i.size)throw new v(S.ErrInvalidArgument,`to is out of range: ${t} > ${i.size}`);if(e===t)return;let r=0;for(const s of i.children){if(e-s.paddedSizes.size;(s.isText||l)&&n([s,s.isText?"Text":"Start"],h),mg(s,Math.max(0,o),Math.min(a,s.size),n),h&&n([s,"End"],h)}r+=s.paddedSize}}function Og(i,e,t=0){for(const n of i.children)Og(n,e,t+1);e(i,t)}function Qa(i,e,t=0){for(const n of i._children)Qa(n,e,t+1);e(i,t)}function Ll(i,e,t=!0){if(e>i.size)throw new v(S.ErrInvalidArgument,`index is out of range: ${e} > ${i.size}`);if(i.isText)return{node:i,offset:e};let n=0,r=0;for(const s of i.children){if(t&&s.isText&&s.size>=e-r)return Ll(s,e-r,t);if(e===r)return{node:i,offset:n};if(!t&&s.paddedSize===e-r)return{node:i,offset:n+1};if(s.paddedSize>e-r)return Ll(s,e-r-1,t);r+=s.paddedSize,n+=1}return{node:i,offset:n}}function yg(i){return i.isText||i.children.length===0?i:yg(i.children[0])}function _S(i,e){if(i.sizei===e?0:i0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,s=t;for(;r&&s===r.left;)s=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new XS(e,t,!0);const r=this.comparator(e,n.key);return r<0?n.left=this.putInternal(e,t,n.left):r>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Mt{constructor(e,t){b(this,"parentID");b(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Mt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,r;return n.isText?(n.parent.children[0]===n&&t===0?r=n.parent:r=n,n=n.parent):t===0?r=n:r=n.children[t-1],Mt.of(n.id,_e.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Mt.of(_e.of(it.fromStruct(e.parentID.createdAt),e.parentID.offset),_e.of(it.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(n);if(!r||!s)throw new v(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[r,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class _e{constructor(e,t){b(this,"createdAt");b(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new _e(e,t)}static fromStruct(e){return _e.of(it.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=r.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new v(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ut(_e.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(_e.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,r){const s=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new An);const r=new Array;for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,n));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function Zl(i){var t;if(i.isText){const n=i;return{type:n.type,value:n.value}}const e={type:i.type,children:i.children.map(Zl)};return i.attrs&&(e.attributes=Ui((t=i.attrs)==null?void 0:t.toObject())),e}function tc(i){if(i.isText)return i.value;let e="";return i.attrs&&i.attrs.size()&&(e=" "+Array.from(i.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${hn(t.getValue())}"`}).join(" ")),`<${i.type}${e}>${i.children.map(t=>tc(t)).join("")}`}function Sg(i){if(i.isText){const e=i;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:i.type,children:i.children.map(Sg),size:i.size,isRemoved:i.isRemoved}}class xt extends ks{constructor(t,n){super(n);b(this,"indexTree");b(this,"nodeMapByID");this.indexTree=new VS(t),this.nodeMapByID=new bg(_e.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,n){return new xt(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[r,s]=t.toTreeNodePair(this);let o=s;const a=r===o,l=o.parent&&!a?o.parent:r;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const m=p.getCreatedAt().getActorID(),g=s?s.has(m)?s.get(m):_t:Vr;if(p.canStyle(r,g)&&n){const y=f.get(m),k=p.getCreatedAt();(!y||k.after(y))&&f.set(m,k);const $=p.setAttrs(n,r),T=$.reduce((I,[,W])=>(W&&(I[W.getKey()]=u[W.getKey()]),I),{}),Q=p.parent,A=p.prevSibling||p.parent;Object.keys(T).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(p,p),fromPath:this.toPath(Q,A),toPath:this.toPath(p,p),actor:r.getActorID(),value:T});for(const[I]of $)I&&d.push({parent:p,child:I})}}),[f,d,c]}removeStyle(t,n,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([d])=>{const p=d.getCreatedAt().getActorID(),m=s?s.has(p)?s.get(p):_t:Vr;if(d.canStyle(r,m)&&n){const g=u.get(p),y=d.getCreatedAt();(!g||y.after(g))&&u.set(p,y),d.attrs||(d.attrs=new An);for(const T of n){const Q=d.attrs.remove(T,r);for(const A of Q)f.push({parent:d,child:A})}const k=d.parent,$=d.prevSibling||d.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(d,d),fromPath:this.toPath(k,$),toPath:this.toPath(d,d),value:n})}}),[u,f,c]}edit(t,n,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),d=this.toPath(l,h),p=[],m=[],g=[],y=new Map;this.traverseInPosRange(l,h,c,u,([T,Q],A)=>{if(Q===we.Start&&!A)for(const L of T.children)g.push(L);const I=T.getCreatedAt().getActorID(),W=a?a.has(I)?a.get(I):_t:Vr;if(T.canDelete(s,W)||p.includes(T.parent)){const L=y.get(I),F=T.getCreatedAt();(!L||F.after(L))&&y.set(I,F),(Q===we.Text||Q===we.Start)&&p.push(T),m.push([T,Q])}});const k=this.makeDeletionChanges(m,s),$=[];for(const T of p)T.remove(s),T.isRemoved&&$.push({parent:this,child:T});for(const T of g)T.removedAt||l.append(T);if(r>0){let T=0,Q=l,A=h;for(;T{l.isRemoved&&(I.remove(s),$.push({parent:this,child:I})),this.nodeMapByID.put(I.id,I)}),A.isRemoved||T.push(A);if(T.length){const A=T.map(I=>Zl(I));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:d,toPath:d,actor:s.getActorID(),value:A})}}return[k,$,y]}editT(t,n,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],n,r,s,o)}move(t,n,r){throw new v(S.ErrUnimplemented,`not implemented: ${t}, ${n}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,r=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const r of n.getGCPairs())t.push(r)}),t}findPos(t,n=!0){const r=this.indexTree.findTreePos(t,n);return Mt.fromTreePos(r)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(r,s=void 0,o=void 0,a=0)=>{var d,p,m,g;let l,h,c;const u=r.isText?{node:r,offset:0}:s&&o?this.toTreePos(s,o):null;u&&(l=this.indexTree.indexOf(u),h=this.indexTree.treePosToPath(u),c=Mt.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(d=r.removedAt)==null?void 0:d.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(m=r.insNextID)==null?void 0:m.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?Ui((g=r.attrs)==null?void 0:g.toObject()):void 0,index:l,path:h,pos:c};for(let y=0;y0&&y===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(g,d)):r.push({type:"content",from:y,to:k,fromPath:this.toPath(m,u),toPath:this.toPath(g,d),actor:n.getActorID()}))}return r.reverse()}findRightToken([t,n]){if(n===we.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?we.Text:we.Start]:[t,we.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,we.End];const a=s[o+1];return[a,a.isText?we.Text:we.Start]}findLeftToken([t,n]){if(n===we.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?we.Text:we.End]}return[t,we.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,we.Start];const a=s[o-1];return[a,a.isText?we.Text:we.End]}}class Ps extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"contents");b(this,"splitLevel");b(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,r,s,o,a,l){return new Ps(t,n,r,s,o,a,l)}execute(t){var l;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof xt))throw new v(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=n,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>it.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:d,toPath:p})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:d,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${n},${r},${s.map(o=>tc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Bn{constructor(e,t,n,r){b(this,"clientSeq");b(this,"serverSeq");b(this,"lamport");b(this,"actor");this.clientSeq=e,this.serverSeq=r,this.lamport=t,this.actor=n}static of(e,t,n,r){return new Bn(e,t,n,r)}next(){return new Bn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new Bn(this.clientSeq,e,this.actor):new Bn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return it.of(this.lamport,e,this.actor)}setActor(e){return new Bn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const US=new Bn(0,Z.fromInt(0,!0),xa);class Ki{constructor({id:e,operations:t,presenceChange:n,message:r}){b(this,"id");b(this,"operations");b(this,"presenceChange");b(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=r}static create({id:e,operations:t,presenceChange:n,message:r}){return new Ki({id:e,operations:t,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===Kn.Put?t.set(this.id.getActorID(),It(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:Ae.bytesToHex(Ae.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>Ae.bytesToHex(Ae.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:r,message:s}=e;return Ki.create({id:Ae.bytesToChangeID(Ae.hexToBytes(t)),operations:n==null?void 0:n.map(o=>Ae.bytesToOperation(Ae.hexToBytes(o))),presenceChange:r,message:s})}}class Pa{constructor(e,t,n,r,s,o){b(this,"documentKey");b(this,"checkpoint");b(this,"isRemoved");b(this,"changes");b(this,"snapshot");b(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=o}static create(e,t,n,r,s,o){return new Pa(e,t,n,r,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Li{constructor(e,t){b(this,"serverSeq");b(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new Li(e,t)}increaseClientSeq(e){return e===0?this:new Li(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return Li.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const LS=new Li(Z.fromInt(0,!0),0);class dn{constructor(e,t){b(this,"createdAt");b(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new dn(e,t)}static fromStruct(e){return dn.of(it.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new dn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const ZS=dn.of(_t,0);class Vt{constructor(e,t){b(this,"id");b(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Vt(e,t)}static fromStruct(e){const t=dn.fromStruct(e.id);return Vt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return dn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Fn extends gg{constructor(t,n,r){super(n);b(this,"id");b(this,"removedAt");b(this,"prev");b(this,"next");b(this,"insPrev");b(this,"insNext");this.id=t,this.removedAt=r}static create(t,n){return new Fn(t,n)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let r=e;for(;r&&r!==t;)n.push(r),r=r.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new v(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const r=e.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,n),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,n){const r=!!n,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?n.has(c)?n.get(c):_t:Vr;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let r,s;for(let o=0;oi<0?Math.ceil(i):Math.floor(i);var gn=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(gn||{});class pt extends ks{constructor(t,n,r){super(r);b(this,"valueType");b(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Z.fromNumber(n).toInt():this.value=Iu(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Z.fromNumber(n):this.value=n;break;default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,r){return new pt(t,n,r)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Z.fromBytesLE(Array.from(n));default:throw new v(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=pt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Z?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!pt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new v(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===Pe.Long?this.value=this.value+t.getValue().toInt():this.value=Z.fromNumber(this.value+Iu(t.getValue())).toInt(),this}}class tr extends qt{constructor(t,n,r){super(t,r);b(this,"value");this.value=n}static create(t,n,r){return new tr(t,n,r)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof pt))throw new v(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,s=this.value.deepcopy();return r.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===Pe.Long?t.getValue().multiply(-1):t.getValue()*-1;return tr.create(this.getParentCreatedAt(),fe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class xn extends qt{constructor(t,n,r,s,o,a,l){super(t,l);b(this,"fromPos");b(this,"toPos");b(this,"maxCreatedAtMapByActor");b(this,"attributes");b(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,n,r,s,o,a){return new xn(t,n,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,r,s,o,a){return new xn(t,n,r,s,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new v(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof xt))throw new v(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function WS(i){const e=new Jh,t=e.data;for(const[n,r]of Object.entries(i))t[n]=JSON.stringify(r);return e}function jS(i){if(i.type===Kn.Put)return new Bl({type:Jr.PUT,presence:WS(i.presence)});if(i.type===Kn.Clear)return new Bl({type:Jr.CLEAR});throw new v(S.ErrUnimplemented,"unimplemented type")}function zS(i){return new hg({serverSeq:i.getServerSeqAsString(),clientSeq:i.getClientSeq()})}function wg(i){return new ka({clientSeq:i.getClientSeq(),lamport:i.getLamportAsString(),actorId:lc(i.getActorID())})}function V(i){if(i)return new X({lamport:i.getLamportAsString(),delimiter:i.getDelimiter(),actorId:lc(i.getActorID())})}function vg(i){switch(i){case Pe.Null:return G.NULL;case Pe.Boolean:return G.BOOLEAN;case Pe.Integer:return G.INTEGER;case Pe.Long:return G.LONG;case Pe.Double:return G.DOUBLE;case Pe.String:return G.STRING;case Pe.Bytes:return G.BYTES;case Pe.Date:return G.DATE;default:throw new v(S.ErrInvalidType,`unsupported type: ${i}`)}}function kg(i){switch(i){case gn.IntegerCnt:return G.INTEGER_CNT;case gn.LongCnt:return G.LONG_CNT;default:throw new v(S.ErrInvalidType,`unsupported type: ${i}`)}}function Ka(i){if(i instanceof rt)return new yn({type:G.JSON_OBJECT,createdAt:V(i.getCreatedAt()),value:Mg(i)});if(i instanceof dt)return new yn({type:G.JSON_ARRAY,createdAt:V(i.getCreatedAt()),value:v1(i)});if(i instanceof Tt)return new yn({type:G.TEXT,createdAt:V(i.getCreatedAt())});if(i instanceof fe)return new yn({type:vg(i.getType()),createdAt:V(i.getCreatedAt()),value:i.toBytes()});if(i instanceof pt)return new yn({type:kg(i.getType()),createdAt:V(i.getCreatedAt()),value:i.toBytes()});if(i instanceof xt)return new yn({type:G.TREE,createdAt:V(i.getCreatedAt()),value:T1(i)});throw new v(S.ErrUnimplemented,"unimplemented element")}function FS(i){return new Xl({createdAt:V(i.getCreatedAt()),offset:i.getOffset()})}function Xs(i){return new wi({createdAt:V(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function Bs(i){return new Yr({parentId:qr(i.getParentID()),leftSiblingId:qr(i.getLeftSiblingID())})}function qr(i){return new Bi({createdAt:V(i.getCreatedAt()),offset:i.getOffset()})}function Tg(i){const e=new Fh;if(i instanceof vi){const t=i,n=new Wp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.key=t.getKey(),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(i instanceof Ts){const t=i,n=new jp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.prevCreatedAt=V(t.getPrevCreatedAt()),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(i instanceof Ln){const t=i,n=new zp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.prevCreatedAt=V(t.getPrevCreatedAt()),n.createdAt=V(t.getCreatedAt()),n.executedAt=V(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(i instanceof ei){const t=i,n=new Fp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.createdAt=V(t.getCreatedAt()),n.executedAt=V(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(i instanceof xs){const t=i,n=new Gp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Xs(t.getFromPos()),n.to=Xs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);n.content=t.getContent();const s=n.attributes;for(const[o,a]of t.getAttributes())s[o]=a;n.executedAt=V(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(i instanceof Qs){const t=i,n=new Yp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Xs(t.getFromPos()),n.to=Xs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);const s=n.attributes;for(const[o,a]of t.getAttributes())s[o]=a;n.executedAt=V(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(i instanceof tr){const t=i,n=new Jp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.value=Ka(t.getValue()),n.executedAt=V(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(i instanceof Ps){const t=i,n=new Hp,r=n.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=V(o);n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Bs(t.getFromPos()),n.to=Bs(t.getToPos()),n.contents=t1(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=V(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(i instanceof xn){const t=i,n=new Kp;n.parentCreatedAt=V(t.getParentCreatedAt()),n.from=Bs(t.getFromPos()),n.to=Bs(t.getToPos());const r=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=V(a);const s=t.getAttributesToRemove();if(s.length>0)n.attributesToRemove=s;else{const o=n.attributes;for(const[a,l]of t.getAttributes())o[a]=l}n.executedAt=V(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new v(S.ErrUnimplemented,"unimplemented operation");return e}function GS(i){const e=[];for(const t of i)e.push(Tg(t));return e}function YS(i){const e=new Zp({id:wg(i.getID()),message:i.getMessage()});return i.hasOperations()&&(e.operations=GS(i.getOperations())),i.hasPresenceChange()&&(e.presenceChange=jS(i.getPresenceChange())),e}function JS(i){const e=[];for(const t of i)e.push(YS(t));return e}function HS(i){const e=[];for(const t of i)e.push(new og({key:t.getStrKey(),element:ic(t.getValue())}));return e}function KS(i){const e=[];for(const t of i)e.push(new Gh({element:ic(t.getValue())}));return e}function e1(i){const e=[];for(const t of i){const n=new ag;n.id=FS(t.getID()),n.value=t.getValue().getContent(),n.removedAt=V(t.getRemovedAt());const r=n.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new Ta;a.value=o.getValue(),a.updatedAt=V(o.getUpdatedAt()),r[o.getKey()]=a}e.push(n)}return e}function t1(i){const e=[];if(!i||!i.length)return e;for(const t of i)e.push(new lg({content:nc(t)}));return e}function n1(i){const e={};for(const t of i)e[t.getKey()]=new Ta({value:t.getValue(),updatedAt:V(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function nc(i){if(!i)return[];const e=[];return Qa(i,(t,n)=>{const r=new Yh({id:qr(t.id),type:t.type,removedAt:V(t.removedAt),depth:n});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=qr(t.insPrevID)),t.insNextID&&(r.insNextId=qr(t.insNextID)),t.attrs&&(r.attributes=n1(t.attrs)),e.push(r)}),e}function i1(i){const e=new Pt;return e.body.case="jsonObject",e.body.value=new eg({nodes:HS(i.getRHT()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function xg(i){const e=new Pt;return e.body.case="jsonArray",e.body.value=new tg({nodes:KS(i.getElements()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function r1(i){const e=new Pt;return e.body.case="primitive",e.body.value=new ng({type:vg(i.getType()),value:i.toBytes(),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function s1(i){const e=new Pt;return e.body.case="text",e.body.value=new ig({nodes:e1(i.getRGATreeSplit()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function o1(i){const e=new Pt;return e.body.case="counter",e.body.value=new rg({type:kg(i.getType()),value:i.toBytes(),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function Qg(i){const e=new Pt;return e.body.case="tree",e.body.value=new sg({nodes:nc(i.getRoot()),createdAt:V(i.getCreatedAt()),movedAt:V(i.getMovedAt()),removedAt:V(i.getRemovedAt())}),e}function ic(i){if(i instanceof rt)return i1(i);if(i instanceof dt)return xg(i);if(i instanceof fe)return r1(i);if(i instanceof Tt)return s1(i);if(i instanceof pt)return o1(i);if(i instanceof xt)return Qg(i);throw new v(S.ErrUnimplemented,"unimplemented element")}function a1(i){return new En({documentKey:i.getDocumentKey(),checkpoint:zS(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:JS(i.getChanges()),snapshot:i.getSnapshot(),minSyncedTicket:V(i.getMinSyncedTicket())})}function Eu(i){const e=i.findDetails(xS);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Pg(i){let e;return i.serverSeq&&(e=Z.fromString(i.serverSeq,!0)),Bn.of(i.clientSeq,Z.fromString(i.lamport,!0),ac(i.actorId),e)}function q(i){if(i)return it.of(Z.fromString(i.lamport,!0),i.delimiter,ac(i.actorId))}function rc(i){const e={};return Object.entries(i.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function l1(i){const e=i.type;if(e===Jr.PUT){const t=rc(i.presence);return{type:Kn.Put,presence:t}}if(e===Jr.CLEAR)return{type:Kn.Clear};throw new v(S.ErrInvalidType,`unsupported type: ${e}`)}function h1(i){const e=new Map;return Object.entries(i).forEach(([t,n])=>{e.set(t,rc(n))}),e}function Ag(i){switch(i){case G.NULL:return Pe.Null;case G.BOOLEAN:return Pe.Boolean;case G.INTEGER:return Pe.Integer;case G.LONG:return Pe.Long;case G.DOUBLE:return Pe.Double;case G.STRING:return Pe.String;case G.BYTES:return Pe.Bytes;case G.DATE:return Pe.Date}throw new v(S.ErrUnimplemented,`unimplemented value type: ${i}`)}function Zo(i){switch(i){case G.INTEGER_CNT:return gn.IntegerCnt;case G.LONG_CNT:return gn.LongCnt}throw new v(S.ErrUnimplemented,`unimplemented value type: ${i}`)}function el(i){switch(i.type){case G.JSON_OBJECT:return i.value?Ng(i.value):rt.create(q(i.createdAt));case G.JSON_ARRAY:return i.value?w1(i.value):dt.create(q(i.createdAt));case G.TEXT:return Tt.create(er.create(),q(i.createdAt));case G.TREE:return k1(i.value);case G.NULL:case G.BOOLEAN:case G.INTEGER:case G.LONG:case G.DOUBLE:case G.STRING:case G.BYTES:case G.DATE:return fe.of(fe.valueFromBytes(Ag(i.type),i.value),q(i.createdAt));case G.INTEGER_CNT:case G.LONG_CNT:return pt.create(Zo(i.type),pt.valueFromBytes(Zo(i.type),i.value),q(i.createdAt))}}function Us(i){return Vt.of(dn.of(q(i.createdAt),i.offset),i.relativeOffset)}function $g(i){return dn.of(q(i.createdAt),i.offset)}function c1(i){const e=ts.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{e.setAttr(n,r.value,q(r.updatedAt))});const t=Fn.create($g(i.id),e);return t.remove(q(i.removedAt)),t}function Ri(i){return Mt.of(Xr(i.parentId),Xr(i.leftSiblingId))}function Xr(i){return _e.of(q(i.createdAt),i.offset)}function u1(i){if(!i.length)return;const e=[];return i.forEach(t=>{const n=sc(t.content);e.push(n)}),e}function sc(i){if(i.length===0)return;const e=[];for(const r of i)e.push(d1(r));const t=e[e.length-1],n=new Map;n.set(i[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(e[r]),n.set(i[r].depth,e[r]);return t.updateDescendantsSize(),xt.create(t,_t).getRoot()}function f1(i){const e=An.create();for(const[t,n]of Object.entries(i))e.setInternal(t,n.value,q(n.updatedAt),n.isRemoved);return e}function d1(i){const e=Xr(i.id),t=ut.create(e,i.type),n=Object.entries(i.attributes);return t.isText?t.value=i.value:n.length&&(t.attrs=f1(i.attributes)),i.insPrevId&&(t.insPrevID=Xr(i.insPrevId)),i.insNextId&&(t.insNextID=Xr(i.insNextId)),t.removedAt=q(i.removedAt),t}function Cg(i){if(i.body.case==="set"){const e=i.body.value;return vi.create(e.key,el(e.value),q(e.parentCreatedAt),q(e.executedAt))}else if(i.body.case==="add"){const e=i.body.value;return Ts.create(q(e.parentCreatedAt),q(e.prevCreatedAt),el(e.value),q(e.executedAt))}else if(i.body.case==="move"){const e=i.body.value;return Ln.create(q(e.parentCreatedAt),q(e.prevCreatedAt),q(e.createdAt),q(e.executedAt))}else if(i.body.case==="remove"){const e=i.body.value;return ei.create(q(e.parentCreatedAt),q(e.createdAt),q(e.executedAt))}else if(i.body.case==="edit"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,q(s))});const n=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{n.set(r,s)}),xs.create(q(e.parentCreatedAt),Us(e.from),Us(e.to),t,e.content,n,q(e.executedAt))}else if(i.body.case==="style"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,q(s))});const n=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{n.set(r,s)}),Qs.create(q(e.parentCreatedAt),Us(e.from),Us(e.to),t,n,q(e.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const e=i.body.value;return tr.create(q(e.parentCreatedAt),el(e.value),q(e.executedAt))}else if(i.body.case==="treeEdit"){const e=i.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,r])=>{t.set(n,q(r))}),Ps.create(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),u1(e.contents),e.splitLevel,t,q(e.executedAt))}else if(i.body.case==="treeStyle"){const e=i.body.value,t=new Map,n=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,q(o))}),(n==null?void 0:n.length)>0?xn.createTreeRemoveStyleOperation(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),r,n,q(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),xn.create(q(e.parentCreatedAt),Ri(e.from),Ri(e.to),r,t,q(e.executedAt)))}else throw new v(S.ErrUnimplemented,"unimplemented operation")}}function p1(i){const e=[];for(const t of i){const n=Cg(t);n&&e.push(n)}return e}function Rg(i){const e=[];for(const t of i)e.push(Ki.create({id:Pg(t.id),operations:p1(t.operations),presenceChange:t.presenceChange?l1(t.presenceChange):void 0,message:t.message}));return e}function g1(i){return Li.of(Z.fromString(i.serverSeq,!0),i.clientSeq)}function m1(i){return Pa.create(i.documentKey,g1(i.checkpoint),i.isRemoved,Rg(i.changes),i.snapshot,q(i.minSyncedTicket))}function Ig(i){const e=new Hr;for(const n of i.nodes){const r=oc(n.element);e.set(n.key,r,r.getPositionedAt())}const t=new rt(q(i.createdAt),e);return t.setMovedAt(q(i.movedAt)),t.setRemovedAt(q(i.removedAt)),t}function Eg(i){const e=new es;for(const n of i.nodes)e.insert(oc(n.element));const t=new dt(q(i.createdAt),e);return t.setMovedAt(q(i.movedAt)),t.setRemovedAt(q(i.removedAt)),t}function O1(i){const e=fe.of(fe.valueFromBytes(Ag(i.type),i.value),q(i.createdAt));return e.setMovedAt(q(i.movedAt)),e.setRemovedAt(q(i.removedAt)),e}function y1(i){const e=new er;let t=e.getHead();for(const r of i.nodes){const s=e.insertAfter(t,c1(r));r.insPrevId&&s.setInsPrev(e.findNode($g(r.insPrevId))),t=s}const n=new Tt(e,q(i.createdAt));return n.setMovedAt(q(i.movedAt)),n.setRemovedAt(q(i.removedAt)),n}function b1(i){const e=pt.create(Zo(i.type),pt.valueFromBytes(Zo(i.type),i.value),q(i.createdAt));return e.setMovedAt(q(i.movedAt)),e.setRemovedAt(q(i.removedAt)),e}function Dg(i){const e=sc(i.nodes);return xt.create(e,q(i.createdAt))}function oc(i){if(i.body.case==="jsonObject")return Ig(i.body.value);if(i.body.case==="jsonArray")return Eg(i.body.value);if(i.body.case==="primitive")return O1(i.body.value);if(i.body.case==="text")return y1(i.body.value);if(i.body.case==="counter")return b1(i.body.value);if(i.body.case==="tree")return Dg(i.body.value);throw new v(S.ErrUnimplemented,"unimplemented element")}function S1(i){if(!i)return{root:rt.create(_t),presences:new Map};const e=tS.fromBinary(i);return{root:oc(e.root),presences:h1(e.presences)}}function Ng(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Ig(e.body.value)}function Mg(i){return ic(i).toBinary()}function w1(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Eg(e.body.value)}function v1(i){return xg(i).toBinary()}function k1(i){if(!i)throw new v(S.ErrInvalidArgument,"bytes is empty");const e=Pt.fromBinary(i);return Dg(e.body.value)}function T1(i){return Qg(i).toBinary()}function _g(i){return i?Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ac(i){return _g(i)}function Vg(i){return new Uint8Array(i.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lc(i){return Vg(i)}function x1(i){const e=ka.fromBinary(i);return Pg(e)}function Q1(i){const e=Fh.fromBinary(i);return Cg(e)}const Ae={fromPresence:rc,toChangePack:a1,fromChangePack:m1,fromChanges:Rg,toTreeNodes:nc,fromTreeNodes:sc,objectToBytes:Mg,bytesToObject:Ng,bytesToSnapshot:S1,bytesToHex:_g,hexToBytes:Vg,toHexString:ac,toUint8Array:lc,toOperation:Tg,toChangeID:wg,PbChangeID:ka,bytesToChangeID:x1,bytesToOperation:Q1};var Fe=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(Fe||{});let ui=3;function qg(i){ui=i}const B={trivial:(...i)=>{ui>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{ui>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{ui>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{ui>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{ui>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>ui<=i};function Xg(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}class P1{constructor(e,t,n,r,s){b(this,"reconnectStreamDelay");b(this,"doc");b(this,"docID");b(this,"syncMode");b(this,"remoteChangeEventReceived");b(this,"watchStream");b(this,"watchLoopTimerID");b(this,"watchAbortController");b(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===xo.RealtimeSyncOff?!1:this.syncMode===xo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==xo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const tl=()=>{};class A1{constructor(e){b(this,"finalized",!1);b(this,"observers",[]);b(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(!e)throw new v(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:n},r.next===void 0&&(r.next=tl),r.error===void 0&&(r.error=tl),r.complete===void 0&&(r.complete=tl);const s=Xg(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(a){B.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class _i{constructor(e,t,n,r){b(this,"id");b(this,"delimiter");b(this,"message");b(this,"root");b(this,"operations");b(this,"presenceChange");b(this,"previousPresence");b(this,"reversePresenceKeys");this.id=e,this.delimiter=Kh,this.root=t,this.operations=[],this.previousPresence=It(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,n,r){return new _i(e,t,n,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Ki.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class ns{constructor(e){b(this,"rootObject");b(this,"elementPairMapByCreatedAt");b(this,"gcElementSetByCreatedAt");b(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Tt||t instanceof xt)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new ns(rt.create(_t))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(S.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof zn&&e.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(e){let t=0;const n=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return n(e),e instanceof zn&&e.getDescendants(r=>(n(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof zn&&n.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new ns(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n);r.element.getRemovedAt()&&e.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r!==void 0&&e.compare(r)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Bg(i,e){const t=new is(i);return new Proxy(e,t.getHandlers())}class is{constructor(e){b(this,"context");b(this,"handlers");this.context=e,this.handlers={set:(t,n,r)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]=${JSON.stringify(r)}`),is.setInternal(e,t,n,r),!0),get:(t,n)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():fi(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`obj[${n}]`),is.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,r){if(n.includes("."))throw new v(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=Wo(e,r,s),a=t.set(n,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(vi.create(n,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const n={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Wo(e,s,o);n[r]=a}return n}static deleteInternal(e,t,n){const r=e.issueTimeTicket(),s=t.deleteByKey(n,r);s&&(e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function C1(i,e){const t=new pe(i,e);return new Proxy(e,t.getHandlers())}function R1(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function I1(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class pe{constructor(e,t){b(this,"context");b(this,"handlers");b(this,"array");this.context=e,this.array=t,this.handlers={get:(n,r,s)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=n.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,n.getLast()):r==="deleteByID"?o=>{const a=pe.deleteInternalByID(e,n,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=pe.insertAfterInternal(e,n,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=pe.insertBeforeInternal(e,n,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{pe.moveBeforeInternal(e,n,o,a)}:r==="moveAfter"?(o,a)=>{pe.moveAfterInternal(e,n,o,a)}:r==="moveFront"?o=>{pe.moveFrontInternal(e,n,o)}:r==="moveLast"?o=>{pe.moveLastInternal(e,n,o)}:R1(r)?fi(e,n.get(Number(r))):r==="push"?o=>pe.pushInternal(e,n,o):r==="splice"?(o,a,...l)=>pe.splice(e,n,o,a,...l):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?pe.iteratorInternal.bind(this,e,n):r==="includes"?(o,a)=>pe.includes(e,n,o,a):r==="indexOf"?(o,a)=>pe.indexOf(e,n,o,a):r==="lastIndexOf"?(o,a)=>pe.lastIndexOf(e,n,o,a):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>pe.toTestString(n):typeof r=="string"&&I1(r)?(...o)=>{const a=Array.from(n).map(l=>fi(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(n,r,s),deleteProperty:(n,r)=>(B.isEnabled(Fe.Trivial)&&B.trivial(`array[${r}]`),pe.deleteInternalByIndex(e,n,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield _n(e,n)}static buildArrayElements(e,t){const n=[];for(const r of t){const s=e.issueTimeTicket(),o=Wo(e,r,s);n.push(o)}return n}static pushInternal(e,t,n){return pe.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,r,s),e.push(Ln.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,n,r){const s=e.issueTimeTicket();t.moveAfter(n,r,s),e.push(Ln.create(t.getCreatedAt(),n,r,s))}static moveFrontInternal(e,t,n){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),n,r),e.push(Ln.create(t.getCreatedAt(),s.getCreatedAt(),n,r))}static moveLastInternal(e,t,n){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,n,r),e.push(Ln.create(t.getCreatedAt(),s,n,r))}static insertAfterInternal(e,t,n,r){const s=e.issueTimeTicket(),o=Wo(e,r,s);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Ts.create(t.getCreatedAt(),n,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,n,r){return pe.insertAfterInternal(e,t,t.getPrevCreatedAt(n),r)}static deleteInternalByIndex(e,t,n){const r=e.issueTimeTicket(),s=t.deleteByIndex(n,r);if(s)return e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,n){const r=e.issueTimeTicket(),s=t.delete(n,r);return e.push(ei.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,n,r,...s){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).includes(n,o);for(let l=o;l=s)return-1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).indexOf(n,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(fe.isSupport(n))return Array.from(t).map(h=>fi(e,h)).lastIndexOf(n,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===n.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let Aa=class{constructor(e,t){b(this,"context");b(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,r){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);B.isEnabled(Fe.Debug)&&B.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${n}`);const o=r?Hi(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,n,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new xs(this.text.getCreatedAt(),s[0],s[1],l,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);B.isEnabled(Fe.Debug)&&B.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const s=Hi(n),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(r,s,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Qs(this.text.getCreatedAt(),r[0],r[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Vt.fromStruct(e[0]),Vt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class $a{constructor(e,t){b(this,"valueType");b(this,"value");b(this,"context");b(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new v(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=fe.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(tr.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function hc(i,e,t){const{type:n}=i,r=t.issueTimeTicket();if(n===Tn){Ug(i);const{value:s}=i,o=ut.create(_e.of(r,0),n,s);e.append(o)}else{const{children:s=[]}=i,{attributes:o}=i;let a;if(typeof o=="object"&&!pg(o)){const h=Hi(o);a=new An;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(_e.of(r,0),n,void 0,a);e.append(l);for(const h of s)hc(h,l,t)}}function E1(i,e){const{type:t}=e,n=i.issueTimeTicket();let r;if(e.type===Tn){const{value:s}=e;r=ut.create(_e.of(n,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!pg(o)){const l=Hi(o);a=new An;for(const[h,c]of Object.entries(l))a.set(h,c,n)}r=ut.create(_e.of(i.issueTimeTicket(),0),t,void 0,a);for(const l of s)hc(l,r,i)}return r}function Ug(i){if(!i.value.length)throw new v(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function Du(i){if(!i.length)return!0;if(i[0].type===Tn)for(const t of i){const{type:n}=t;if(n!==Tn)throw new v(S.ErrInvalidArgument,"element node and text node cannot be passed together");Ug(t)}else for(const t of i){const{type:n}=t;if(n===Tn)throw new v(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let Ca=class{constructor(e){b(this,"initialRoot");b(this,"context");b(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ut.create(_e.of(e.issueTimeTicket(),0),DS);const t=ut.create(_e.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)hc(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?Hi(t):void 0,[a]=this.tree.style([n,r],o,s);this.context.push(xn.create(this.tree.getCreatedAt(),n,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,n){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?Hi(n):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(xn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([r,s],n,o);for(const h of l)this.context.registerGCPair(h);this.context.push(xn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,n,o))}editInternal(e,t,n,r=0){var h;if(n.length!==0&&n[0]&&(Du(n),n[0].type!==Tn))for(const c of n){const{children:u=[]}=c;Du(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=n[0])==null?void 0:h.type)===Tn){let c="";for(const u of n){const{value:f}=u;c+=f}o.push(ut.create(_e.of(this.context.issueTimeTicket(),0),Tn,c))}else o=n.map(c=>c&&E1(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,t],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,r,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(Ps.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,n?[n]:[],r)}editBulkByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,n,r)}edit(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,n?[n]:[],r)}editBulk(e,t,n,r=0){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,n,r)}toXML(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Mt.fromStruct(e[0]),Mt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Mt.fromStruct(e[0]),Mt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Nu(i,e){return Bg(i,e)}function _n(i,e){if(e){if(e instanceof fe)return e;if(e instanceof rt)return Bg(i,e);if(e instanceof dt)return C1(i,e);if(e instanceof Tt)return new Aa(i,e);if(e instanceof pt){const t=new $a(gn.IntegerCnt,0);return t.initialize(i,e),t}else if(e instanceof xt){const t=new Ca;return t.initialize(i,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function fi(i,e){const t=_n(i,e);return t instanceof fe?t.getValue():t}function Wo(i,e,t){let n;if(fe.isSupport(e))n=fe.of(e,t);else if(Array.isArray(e))n=dt.create(t,pe.buildArrayElements(i,e));else if(typeof e=="object")e instanceof Aa?(n=Tt.create(er.create(),t),e.initialize(i,n)):e instanceof $a?(n=pt.create(e.getValueType(),e.getValue(),t),e.initialize(i,n)):e instanceof Ca?(n=xt.create(e.buildRoot(i),t),e.initialize(i,n)):n=rt.create(t,is.buildObjectMembers(i,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Mu=50;class D1{constructor(){b(this,"undoStack",[]);b(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Mu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Mu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const N1="yorkie-devtools-panel",M1="yorkie-devtools-sdk";let Ei="disconnected";const _u=new Map,To=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=To);function Ls(i,e){(e!=null&&e.force||Ei!=="disconnected")&&window.postMessage({source:M1,...i},"*")}function _1(i){if(!i.isEnableDevtools()||typeof window>"u"||_u.has(i.getKey()))return;To.set(i.getKey(),[]);const e=i.subscribe("all",t=>{t.some(n=>n.type!==ze.StatusChanged&&n.type!==ze.Snapshot&&n.type!==ze.LocalChange&&n.type!==ze.RemoteChange&&n.type!==ze.Initialized&&n.type!==ze.Watched&&n.type!==ze.Unwatched&&n.type!==ze.PresenceChanged)||(To.get(i.getKey()).push(t),Ei==="synced"&&Ls({msg:"doc::sync::partial",docKey:i.getKey(),event:t}))});_u.set(i.getKey(),[e]),Ls({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==N1)return;switch(t.data.msg){case"devtools::connect":if(Ei!=="disconnected")break;Ei="connected",Ls({msg:"doc::available",docKey:i.getKey()}),B.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Ei="disconnected",B.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Ei="synced",Ls({msg:"doc::sync::full",docKey:i.getKey(),events:To.get(i.getKey())}),B.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var Vn=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(Vn||{}),ze=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(ze||{}),rs=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(rs||{}),Wl=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(Wl||{});class Lg{constructor(e,t){b(this,"key");b(this,"status");b(this,"opts");b(this,"changeID");b(this,"checkpoint");b(this,"localChanges");b(this,"root");b(this,"clone");b(this,"eventStream");b(this,"eventStreamObserver");b(this,"onlineClients");b(this,"presences");b(this,"history");b(this,"internalHistory");b(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=ns.create(),this.changeID=US,this.checkpoint=LS,this.localChanges=[],this.eventStream=$1(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new D1,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},_1(this)}update(e,t){if(this.getStatus()==="removed")throw new v(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const s=Nu(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(s,new Ha(r,this.clone.presences.get(n)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){B.isEnabled(Fe.Trivial)&&B.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,re.Local),l=r.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const h=[];o.length>0&&h.push({type:"local-change",source:re.Local,value:{message:s.getMessage()||"",operations:o,actor:n,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:re.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(h),B.isEnabled(Fe.Trivial)&&B.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,r){if(typeof e=="string"){if(typeof t!="function")throw new v(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||a(h)},n,r)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||a(h)},n,r)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&a(h)},n,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},n,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},n,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},n,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,r)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&h.push(c);h.length&&o({...l,value:{...l.value,operations:h}})}},n,r)}if(typeof e=="function"){const s=e,o=t,a=n;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||s(h)},o,a)}throw new v(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((s,o)=>s===n[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),re.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,re.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),B.isEnabled(Fe.Trivial)&&B.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:It(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Pa.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Nu(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:r}=Ae.bytesToSnapshot(t);this.root=new ns(n),this.presences=r,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:re.Remote,value:{snapshot:this.isEnableDevtools()?Ae.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){B.isEnabled(Fe.Debug)&&B.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),B.isEnabled(Fe.Trivial)&&B.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` `));for(const n of e)this.applyChange(n,t);B.isEnabled(Fe.Debug)&&B.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case Kn.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:re.Remote,value:{clientID:r,presence:o.presence}});break;case Kn.Clear:n.push({type:"unwatched",source:re.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===re.Remote?{type:"remote-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const r of t)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:re.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,r=[];if(t===_r.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:re.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(t===_r.DOCUMENT_UNWATCHED){const s=this.getPresence(n);this.removeOnlineClient(n),s&&r.push({type:"unwatched",source:re.Remote,value:{clientID:n,presence:s}})}else if(t===_r.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:n,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(xa),this.publish([{source:e==="removed"?re.Remote:re.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n}=e.value;if(!t)return;this.applySnapshot(Z.fromString(n),Ae.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=Ki.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:r}of e.value)t.add(n),this.presences.set(n,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const r of t)if(n=n[r],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?It(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?It(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?It(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:It(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:It(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof qt)){new Ha(t,It(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,re.UndoRedo);const{opInfos:r,reverseOps:s}=n.execute(this.root,this.presences,re.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:re.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&l.push({type:"presence-changed",source:re.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=_i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof qt)){new Ha(t,It(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,re.UndoRedo);const{opInfos:r,reverseOps:s}=n.execute(this.root,this.presences,re.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:re.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&l.push({type:"presence-changed",source:re.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const r={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([r])}}function V1(i,e){return t=>async n=>(i&&n.header.set("x-api-key",i),e&&n.header.set("authorization",e),await t(n))}const q1="yorkie-js-sdk",X1="0.5.0",B1="Yorkie JS SDK",U1="./src/yorkie.ts",L1={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Z1=["dist"],W1={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},j1={node:">=18.0.0",npm:">=7.1.0"},z1={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},F1={name:"hackerwins",email:"susukang98@gmail.com"},G1="Apache-2.0",Y1={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},J1="https://github.com/yorkie-team/yorkie-js-sdk#readme",H1={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},K1={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Vu={name:q1,version:X1,description:B1,main:U1,publishConfig:L1,files:Z1,scripts:W1,engines:j1,repository:z1,author:F1,license:G1,bugs:Y1,homepage:J1,devDependencies:H1,dependencies:K1};function ew(){return i=>async e=>(e.header.set("x-yorkie-user-agent",Vu.name+"/"+Vu.version),await i(e))}const tw=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var xo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(xo||{});const Zs={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nl={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Zg{constructor(e,t){b(this,"id");b(this,"key");b(this,"status");b(this,"attachmentMap");b(this,"apiKey");b(this,"conditions");b(this,"syncLoopDuration");b(this,"reconnectStreamDelay");b(this,"retrySyncLoopDelay");b(this,"rpcClient");b(this,"taskQueue");b(this,"processing",!1);t=t||Zs,this.key=t.key?t.key:Xg(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||Zs.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||Zs.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||Zs.retrySyncLoopDelay,this.rpcClient=Ib(kS,eS({baseUrl:e,interceptors:[V1(t.apiKey,t.token),ew()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),B.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw B.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),B.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw B.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Vn.Detached)throw new v(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,h=s.options;try{await this.broadcast(e.getKey(),o,a,h)}catch(u){u instanceof Error&&(l==null||l(u))}}),r=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:Ae.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=Ae.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===Vn.Removed||(e.applyStatus(Vn.Attached),this.attachmentMap.set(e.getKey(),new P1(this.reconnectStreamDelay,e,s.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(e.getKey()),B.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw B.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new v(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:Ae.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=Ae.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Vn.Removed&&e.applyStatus(Vn.Detached),this.detachInternal(e.getKey()),B.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw B.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new v(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=n.syncMode;return r===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw B.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw B.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=Ae.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=Ae.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),B.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw B.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,r){if(!this.isActive())throw new v(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(S.ErrDocumentNotAttached,`${e} is not attached`);if(!tw(n))throw new v(S.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??nl.maxRetries,a=nl.maxBackoff;let l=0;const h=u=>Math.min(nl.initialRetryInterval*2**u,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{B.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(B.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),B.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw B.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){B.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{B.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};B.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new v(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(S.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:r.signal});return t.doc.publish([{type:ze.ConnectionChanged,value:rs.Connected}]),B.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const h of s)this.handleWatchDocumentsResponse(t,h),h.body.case==="initialization"&&o([s,r])}catch(h){t.doc.resetOnlineClients(),t.doc.publish([{type:ze.Initialized,source:re.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:ze.ConnectionChanged,value:rs.Disconnected}]),B.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?n():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===_r.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Vn.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:r}=e,s=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:Ae.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(o=>{const a=Ae.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(a),e.doc.publish([{type:ze.SyncStatusChanged,value:Wl.Synced}]),n.getStatus()===Vn.Removed&&this.detachInternal(n.getKey());const l=n.getKey(),h=a.getChangeSize();return B.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),n}).catch(o=>{throw n.publish([{type:ze.SyncStatusChanged,value:Wl.SyncFailed}]),B.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof ve?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((Eu(e)===S.ErrClientNotActivated||Eu(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{B.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const il={Client:Zg,Document:Lg,Primitive:fe,Text:Aa,Counter:$a,Tree:Ca,LogLevel:Fe,setLogLevel:qg,IntType:gn.IntegerCnt,LongType:gn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Zg,Document:Lg,Primitive:fe,Text:Aa,Counter:$a,Tree:Ca,LogLevel:Fe,setLogLevel:qg,IntType:gn.IntegerCnt,LongType:gn.LongCnt});class H{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=nr(this,e,t);let r=[];return this.decompose(0,e,r,2),n.length&&n.decompose(0,n.length,r,3),this.decompose(t,this.length,r,1),Ht.from(r,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=nr(this,e,t);let n=[];return this.decompose(e,t,n,0),Ht.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),r=new Br(this),s=new Br(e);for(let o=t,a=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(a+=r.value.length,r.done||a>=n)return!0}}iter(e=1){return new Br(this,e)}iterRange(e,t=this.length){return new Wg(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;n=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new jg(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?H.empty:e.length<=32?new ye(e):Ht.from(ye.split(e,[]))}}class ye extends H{constructor(e,t=nw(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?n:a)>=e)return new iw(r,a,n,o);r=a+1,n++}}decompose(e,t,n,r){let s=e<=0&&t>=this.length?this:new ye(qu(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=n.pop(),a=Qo(s.text,o.text.slice(),0,s.length);if(a.length<=32)n.push(new ye(a,o.length+s.length));else{let l=a.length>>1;n.push(new ye(a.slice(0,l)),new ye(a.slice(l)))}}else n.push(s)}replace(e,t,n){if(!(n instanceof ye))return super.replace(e,t,n);[e,t]=nr(this,e,t);let r=Qo(this.text,Qo(n.text,qu(this.text,0,e)),t),s=this.length+n.length-(t-e);return r.length<=32?new ye(r,s):Ht.from(ye.split(r,[]),s)}sliceString(e,t=this.length,n=` `){[e,t]=nr(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=n),es&&(r+=a.slice(Math.max(0,e-s),t-s)),s=l+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let n=[],r=-1;for(let s of e)n.push(s),r+=s.length+1,n.length==32&&(t.push(new ye(n,r)),n=[],r=-1);return r>-1&&t.push(new ye(n,r)),t}}class Ht extends H{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,t,n,r){for(let s=0;;s++){let o=this.children[s],a=r+o.length,l=n+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,n,r);r=a+1,n=l+1}}decompose(e,t,n,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!h?n.push(a):a.decompose(e-o,t-o,n,h)}o=l+1}}replace(e,t,n){if([e,t]=nr(this,e,t),n.lines=s&&t<=a){let l=o.replace(e-s,t-s,n),h=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>h>>6){let c=this.children.slice();return c[r]=l,new Ht(c,this.length-(t-e)+n.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,n)}sliceString(e,t=this.length,n=` `){[e,t]=nr(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=n),eo&&(r+=a.sliceString(e-o,t-o,n)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof Ht))return 0;let n=0,[r,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==a)return n;let l=this.children[r],h=e.children[s];if(l!=h)return n+l.scanIdentical(h,t);n+=l.length+1}}static from(e,t=e.reduce((n,r)=>n+r.length+1,-1)){let n=0;for(let d of e)n+=d.lines;if(n<32){let d=[];for(let p of e)p.flatten(d);return new ye(d,t)}let r=Math.max(32,n>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function u(d){let p;if(d.lines>s&&d instanceof Ht)for(let m of d.children)u(m);else d.lines>o&&(l>o||!l)?(f(),a.push(d)):d instanceof ye&&l&&(p=c[c.length-1])instanceof ye&&d.lines+p.lines<=32?(l+=d.lines,h+=d.length+1,c[c.length-1]=new ye(p.text.concat(d.text),p.length+1+d.length)):(l+d.lines>r&&f(),l+=d.lines,h+=d.length+1,c.push(d))}function f(){l!=0&&(a.push(c.length==1?c[0]:Ht.from(c,h)),h=-1,l=c.length=0)}for(let d of e)u(d);return f(),a.length==1?a[0]:new Ht(a,t)}}H.empty=new ye([""],0);function nw(i){let e=-1;for(let t of i)e+=t.length+1;return e}function Qo(i,e,t=0,n=1e9){for(let r=0,s=0,o=!0;s=t&&(l>n&&(a=a.slice(0,n-r)),r0?1:(e instanceof ye?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,r=this.nodes[n],s=this.offsets[n],o=s>>1,a=r instanceof ye?r.text.length:r.children.length;if(o==(t>0?a:0)){if(n==0)return this.done=!0,this.value="",this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=` diff --git a/examples/vanilla-codemirror6/index.html b/examples/vanilla-codemirror6/index.html index 2deca7eb8..741397ccd 100644 --- a/examples/vanilla-codemirror6/index.html +++ b/examples/vanilla-codemirror6/index.html @@ -4,7 +4,7 @@ Yorkie + CodeMirror 6 Example - + diff --git a/examples/vanilla-quill/assets/index-BWTv0Xii.js b/examples/vanilla-quill/assets/index-Dlajql5W.js similarity index 79% rename from examples/vanilla-quill/assets/index-BWTv0Xii.js rename to examples/vanilla-quill/assets/index-Dlajql5W.js index 4d8c76a9d..fdd2d58ad 100644 --- a/examples/vanilla-quill/assets/index-BWTv0Xii.js +++ b/examples/vanilla-quill/assets/index-Dlajql5W.js @@ -19,7 +19,7 @@ var ol=Object.defineProperty;var sl=(i,e,t)=>e in i?ol(i,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Mt=null;try{Mt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Re(i,e,t){this.low=i|0,this.high=e|0,this.unsigned=!!t}Re.prototype.__isLong__;Object.defineProperty(Re.prototype,"__isLong__",{value:!0});function mt(i){return(i&&i.__isLong__)===!0}function hs(i){var e=Math.clz32(i&-i);return i?31-e:e}Re.isLong=mt;var ds={},gs={};function vr(i,e){var t,n,r;return e?(i>>>=0,(r=0<=i&&i<256)&&(n=gs[i],n)?n:(t=Ve(i,0,!0),r&&(gs[i]=t),t)):(i|=0,(r=-128<=i&&i<128)&&(n=ds[i],n)?n:(t=Ve(i,i<0?-1:0,!1),r&&(ds[i]=t),t))}Re.fromInt=vr;function Bt(i,e){if(isNaN(i))return e?qn:Yt;if(e){if(i<0)return qn;if(i>=Aa)return Ea}else{if(i<=-ms)return Et;if(i+1>=ms)return _a}return i<0?Bt(-i,e).neg():Ve(i%Lr|0,i/Lr|0,e)}Re.fromNumber=Bt;function Ve(i,e,t){return new Re(i,e,t)}Re.fromBits=Ve;var ji=Math.pow;function Oo(i,e,t){if(i.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return e?qn:Yt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return Oo(i.substring(1),e,t).neg();for(var r=Bt(ji(t,8)),o=Yt,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Lr+(this.low>>>0):this.high*Lr+(this.low>>>0)};he.toString=function(e){if(e=e||10,e<2||36>>0,v=m.toString(e);if(s=c,s.isZero())return v+u;for(;v.length<6;)v="0"+v;u=""+v+u}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Et)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(e){return mt(e)||(e=tn(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};he.eq=he.equals;he.notEquals=function(e){return!this.eq(e)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(e){return this.comp(e)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(e){return this.comp(e)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(e){return this.comp(e)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(e){return this.comp(e)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(e){if(mt(e)||(e=tn(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(Et)?Et:this.not().add(xr)};he.neg=he.negate;he.add=function(e){mt(e)||(e=tn(e));var t=this.high>>>16,n=this.high&65535,r=this.low>>>16,o=this.low&65535,s=e.high>>>16,u=e.high&65535,c=e.low>>>16,m=e.low&65535,v=0,d=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,d+=l>>>16,l&=65535,d+=n+u,v+=d>>>16,d&=65535,v+=t+s,v&=65535,Ve(l<<16|a,v<<16|d,this.unsigned)};he.subtract=function(e){return mt(e)||(e=tn(e)),this.add(e.neg())};he.sub=he.subtract;he.multiply=function(e){if(this.isZero())return this;if(mt(e)||(e=tn(e)),Mt){var t=Mt.mul(this.low,this.high,e.low,e.high);return Ve(t,Mt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?qn:Yt;if(this.eq(Et))return e.isOdd()?Et:Yt;if(e.eq(Et))return this.isOdd()?Et:Yt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(ys)&&e.lt(ys))return Bt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,o=this.low>>>16,s=this.low&65535,u=e.high>>>16,c=e.high&65535,m=e.low>>>16,v=e.low&65535,d=0,l=0,a=0,p=0;return p+=s*v,a+=p>>>16,p&=65535,a+=o*v,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*v,d+=l>>>16,l&=65535,l+=o*m,d+=l>>>16,l&=65535,l+=s*c,d+=l>>>16,l&=65535,d+=n*v+r*m+o*c+s*u,d&=65535,Ve(a<<16|p,d<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(e){if(mt(e)||(e=tn(e)),e.isZero())throw Error("division by zero");if(Mt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Mt.div_u:Mt.div_s)(this.low,this.high,e.low,e.high);return Ve(t,Mt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?qn:Yt;var n,r,o;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return qn;if(e.gt(this.shru(1)))return Ta;o=qn}else{if(this.eq(Et)){if(e.eq(xr)||e.eq(po))return Et;if(e.eq(Et))return xr;var s=this.shr(1);return n=s.div(e).shl(1),n.eq(Yt)?e.isNegative()?xr:po:(r=this.sub(e.mul(n)),o=n.add(r.div(e)),o)}else if(e.eq(Et))return this.unsigned?qn:Yt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();o=Yt}for(r=this;r.gte(e);){n=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:ji(2,u-48),m=Bt(n),v=m.mul(e);v.isNegative()||v.gt(r);)n-=c,m=Bt(n,this.unsigned),v=m.mul(e);m.isZero()&&(m=xr),o=o.add(m),r=r.sub(v)}return o};he.div=he.divide;he.modulo=function(e){if(mt(e)||(e=tn(e)),Mt){var t=(this.unsigned?Mt.rem_u:Mt.rem_s)(this.low,this.high,e.low,e.high);return Ve(t,Mt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return Ve(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?hs(this.low):hs(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(e){return mt(e)||(e=tn(e)),Ve(this.low&e.low,this.high&e.high,this.unsigned)};he.or=function(e){return mt(e)||(e=tn(e)),Ve(this.low|e.low,this.high|e.high,this.unsigned)};he.xor=function(e){return mt(e)||(e=tn(e)),Ve(this.low^e.low,this.high^e.high,this.unsigned)};he.shiftLeft=function(e){return mt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ve(this.low<>>32-e,this.unsigned):Ve(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ve(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(e){return mt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ve(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Ve(this.high,0,this.unsigned):Ve(this.high>>>e-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(e){var t;return mt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ve(this.high,this.low,this.unsigned):e<32?(t=32-e,Ve(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Ve(this.high<>>t,this.low<>>t,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(e){var t;return mt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ve(this.high,this.low,this.unsigned):e<32?(t=32-e,Ve(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Ve(this.low<>>e,this.high<>>e,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?Ve(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:Ve(this.low,this.high,!0)};he.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};he.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};Re.fromBytes=function(e,t,n){return n?Re.fromBytesLE(e,t):Re.fromBytesBE(e,t)};Re.fromBytesLE=function(e,t){return new Re(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Re.fromBytesBE=function(e,t){return new Re(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const Xu=te.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);te.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:Mn}]);te.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);te.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:Qu,repeated:!0}]);const Qu=te.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});te.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:ec,repeated:!0}]);const ec=te.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});te.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:tc,repeated:!0}]);const tc=te.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});te.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);te.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);te.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:nc,repeated:!0}]);const nc=te.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});te.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var ee=(i=>(i.Ok="ok",i.ErrClientNotActivated="ErrClientNotActivated",i.ErrClientNotFound="ErrClientNotFound",i.ErrUnimplemented="ErrUnimplemented",i.ErrInvalidType="ErrInvalidType",i.ErrDummy="ErrDummy",i.ErrDocumentNotAttached="ErrDocumentNotAttached",i.ErrDocumentNotDetached="ErrDocumentNotDetached",i.ErrDocumentRemoved="ErrDocumentRemoved",i.ErrInvalidObjectKey="ErrInvalidObjectKey",i.ErrInvalidArgument="ErrInvalidArgument",i.ErrNotInitialized="ErrNotInitialized",i.ErrNotReady="ErrNotReady",i.ErrRefused="ErrRefused",i.ErrContextNotProvided="ErrContextNotProvided",i))(ee||{});class ne extends Error{constructor(t,n){super(n);J(this,"name","YorkieError");J(this,"stack");this.code=t,this.message=n,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function Gt(i){if(i instanceof Map){const e=Array.from(i);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(i))}const Oa=i=>i?Object.entries(i).length===0:!0,Mr=i=>{const e={};for(const[t,n]of Object.entries(i))e[t]=JSON.stringify(n);return e},Pr=i=>{const e={};for(const[t,n]of Object.entries(i))e[t]=JSON.parse(n);return e};var ir=(i=>(i.Put="put",i.Clear="clear",i))(ir||{});class io{constructor(e,t){J(this,"context");J(this,"presence");this.context=e,this.presence=t}set(e,t){for(const n of Object.keys(e))this.presence[n]=e[n];this.context.setPresenceChange({type:"put",presence:Gt(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const Hi="000000000000000000000000",rc="FFFFFFFFFFFFFFFFFFFFFFFF";class Ot{constructor(e,t,n){J(this,"lamport");J(this,"delimiter");J(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=n}static of(e,t,n){return new Ot(e,t,n)}static fromStruct(e){return Ot.of(Re.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new Ot(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const So=0,ic=4294967295,oc=Re.MAX_VALUE,Xt=new Ot(Re.fromNumber(0),So,Hi);new Ot(Re.fromNumber(1),So+1,Hi);const Yr=new Ot(oc,ic,rc);function xn(i){return i.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ui{constructor(e){J(this,"createdAt");J(this,"movedAt");J(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class tr extends ui{constructor(e){super(e)}}class ko{constructor(e,t){J(this,"strKey");J(this,"value");this.strKey=e,this.value=t}static of(e,t){return new ko(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class ni{constructor(){J(this,"nodeMapByKey");J(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new ni}set(e,t,n){let r;const o=this.nodeMapByKey.get(e);o!=null&&!o.isRemoved()&&o.remove(n)&&(r=o.getValue());const s=ko.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(o==null||n.after(o.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(n)),r}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ne(ee.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ne(ee.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class St extends tr{constructor(t,n){super(t);J(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new St(t,ni.create());const r=ni.create();for(const[o,s]of Object.entries(n))r.set(o,s.deepcopy(),s.getCreatedAt());return new St(t,r)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,r){return this.memberNodes.set(t,n,r)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,r]of this)t.push(`"${xn(n)}":${r.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,r]of this){const{createdAt:o,value:s,type:u}=r.toJSForTest();t[n]={key:n,createdAt:o,value:s,type:u}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var r;const t=Array();for(const[o]of this)t.push(o);const n=[];for(const o of t.sort()){const s=(r=this.memberNodes.get(o))==null?void 0:r.getValue();n.push(`"${xn(o)}":${s.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=St.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const r=n.getValue();if(t(r,this))return;r instanceof tr&&r.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var Ge=(i=>(i.Local="local",i.Remote="remote",i.UndoRedo="undoredo",i))(Ge||{});class en{constructor(e,t){J(this,"parentCreatedAt");J(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ne(ee.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Sa{constructor(e){J(this,"value");J(this,"left");J(this,"right");J(this,"parent");J(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class ri{constructor(e){J(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ne(ee.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return[t,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let t=0,n=e,r;for(;n;)(!r||r===n.getRight())&&(t+=n.getLength()+(n.hasLeft()?n.getLeftWeight():0)),r=n,n=n.getParent();return t-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new ri(e.getLeft());t.root&&t.root.setParent();const n=new ri(e.getRight());if(n.root&&n.root.setParent(),t.root){const r=t.getRightmost();t.splayNode(r),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var ut=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(ut||{});class Xe extends ui{constructor(t,n){super(n);J(this,"valueType");J(this,"value");this.valueType=Xe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new Xe(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(o,s){r.setUint8(s,o)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Re.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Re.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${xn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=Xe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Re)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return Xe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=Re.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Ui extends Sa{constructor(t){super(t);J(this,"prev");J(this,"next");this.value=t}static createAfter(t,n){const r=new Ui(n),o=t.next;return t.next=r,r.prev=t,r.next=o,o&&(o.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class ii{constructor(){J(this,"dummyHead");J(this,"last");J(this,"nodeMapByIndex");J(this,"nodeMapByCreatedAt");const e=Xe.of(0,Xt);e.setRemovedAt(Xt),this.dummyHead=new Ui(e),this.last=this.dummyHead,this.nodeMapByIndex=new ri,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new ii}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,n),o=Ui.createAfter(r,t);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(e,t,n){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const o=this.nodeMapByCreatedAt.get(t.toIDString());if(!o)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==o&&(!o.getValue().getMovedAt()||n.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(r.getCreatedAt(),o.getValue(),n),o.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ne(ee.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),r=n.isRemoved();return n.remove(t)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class Rt extends tr{constructor(t,n){super(t);J(this,"elements");this.elements=n}static create(t,n){if(!n)return new Rt(t,ii.create());const r=ii.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,r){this.elements.moveAfter(t,n,r)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const r=n.getValue();if(t(r,this))return;r instanceof tr&&r.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...a,value:a.value?{attributes:Pr(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,v,[c,c]]}setStyle(t,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),v=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):Xt:Yr;if(a.canStyle(r,b)){const w=v.get(p),y=a.getCreatedAt();(!w||y.after(w))&&v.set(p,y),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:Pr(n)}});for(const[w,y]of Object.entries(n)){const[h]=a.getValue().setAttr(w,y,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[v,l,c]}indexRangeToPosRange(t,n){const r=this.rgaTreeSplit.indexToPos(t);return t===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();t.push({attributes:Pr(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new qt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())t.push(r)}return t}}class fi extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"content");J(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(t,n,r,o,s,u,c){return new fi(t,n,r,o,s,u,c)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof qt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${t}.EDIT(${n},${r},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class hi extends en{constructor(t,n,r,o,s,u){super(t,u);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(t,n,r,o,s,u){return new hi(t,n,r,o,s,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof qt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)t.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${t}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const sc=2,ac="root",Fn="text";function Vr(i,e){let t=0;const n=i.children;for(let r=0;r0)throw new ne(ee.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Fn}get paddedSize(){return this.size+(this.isText?0:sc)}isAncestorOf(e){return uc(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=n;const o=this.cloneText(e+t);return o.value=r,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,e),o=this.children.slice(e);this._children=r,n._children=o,this.size=this._children.reduce((s,u)=>s+u.paddedSize,0),n.size=n._children.reduce((s,u)=>s+u.paddedSize,0);for(const s of n._children)s.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function uc(i,e){if(i===e)return!1;for(;e.parent;){if(e.parent===i)return!0;e=e.parent}return!1}var st=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(st||{});function ka(i,e,t,n){if(e>t)throw new ne(ee.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>i.size)throw new ne(ee.ErrInvalidArgument,`from is out of range: ${e} > ${i.size}`);if(t>i.size)throw new ne(ee.ErrInvalidArgument,`to is out of range: ${t} > ${i.size}`);if(e===t)return;let r=0;for(const o of i.children){if(e-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),ka(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function xa(i,e,t=0){for(const n of i.children)xa(n,e,t+1);e(i,t)}function Wi(i,e,t=0){for(const n of i._children)Wi(n,e,t+1);e(i,t)}function mo(i,e,t=!0){if(e>i.size)throw new ne(ee.ErrInvalidArgument,`index is out of range: ${e} > ${i.size}`);if(i.isText)return{node:i,offset:e};let n=0,r=0;for(const o of i.children){if(t&&o.isText&&o.size>=e-r)return mo(o,e-r,t);if(e===r)return{node:i,offset:n};if(!t&&o.paddedSize===e-r)return{node:i,offset:n+1};if(o.paddedSize>e-r)return mo(o,e-r-1,t);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function Na(i){return i.isText||i.children.length===0?i:Na(i.children[0])}function cc(i,e){if(i.sizei===e?0:i0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,o=t;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new dc(e,t,!0);const r=this.comparator(e,n.key);return r<0?n.left=this.putInternal(e,t,n.left):r>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Zt{constructor(e,t){J(this,"parentID");J(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Zt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,r;return n.isText?(n.parent.children[0]===n&&t===0?r=n.parent:r=n,n=n.parent):t===0?r=n:r=n.children[t-1],Zt.of(n.id,gt.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Zt.of(gt.of(Ot.fromStruct(e.parentID.createdAt),e.parentID.offset),gt.of(Ot.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),r=e.findFloorNode(t);let o=e.findFloorNode(n);if(!r||!o)throw new ne(ee.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=e.findFloorNode(o.insPrevID)),[r,o]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class gt{constructor(e,t){J(this,"createdAt");J(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new gt(e,t)}static fromStruct(e){return gt.of(Ot.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const o=r.deepcopy();return o.parent=t,o}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ne(ee.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new ne(ee.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new Ct(gt.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ct(gt.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,r){const o=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(o){if(o.insPrevID=this.id,this.insNextID){const s=t.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,t.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new Un);const r=new Array;for(const[o,s]of Object.entries(t))r.push(this.attrs.set(o,s,n));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function yo(i){var t;if(i.isText){const n=i;return{type:n.type,value:n.value}}const e={type:i.type,children:i.children.map(yo)};return i.attrs&&(e.attributes=Pr((t=i.attrs)==null?void 0:t.toObject())),e}function xo(i){if(i.isText)return i.value;let e="";return i.attrs&&i.attrs.size()&&(e=" "+Array.from(i.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${xn(t.getValue())}"`}).join(" ")),`<${i.type}${e}>${i.children.map(t=>xo(t)).join("")}`}function Pa(i){if(i.isText){const e=i;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:i.type,children:i.children.map(Pa),size:i.size,isRemoved:i.isRemoved}}class Ft extends ui{constructor(t,n){super(n);J(this,"indexTree");J(this,"nodeMapByID");this.indexTree=new fc(t),this.nodeMapByID=new Ia(gt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,n){return new Ft(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[r,o]=t.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,t.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,v=u?0:m.indexOf(s)+1;for(let d=v;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):Xt:Yr;if(p.canStyle(r,w)&&n){const y=l.get(b),h=p.getCreatedAt();(!y||h.after(y))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((_,[,S])=>(S&&(_[S.getKey()]=d[S.getKey()]),_),{}),A=p.parent,T=p.prevSibling||p.parent;Object.keys(f).length>0&&v.push({type:"style",from:this.toIndex(A,T),to:this.toIndex(p,p),fromPath:this.toPath(A,T),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[_]of g)_&&a.push({parent:p,child:_})}}),[l,a,v]}removeStyle(t,n,r,o){const[s,u]=this.findNodesAndSplitText(t[0],r),[c,m]=this.findNodesAndSplitText(t[1],r),v=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):Xt:Yr;if(a.canStyle(r,b)&&n){const w=d.get(p),y=a.getCreatedAt();(!w||y.after(w))&&d.set(p,y),a.attrs||(a.attrs=new Un);for(const f of n){const A=a.attrs.remove(f,r);for(const T of A)l.push({parent:a,child:T})}const h=a.parent,g=a.prevSibling||a.parent;v.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,v]}edit(t,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(t[0],o),[v,d]=this.findNodesAndSplitText(t[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],y=new Map;this.traverseInPosRange(c,m,v,d,([f,A],T)=>{if(A===st.Start&&!T)for(const I of f.children)w.push(I);const _=f.getCreatedAt().getActorID(),S=u?u.has(_)?u.get(_):Xt:Yr;if(f.canDelete(o,S)||p.includes(f.parent)){const I=y.get(_),O=f.getCreatedAt();(!I||O.after(I))&&y.set(_,O),(A===st.Text||A===st.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,T=m;for(;f{c.isRemoved&&(_.remove(o),g.push({parent:this,child:_})),this.nodeMapByID.put(_.id,_)}),T.isRemoved||f.push(T);if(f.length){const T=f.map(_=>yo(_));h.length&&h[h.length-1].from===l?h[h.length-1].value=T:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:T})}}return[h,g,y]}editT(t,n,r,o,s){const u=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([u,c],n,r,o,s)}move(t,n,r){throw new ne(ee.ErrUnimplemented,`not implemented: ${t}, ${n}, ${r}`)}purge(t){var o;(o=t.parent)==null||o.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,r=t.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const r of n.getGCPairs())t.push(r)}),t}findPos(t,n=!0){const r=this.indexTree.findTreePos(t,n);return Zt.fromTreePos(r)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return xo(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,v;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),v=Zt.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?Pr((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:v};for(let y=0;y0&&y===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:y,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([t,n]){if(n===st.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?st.Text:st.Start]:[t,st.End]}const r=t.parent,o=r.allChildren,s=o.indexOf(t);if(r&&s===o.length-1)return[r,st.End];const u=o[s+1];return[u,u.isText?st.Text:st.Start]}findLeftToken([t,n]){if(n===st.End){const c=t.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?st.Text:st.End]}return[t,st.Start]}const r=t.parent,o=r.allChildren,s=o.indexOf(t);if(r&&s===0)return[r,st.Start];const u=o[s-1];return[u,u.isText?st.Text:st.End]}}class di extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"contents");J(this,"splitLevel");J(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(t,n,r,o,s,u,c){return new di(t,n,r,o,s,u,c)}execute(t){var c;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Ft))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Ot.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)t.registerGCPair(m);return{opInfos:s.map(({from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${t}.EDIT(${n},${r},${o.map(s=>xo(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Qn{constructor(e,t,n,r){J(this,"clientSeq");J(this,"serverSeq");J(this,"lamport");J(this,"actor");this.clientSeq=e,this.serverSeq=r,this.lamport=t,this.actor=n}static of(e,t,n,r){return new Qn(e,t,n,r)}next(){return new Qn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new Qn(this.clientSeq,e,this.actor):new Qn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return Ot.of(this.lamport,e,this.actor)}setActor(e){return new Qn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const pc=new Qn(0,Re.fromInt(0,!0),Hi);class Br{constructor({id:e,operations:t,presenceChange:n,message:r}){J(this,"id");J(this,"operations");J(this,"presenceChange");J(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=r}static create({id:e,operations:t,presenceChange:n,message:r}){return new Br({id:e,operations:t,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(e,n);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===ir.Put?t.set(this.id.getActorID(),Gt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ct.bytesToHex(ct.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ct.bytesToHex(ct.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:r,message:o}=e;return Br.create({id:ct.bytesToChangeID(ct.hexToBytes(t)),operations:n==null?void 0:n.map(s=>ct.bytesToOperation(ct.hexToBytes(s))),presenceChange:r,message:o})}}class Gi{constructor(e,t,n,r,o,s){J(this,"documentKey");J(this,"checkpoint");J(this,"isRemoved");J(this,"changes");J(this,"snapshot");J(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=r,this.snapshot=o,this.minSyncedTicket=s}static create(e,t,n,r,o,s){return new Gi(e,t,n,r,o,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Cr{constructor(e,t){J(this,"serverSeq");J(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new Cr(e,t)}increaseClientSeq(e){return e===0?this:new Cr(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return Cr.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const mc=new Cr(Re.fromInt(0,!0),0);class Nn{constructor(e,t){J(this,"createdAt");J(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Nn(e,t)}static fromStruct(e){return Nn.of(Ot.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Nn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const yc=Nn.of(Xt,0);class Qt{constructor(e,t){J(this,"id");J(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Qt(e,t)}static fromStruct(e){const t=Nn.fromStruct(e.id);return Qt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Nn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class nr extends Sa{constructor(t,n,r){super(n);J(this,"id");J(this,"removedAt");J(this,"prev");J(this,"next");J(this,"insPrev");J(this,"insNext");this.id=t,this.removedAt=r}static create(t,n){return new nr(t,n)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let r=e;for(;r&&r!==t;)n.push(r),r=r.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new ne(ee.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const r=e.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(e,t,n),s=new Map,u=new Map,c=this.makeChanges(o,t);for(const m of r){const v=m.getCreatedAt().getActorID();(!s.has(v)||m.getID().getCreatedAt().after(s.get(v)))&&s.set(v,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(t)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(e,t,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(e);s.push(u);for(const m of e){const v=m.getCreatedAt().getActorID(),d=r?n.has(v)?n.get(v):Xt:Yr;m.canDelete(t,d)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var In=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(In||{});class Dt extends ui{constructor(t,n,r){super(r);J(this,"valueType");J(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Re.fromNumber(n).toInt():this.value=vs(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Re.fromNumber(n):this.value=n;break;default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,r){return new Dt(t,n,r)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Re.fromBytesLE(Array.from(n));default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=Dt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Re?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!Dt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ut.Long?this.value=this.value+t.getValue().toInt():this.value=Re.fromNumber(this.value+vs(t.getValue())).toInt(),this}}class Fr extends en{constructor(t,n,r){super(t,r);J(this,"value");this.value=n}static create(t,n,r){return new Fr(t,n,r)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Dt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===ut.Long?t.getValue().multiply(-1):t.getValue()*-1;return Fr.create(this.getParentCreatedAt(),Xe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class jn extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"attributes");J(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(t,n,r,o,s,u){return new jn(t,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(t,n,r,o,s,u){return new jn(t,n,r,o,new Map,s,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Ft))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:v,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:v,toPath:d,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([o,s])=>`${o}:"${s}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function vc(i){const e=new Eo,t=e.data;for(const[n,r]of Object.entries(i))t[n]=JSON.stringify(r);return e}function bc(i){if(i.type===ir.Put)return new go({type:ti.PUT,presence:vc(i.presence)});if(i.type===ir.Clear)return new go({type:ti.CLEAR});throw new ne(ee.ErrUnimplemented,"unimplemented type")}function wc(i){return new wa({serverSeq:i.getServerSeqAsString(),clientSeq:i.getClientSeq()})}function Ca(i){return new Vi({clientSeq:i.getClientSeq(),lamport:i.getLamportAsString(),actorId:Lo(i.getActorID())})}function Ee(i){if(i)return new ke({lamport:i.getLamportAsString(),delimiter:i.getDelimiter(),actorId:Lo(i.getActorID())})}function Ra(i){switch(i){case ut.Null:return Le.NULL;case ut.Boolean:return Le.BOOLEAN;case ut.Integer:return Le.INTEGER;case ut.Long:return Le.LONG;case ut.Double:return Le.DOUBLE;case ut.String:return Le.STRING;case ut.Bytes:return Le.BYTES;case ut.Date:return Le.DATE;default:throw new ne(ee.ErrInvalidType,`unsupported type: ${i}`)}}function Da(i){switch(i){case In.IntegerCnt:return Le.INTEGER_CNT;case In.LongCnt:return Le.LONG_CNT;default:throw new ne(ee.ErrInvalidType,`unsupported type: ${i}`)}}function oo(i){if(i instanceof St)return new Dn({type:Le.JSON_OBJECT,createdAt:Ee(i.getCreatedAt()),value:Ha(i)});if(i instanceof Rt)return new Dn({type:Le.JSON_ARRAY,createdAt:Ee(i.getCreatedAt()),value:Gc(i)});if(i instanceof qt)return new Dn({type:Le.TEXT,createdAt:Ee(i.getCreatedAt())});if(i instanceof Xe)return new Dn({type:Ra(i.getType()),createdAt:Ee(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Dn({type:Da(i.getType()),createdAt:Ee(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Ft)return new Dn({type:Le.TREE,createdAt:Ee(i.getCreatedAt()),value:Zc(i)});throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Ac(i){return new ho({createdAt:Ee(i.getCreatedAt()),offset:i.getOffset()})}function Ei(i){return new mr({createdAt:Ee(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function Oi(i){return new ei({parentId:Zr(i.getParentID()),leftSiblingId:Zr(i.getLeftSiblingID())})}function Zr(i){return new Ir({createdAt:Ee(i.getCreatedAt()),offset:i.getOffset()})}function La(i){const e=new Ao;if(i instanceof yr){const t=i,n=new na;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.key=t.getKey(),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(i instanceof ci){const t=i,n=new ra;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.prevCreatedAt=Ee(t.getPrevCreatedAt()),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(i instanceof er){const t=i,n=new ia;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.prevCreatedAt=Ee(t.getPrevCreatedAt()),n.createdAt=Ee(t.getCreatedAt()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(i instanceof or){const t=i,n=new oa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.createdAt=Ee(t.getCreatedAt()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(i instanceof fi){const t=i,n=new sa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Ei(t.getFromPos()),n.to=Ei(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);n.content=t.getContent();const o=n.attributes;for(const[s,u]of t.getAttributes())o[s]=u;n.executedAt=Ee(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(i instanceof hi){const t=i,n=new aa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Ei(t.getFromPos()),n.to=Ei(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);const o=n.attributes;for(const[s,u]of t.getAttributes())o[s]=u;n.executedAt=Ee(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(i instanceof Fr){const t=i,n=new la;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(i instanceof di){const t=i,n=new ua,r=n.createdAtMapByActor;for(const[o,s]of t.getMaxCreatedAtMapByActor())r[o]=Ee(s);n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Oi(t.getFromPos()),n.to=Oi(t.getToPos()),n.contents=xc(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=Ee(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(i instanceof jn){const t=i,n=new ca;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Oi(t.getFromPos()),n.to=Oi(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);const o=t.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of t.getAttributes())s[u]=c}n.executedAt=Ee(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new ne(ee.ErrUnimplemented,"unimplemented operation");return e}function Tc(i){const e=[];for(const t of i)e.push(La(t));return e}function _c(i){const e=new ta({id:Ca(i.getID()),message:i.getMessage()});return i.hasOperations()&&(e.operations=Tc(i.getOperations())),i.hasPresenceChange()&&(e.presenceChange=bc(i.getPresenceChange())),e}function Ec(i){const e=[];for(const t of i)e.push(_c(t));return e}function Oc(i){const e=[];for(const t of i)e.push(new ya({key:t.getStrKey(),element:Io(t.getValue())}));return e}function Sc(i){const e=[];for(const t of i)e.push(new To({element:Io(t.getValue())}));return e}function kc(i){const e=[];for(const t of i){const n=new va;n.id=Ac(t.getID()),n.value=t.getValue().getContent(),n.removedAt=Ee(t.getRemovedAt());const r=n.attributes,o=t.getValue().getAttrs();for(const s of o){const u=new Ki;u.value=s.getValue(),u.updatedAt=Ee(s.getUpdatedAt()),r[s.getKey()]=u}e.push(n)}return e}function xc(i){const e=[];if(!i||!i.length)return e;for(const t of i)e.push(new ba({content:No(t)}));return e}function Nc(i){const e={};for(const t of i)e[t.getKey()]=new Ki({value:t.getValue(),updatedAt:Ee(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function No(i){if(!i)return[];const e=[];return Wi(i,(t,n)=>{const r=new _o({id:Zr(t.id),type:t.type,removedAt:Ee(t.removedAt),depth:n});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Zr(t.insPrevID)),t.insNextID&&(r.insNextId=Zr(t.insNextID)),t.attrs&&(r.attributes=Nc(t.attrs)),e.push(r)}),e}function Ic(i){const e=new jt;return e.body.case="jsonObject",e.body.value=new fa({nodes:Oc(i.getRHT()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Ma(i){const e=new jt;return e.body.case="jsonArray",e.body.value=new ha({nodes:Sc(i.getElements()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Pc(i){const e=new jt;return e.body.case="primitive",e.body.value=new da({type:Ra(i.getType()),value:i.toBytes(),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Cc(i){const e=new jt;return e.body.case="text",e.body.value=new ga({nodes:kc(i.getRGATreeSplit()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Rc(i){const e=new jt;return e.body.case="counter",e.body.value=new pa({type:Da(i.getType()),value:i.toBytes(),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Ba(i){const e=new jt;return e.body.case="tree",e.body.value=new ma({nodes:No(i.getRoot()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Io(i){if(i instanceof St)return Ic(i);if(i instanceof Rt)return Ma(i);if(i instanceof Xe)return Pc(i);if(i instanceof qt)return Cc(i);if(i instanceof Dt)return Rc(i);if(i instanceof Ft)return Ba(i);throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Dc(i){return new $n({documentKey:i.getDocumentKey(),checkpoint:wc(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:Ec(i.getChanges()),snapshot:i.getSnapshot(),minSyncedTicket:Ee(i.getMinSyncedTicket())})}function bs(i){const e=i.findDetails(Xu);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function qa(i){let e;return i.serverSeq&&(e=Re.fromString(i.serverSeq,!0)),Qn.of(i.clientSeq,Re.fromString(i.lamport,!0),Do(i.actorId),e)}function Se(i){if(i)return Ot.of(Re.fromString(i.lamport,!0),i.delimiter,Do(i.actorId))}function Po(i){const e={};return Object.entries(i.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Lc(i){const e=i.type;if(e===ti.PUT){const t=Po(i.presence);return{type:ir.Put,presence:t}}if(e===ti.CLEAR)return{type:ir.Clear};throw new ne(ee.ErrInvalidType,`unsupported type: ${e}`)}function Mc(i){const e=new Map;return Object.entries(i).forEach(([t,n])=>{e.set(t,Po(n))}),e}function Fa(i){switch(i){case Le.NULL:return ut.Null;case Le.BOOLEAN:return ut.Boolean;case Le.INTEGER:return ut.Integer;case Le.LONG:return ut.Long;case Le.DOUBLE:return ut.Double;case Le.STRING:return ut.String;case Le.BYTES:return ut.Bytes;case Le.DATE:return ut.Date}throw new ne(ee.ErrUnimplemented,`unimplemented value type: ${i}`)}function $i(i){switch(i){case Le.INTEGER_CNT:return In.IntegerCnt;case Le.LONG_CNT:return In.LongCnt}throw new ne(ee.ErrUnimplemented,`unimplemented value type: ${i}`)}function so(i){switch(i.type){case Le.JSON_OBJECT:return i.value?Ka(i.value):St.create(Se(i.createdAt));case Le.JSON_ARRAY:return i.value?Wc(i.value):Rt.create(Se(i.createdAt));case Le.TEXT:return qt.create(qr.create(),Se(i.createdAt));case Le.TREE:return Yc(i.value);case Le.NULL:case Le.BOOLEAN:case Le.INTEGER:case Le.LONG:case Le.DOUBLE:case Le.STRING:case Le.BYTES:case Le.DATE:return Xe.of(Xe.valueFromBytes(Fa(i.type),i.value),Se(i.createdAt));case Le.INTEGER_CNT:case Le.LONG_CNT:return Dt.create($i(i.type),Dt.valueFromBytes($i(i.type),i.value),Se(i.createdAt))}}function Si(i){return Qt.of(Nn.of(Se(i.createdAt),i.offset),i.relativeOffset)}function ja(i){return Nn.of(Se(i.createdAt),i.offset)}function Bc(i){const e=oi.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{e.setAttr(n,r.value,Se(r.updatedAt))});const t=nr.create(ja(i.id),e);return t.remove(Se(i.removedAt)),t}function Er(i){return Zt.of(Xr(i.parentId),Xr(i.leftSiblingId))}function Xr(i){return gt.of(Se(i.createdAt),i.offset)}function qc(i){if(!i.length)return;const e=[];return i.forEach(t=>{const n=Co(t.content);e.push(n)}),e}function Co(i){if(i.length===0)return;const e=[];for(const r of i)e.push(jc(r));const t=e[e.length-1],n=new Map;n.set(i[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(e[r]),n.set(i[r].depth,e[r]);return t.updateDescendantsSize(),Ft.create(t,Xt).getRoot()}function Fc(i){const e=Un.create();for(const[t,n]of Object.entries(i))e.setInternal(t,n.value,Se(n.updatedAt),n.isRemoved);return e}function jc(i){const e=Xr(i.id),t=Ct.create(e,i.type),n=Object.entries(i.attributes);return t.isText?t.value=i.value:n.length&&(t.attrs=Fc(i.attributes)),i.insPrevId&&(t.insPrevID=Xr(i.insPrevId)),i.insNextId&&(t.insNextID=Xr(i.insNextId)),t.removedAt=Se(i.removedAt),t}function Ua(i){if(i.body.case==="set"){const e=i.body.value;return yr.create(e.key,so(e.value),Se(e.parentCreatedAt),Se(e.executedAt))}else if(i.body.case==="add"){const e=i.body.value;return ci.create(Se(e.parentCreatedAt),Se(e.prevCreatedAt),so(e.value),Se(e.executedAt))}else if(i.body.case==="move"){const e=i.body.value;return er.create(Se(e.parentCreatedAt),Se(e.prevCreatedAt),Se(e.createdAt),Se(e.executedAt))}else if(i.body.case==="remove"){const e=i.body.value;return or.create(Se(e.parentCreatedAt),Se(e.createdAt),Se(e.executedAt))}else if(i.body.case==="edit"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,o])=>{t.set(r,Se(o))});const n=new Map;return Object.entries(e.attributes).forEach(([r,o])=>{n.set(r,o)}),fi.create(Se(e.parentCreatedAt),Si(e.from),Si(e.to),t,e.content,n,Se(e.executedAt))}else if(i.body.case==="style"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,o])=>{t.set(r,Se(o))});const n=new Map;return Object.entries(e.attributes).forEach(([r,o])=>{n.set(r,o)}),hi.create(Se(e.parentCreatedAt),Si(e.from),Si(e.to),t,n,Se(e.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const e=i.body.value;return Fr.create(Se(e.parentCreatedAt),so(e.value),Se(e.executedAt))}else if(i.body.case==="treeEdit"){const e=i.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,r])=>{t.set(n,Se(r))}),di.create(Se(e.parentCreatedAt),Er(e.from),Er(e.to),qc(e.contents),e.splitLevel,t,Se(e.executedAt))}else if(i.body.case==="treeStyle"){const e=i.body.value,t=new Map,n=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Se(s))}),(n==null?void 0:n.length)>0?jn.createTreeRemoveStyleOperation(Se(e.parentCreatedAt),Er(e.from),Er(e.to),r,n,Se(e.executedAt)):(Object.entries(e.attributes).forEach(([o,s])=>{t.set(o,s)}),jn.create(Se(e.parentCreatedAt),Er(e.from),Er(e.to),r,t,Se(e.executedAt)))}else throw new ne(ee.ErrUnimplemented,"unimplemented operation")}}function Uc(i){const e=[];for(const t of i){const n=Ua(t);n&&e.push(n)}return e}function $a(i){const e=[];for(const t of i)e.push(Br.create({id:qa(t.id),operations:Uc(t.operations),presenceChange:t.presenceChange?Lc(t.presenceChange):void 0,message:t.message}));return e}function $c(i){return Cr.of(Re.fromString(i.serverSeq,!0),i.clientSeq)}function zc(i){return Gi.create(i.documentKey,$c(i.checkpoint),i.isRemoved,$a(i.changes),i.snapshot,Se(i.minSyncedTicket))}function za(i){const e=new ni;for(const n of i.nodes){const r=Ro(n.element);e.set(n.key,r,r.getPositionedAt())}const t=new St(Se(i.createdAt),e);return t.setMovedAt(Se(i.movedAt)),t.setRemovedAt(Se(i.removedAt)),t}function Ja(i){const e=new ii;for(const n of i.nodes)e.insert(Ro(n.element));const t=new Rt(Se(i.createdAt),e);return t.setMovedAt(Se(i.movedAt)),t.setRemovedAt(Se(i.removedAt)),t}function Jc(i){const e=Xe.of(Xe.valueFromBytes(Fa(i.type),i.value),Se(i.createdAt));return e.setMovedAt(Se(i.movedAt)),e.setRemovedAt(Se(i.removedAt)),e}function Vc(i){const e=new qr;let t=e.getHead();for(const r of i.nodes){const o=e.insertAfter(t,Bc(r));r.insPrevId&&o.setInsPrev(e.findNode(ja(r.insPrevId))),t=o}const n=new qt(e,Se(i.createdAt));return n.setMovedAt(Se(i.movedAt)),n.setRemovedAt(Se(i.removedAt)),n}function Kc(i){const e=Dt.create($i(i.type),Dt.valueFromBytes($i(i.type),i.value),Se(i.createdAt));return e.setMovedAt(Se(i.movedAt)),e.setRemovedAt(Se(i.removedAt)),e}function Va(i){const e=Co(i.nodes);return Ft.create(e,Se(i.createdAt))}function Ro(i){if(i.body.case==="jsonObject")return za(i.body.value);if(i.body.case==="jsonArray")return Ja(i.body.value);if(i.body.case==="primitive")return Jc(i.body.value);if(i.body.case==="text")return Vc(i.body.value);if(i.body.case==="counter")return Kc(i.body.value);if(i.body.case==="tree")return Va(i.body.value);throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Hc(i){if(!i)return{root:St.create(Xt),presences:new Map};const e=xu.fromBinary(i);return{root:Ro(e.root),presences:Mc(e.presences)}}function Ka(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return za(e.body.value)}function Ha(i){return Io(i).toBinary()}function Wc(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return Ja(e.body.value)}function Gc(i){return Ma(i).toBinary()}function Yc(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return Va(e.body.value)}function Zc(i){return Ba(i).toBinary()}function Wa(i){return i?Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function Do(i){return Wa(i)}function Ga(i){return new Uint8Array(i.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Lo(i){return Ga(i)}function Xc(i){const e=Vi.fromBinary(i);return qa(e)}function Qc(i){const e=Ao.fromBinary(i);return Ua(e)}const ct={fromPresence:Po,toChangePack:Dc,fromChangePack:zc,fromChanges:$a,toTreeNodes:No,fromTreeNodes:Co,objectToBytes:Ha,bytesToObject:Ka,bytesToSnapshot:Hc,bytesToHex:Wa,hexToBytes:Ga,toHexString:Do,toUint8Array:Lo,toOperation:La,toChangeID:Ca,PbChangeID:Vi,bytesToChangeID:Xc,bytesToOperation:Qc};var bt=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(bt||{});let lr=3;function Ya(i){lr=i}const xe={trivial:(...i)=>{lr>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{lr>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{lr>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{lr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{lr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>lr<=i};function Za(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}class ef{constructor(e,t,n,r,o){J(this,"reconnectStreamDelay");J(this,"doc");J(this,"docID");J(this,"syncMode");J(this,"remoteChangeEventReceived");J(this,"watchStream");J(this,"watchLoopTimerID");J(this,"watchAbortController");J(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Mi.RealtimeSyncOff?!1:this.syncMode===Mi.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Mi.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const ao=()=>{};class tf{constructor(e){J(this,"finalized",!1);J(this,"observers",[]);J(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(!e)throw new ne(ee.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(ee.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:n},r.next===void 0&&(r.next=ao),r.error===void 0&&(r.error=ao),r.complete===void 0&&(r.complete=ao);const o=Za(),s=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(u){xe.warn(u)}return s}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Nr{constructor(e,t,n,r){J(this,"id");J(this,"delimiter");J(this,"message");J(this,"root");J(this,"operations");J(this,"presenceChange");J(this,"previousPresence");J(this,"reversePresenceKeys");this.id=e,this.delimiter=So,this.root=t,this.operations=[],this.previousPresence=Gt(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,n,r){return new Nr(e,t,n,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Br.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class si{constructor(e){J(this,"rootObject");J(this,"elementPairMapByCreatedAt");J(this,"gcElementSetByCreatedAt");J(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof qt||t instanceof Ft)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new si(St.create(Xt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const r=t.element.getCreatedAt(),o=t.parent.subPathOf(r);if(o===void 0)throw new ne(ee.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tr&&e.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(e){let t=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),t++};return n(e),e instanceof tr&&e.getDescendants(r=>(n(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof tr&&n.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new si(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n);r.element.getRemovedAt()&&e.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r!==void 0&&e.compare(r)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Xa(i,e){const t=new ai(i);return new Proxy(e,t.getHandlers())}class ai{constructor(e){J(this,"context");J(this,"handlers");this.context=e,this.handlers={set:(t,n,r)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]=${JSON.stringify(r)}`),ai.setInternal(e,t,n,r),!0),get:(t,n)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():ur(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]`),ai.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,r){if(n.includes("."))throw new ne(ee.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),s=zi(e,r,o),u=t.set(n,s,o);e.registerElement(s,t),u&&e.registerRemovedElement(u),e.push(yr.create(n,s.deepcopy(),t.getCreatedAt(),o))}static buildObjectMembers(e,t){const n={};for(const[r,o]of Object.entries(t)){if(r.includes("."))throw new ne(ee.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),u=zi(e,o,s);n[r]=u}return n}static deleteInternal(e,t,n){const r=e.issueTimeTicket(),o=t.deleteByKey(n,r);o&&(e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o))}getHandlers(){return this.handlers}}function rf(i,e){const t=new et(i,e);return new Proxy(e,t.getHandlers())}function of(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function sf(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class et{constructor(e,t){J(this,"context");J(this,"handlers");J(this,"array");this.context=e,this.array=t,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return Wn(e,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return Wn(e,u)}:r==="getLast"?()=>Wn(e,n.getLast()):r==="deleteByID"?s=>{const u=et.deleteInternalByID(e,n,s);return Wn(e,u)}:r==="insertAfter"?(s,u)=>{const c=et.insertAfterInternal(e,n,s,u);return Wn(e,c)}:r==="insertBefore"?(s,u)=>{const c=et.insertBeforeInternal(e,n,s,u);return Wn(e,c)}:r==="moveBefore"?(s,u)=>{et.moveBeforeInternal(e,n,s,u)}:r==="moveAfter"?(s,u)=>{et.moveAfterInternal(e,n,s,u)}:r==="moveFront"?s=>{et.moveFrontInternal(e,n,s)}:r==="moveLast"?s=>{et.moveLastInternal(e,n,s)}:of(r)?ur(e,n.get(Number(r))):r==="push"?s=>et.pushInternal(e,n,s):r==="splice"?(s,u,...c)=>et.splice(e,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?et.iteratorInternal.bind(this,e,n):r==="includes"?(s,u)=>et.includes(e,n,s,u):r==="indexOf"?(s,u)=>et.indexOf(e,n,s,u):r==="lastIndexOf"?(s,u)=>et.lastIndexOf(e,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>et.toTestString(n):typeof r=="string"&&sf(r)?(...s)=>{const u=Array.from(n).map(c=>ur(e,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`array[${r}]`),et.deleteInternalByIndex(e,n,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield Wn(e,n)}static buildArrayElements(e,t){const n=[];for(const r of t){const o=e.issueTimeTicket(),s=zi(e,r,o);n.push(s)}return n}static pushInternal(e,t,n){return et.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,r){const o=e.issueTimeTicket(),s=t.getPrevCreatedAt(n);t.moveAfter(s,r,o),e.push(er.create(t.getCreatedAt(),s,r,o))}static moveAfterInternal(e,t,n,r){const o=e.issueTimeTicket();t.moveAfter(n,r,o),e.push(er.create(t.getCreatedAt(),n,r,o))}static moveFrontInternal(e,t,n){const r=e.issueTimeTicket(),o=t.getHead();t.moveAfter(o.getCreatedAt(),n,r),e.push(er.create(t.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(e,t,n){const r=e.issueTimeTicket(),o=t.getLastCreatedAt();t.moveAfter(o,n,r),e.push(er.create(t.getCreatedAt(),o,n,r))}static insertAfterInternal(e,t,n,r){const o=e.issueTimeTicket(),s=zi(e,r,o);return t.insertAfter(n,s),e.registerElement(s,t),e.push(ci.create(t.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(e,t,n,r){return et.insertAfterInternal(e,t,t.getPrevCreatedAt(n),r)}static deleteInternalByIndex(e,t,n){const r=e.issueTimeTicket(),o=t.deleteByIndex(n,r);if(o)return e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o),o}static deleteInternalByID(e,t,n){const r=e.issueTimeTicket(),o=t.delete(n,r);return e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o),o}static splice(e,t,n,r,...o){const s=t.length,u=n>=0?Math.min(n,s):Math.max(s+n,0),c=r===void 0?s:r<0?u:Math.min(u+r,s),m=[];for(let v=u;v=o)return!1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).includes(n,s);for(let c=s;c=o)return-1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=t.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let Yi=class{constructor(e,t){J(this,"context");J(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,r){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(e,t);xe.isEnabled(bt.Debug)&&xe.debug(`EDIT: f:${e}->${o[0].toTestString()}, t:${t}->${o[1].toTestString()} c:${n}`);const s=r?Mr(r):void 0,u=this.context.issueTimeTicket(),[c,,m,v]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new fi(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(v)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);xe.isEnabled(bt.Debug)&&xe.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Mr(n),s=this.context.issueTimeTicket(),[u,c]=this.text.setStyle(r,o,s);for(const m of c)this.context.registerGCPair(m);return this.context.push(new hi(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Qt.fromStruct(e[0]),Qt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class Zi{constructor(e,t){J(this,"valueType");J(this,"value");J(this,"context");J(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ne(ee.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=Xe.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Fr.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(ee.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Mo(i,e,t){const{type:n}=i,r=t.issueTimeTicket();if(n===Fn){Qa(i);const{value:o}=i,s=Ct.create(gt.of(r,0),n,o);e.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!Oa(s)){const m=Mr(s);u=new Un;for(const[v,d]of Object.entries(m))u.set(v,d,r)}const c=Ct.create(gt.of(r,0),n,void 0,u);e.append(c);for(const m of o)Mo(m,c,t)}}function af(i,e){const{type:t}=e,n=i.issueTimeTicket();let r;if(e.type===Fn){const{value:o}=e;r=Ct.create(gt.of(n,0),t,o)}else if(e){const{children:o=[]}=e,{attributes:s}=e;let u;if(typeof s=="object"&&!Oa(s)){const c=Mr(s);u=new Un;for(const[m,v]of Object.entries(c))u.set(m,v,n)}r=Ct.create(gt.of(i.issueTimeTicket(),0),t,void 0,u);for(const c of o)Mo(c,r,i)}return r}function Qa(i){if(!i.value.length)throw new ne(ee.ErrInvalidArgument,"text node cannot have empty value");return!0}function ws(i){if(!i.length)return!0;if(i[0].type===Fn)for(const t of i){const{type:n}=t;if(n!==Fn)throw new ne(ee.ErrInvalidArgument,"element node and text node cannot be passed together");Qa(t)}else for(const t of i){const{type:n}=t;if(n===Fn)throw new ne(ee.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Xi{constructor(e){J(this,"initialRoot");J(this,"context");J(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ct.create(gt.of(e.issueTimeTicket(),0),ac);const t=Ct.create(gt.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Mo(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(e),o=this.context.issueTimeTicket(),s=t?Mr(t):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(jn.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(e,t,n){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),o=this.tree.findPos(t),s=this.context.issueTimeTicket(),u=n?Mr(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const v of m)this.context.registerGCPair(v);this.context.push(jn.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),o=this.tree.findPos(t),s=this.context.issueTimeTicket(),[u,c]=this.tree.removeStyle([r,o],n,s);for(const m of c)this.context.registerGCPair(m);this.context.push(jn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(e,t,n,r=0){var m;if(n.length!==0&&n[0]&&(ws(n),n[0].type!==Fn))for(const v of n){const{children:d=[]}=v;ws(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Fn){let v="";for(const d of n){const{value:l}=d;v+=l}s.push(Ct.create(gt.of(this.context.issueTimeTicket(),0),Fn,v))}else s=n.map(v=>v&&af(this.context,v)).filter(v=>v);const[,u,c]=this.tree.edit([e,t],s.length?s.map(v=>v==null?void 0:v.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const v of u)this.context.registerGCPair(v);return this.context.push(di.create(this.tree.getCreatedAt(),e,t,s.length?s:void 0,r,c,o)),!0}editByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ne(ee.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ne(ee.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(o,s,n,r)}edit(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(o,s,n?[n]:[],r)}editBulk(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[Zt.fromStruct(e[0]),Zt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[Zt.fromStruct(e[0]),Zt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function As(i,e){return Xa(i,e)}function Wn(i,e){if(e){if(e instanceof Xe)return e;if(e instanceof St)return Xa(i,e);if(e instanceof Rt)return rf(i,e);if(e instanceof qt)return new Yi(i,e);if(e instanceof Dt){const t=new Zi(In.IntegerCnt,0);return t.initialize(i,e),t}else if(e instanceof Ft){const t=new Xi;return t.initialize(i,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ur(i,e){const t=Wn(i,e);return t instanceof Xe?t.getValue():t}function zi(i,e,t){let n;if(Xe.isSupport(e))n=Xe.of(e,t);else if(Array.isArray(e))n=Rt.create(t,et.buildArrayElements(i,e));else if(typeof e=="object")e instanceof Yi?(n=qt.create(qr.create(),t),e.initialize(i,n)):e instanceof Zi?(n=Dt.create(e.getValueType(),e.getValue(),t),e.initialize(i,n)):e instanceof Xi?(n=Ft.create(e.buildRoot(i),t),e.initialize(i,n)):n=St.create(t,ai.buildObjectMembers(i,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Ts=50;class lf{constructor(){J(this,"undoStack",[]);J(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Ts&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Ts&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const uf="yorkie-devtools-panel",cf="yorkie-devtools-sdk";let Or="disconnected";const _s=new Map,Li=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Li);function ki(i,e){(e!=null&&e.force||Or!=="disconnected")&&window.postMessage({source:cf,...i},"*")}function ff(i){if(!i.isEnableDevtools()||typeof window>"u"||_s.has(i.getKey()))return;Li.set(i.getKey(),[]);const e=i.subscribe("all",t=>{t.some(n=>n.type!==dt.StatusChanged&&n.type!==dt.Snapshot&&n.type!==dt.LocalChange&&n.type!==dt.RemoteChange&&n.type!==dt.Initialized&&n.type!==dt.Watched&&n.type!==dt.Unwatched&&n.type!==dt.PresenceChanged)||(Li.get(i.getKey()).push(t),Or==="synced"&&ki({msg:"doc::sync::partial",docKey:i.getKey(),event:t}))});_s.set(i.getKey(),[e]),ki({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==uf)return;switch(t.data.msg){case"devtools::connect":if(Or!=="disconnected")break;Or="connected",ki({msg:"doc::available",docKey:i.getKey()}),xe.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Or="disconnected",xe.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Or="synced",ki({msg:"doc::sync::full",docKey:i.getKey(),events:Li.get(i.getKey())}),xe.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var Gn=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(Gn||{}),dt=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(dt||{}),li=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(li||{}),vo=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(vo||{});class el{constructor(e,t){J(this,"key");J(this,"status");J(this,"opts");J(this,"changeID");J(this,"checkpoint");J(this,"localChanges");J(this,"root");J(this,"clone");J(this,"eventStream");J(this,"eventStreamObserver");J(this,"onlineClients");J(this,"presences");J(this,"history");J(this,"internalHistory");J(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=si.create(),this.changeID=pc,this.checkpoint=mc,this.localChanges=[],this.eventStream=nf(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new lf,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ff(this)}update(e,t){if(this.getStatus()==="removed")throw new ne(ee.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const o=As(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(o,new io(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){xe.isEnabled(bt.Trivial)&&xe.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ge.Local),c=r.getReversePresence();c&&u.push({type:"presence",value:c}),this.localChanges.push(o),u.length>0&&this.internalHistory.pushUndo(u),s.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const m=[];s.length>0&&m.push({type:"local-change",source:Ge.Local,value:{message:o.getMessage()||"",operations:s,actor:n,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&m.push({type:"presence-changed",source:Ge.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),xe.isEnabled(bt.Trivial)&&xe.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,r){if(typeof e=="string"){if(typeof t!="function")throw new ne(ee.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||u(m)},n,r)}if(e==="my-presence"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="presence-changed"||m.type==="presence-changed"&&m.value.clientID!==this.changeID.getActorID()||u(m)},n,r)}if(e==="others"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||m.value.clientID!==this.changeID.getActorID()&&u(m)},n,r)}if(e==="connection"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(e==="status"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(e==="sync"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(e==="local-broadcast"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(e==="broadcast"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(e==="all"){const u=t;return this.eventStream.subscribe(u,n,r)}const o=e,s=t;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const v of c.value.operations)this.isSameElementOrChildOf(v.path,o)&&m.push(v);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof e=="function"){const o=e,s=t,u=n;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="snapshot"&&m.type!=="local-change"&&m.type!=="remote-change"||o(m)},s,u)}throw new ne(ee.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((o,s)=>o===n[s])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Ge.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,Ge.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),xe.isEnabled(bt.Trivial)&&xe.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Gt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Gi.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return As(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:r}=ct.bytesToSnapshot(t);this.root=new si(n),this.presences=r,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:Ge.Remote,value:{snapshot:this.isEnableDevtools()?ct.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){xe.isEnabled(bt.Debug)&&xe.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),xe.isEnabled(bt.Trivial)&&xe.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class ui{constructor(e){J(this,"createdAt");J(this,"movedAt");J(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class tr extends ui{constructor(e){super(e)}}class ko{constructor(e,t){J(this,"strKey");J(this,"value");this.strKey=e,this.value=t}static of(e,t){return new ko(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class ni{constructor(){J(this,"nodeMapByKey");J(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new ni}set(e,t,n){let r;const o=this.nodeMapByKey.get(e);o!=null&&!o.isRemoved()&&o.remove(n)&&(r=o.getValue());const s=ko.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(o==null||n.after(o.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(n)),r}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ne(ee.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const n=this.nodeMapByCreatedAt.get(e.toIDString());return n.remove(t),n.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ne(ee.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const n=this.nodeMapByKey.get(t.getStrKey());t===n&&this.nodeMapByKey.delete(n.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const n=this.nodeMapByKey.get(e);if(n!=null&&n.remove(t))return n.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class St extends tr{constructor(t,n){super(t);J(this,"memberNodes");this.memberNodes=n}static create(t,n){if(!n)return new St(t,ni.create());const r=ni.create();for(const[o,s]of Object.entries(n))r.set(o,s.deepcopy(),s.getCreatedAt());return new St(t,r)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,n,r){return this.memberNodes.set(t,n,r)}delete(t,n){return this.memberNodes.delete(t,n)}deleteByKey(t,n){return this.memberNodes.deleteByKey(t,n)}get(t){const n=this.memberNodes.get(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.memberNodes.getByID(t);return n==null?void 0:n.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[n,r]of this)t.push(`"${xn(n)}":${r.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[n,r]of this){const{createdAt:o,value:s,type:u}=r.toJSForTest();t[n]={key:n,createdAt:o,value:s,type:u}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[n]of this)t.push(n);return t}toSortedJSON(){var r;const t=Array();for(const[o]of this)t.push(o);const n=[];for(const o of t.sort()){const s=(r=this.memberNodes.get(o))==null?void 0:r.getValue();n.push(`"${xn(o)}":${s.toSortedJSON()}`)}return`{${n.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=St.create(this.getCreatedAt());for(const n of this.memberNodes)t.memberNodes.set(n.getStrKey(),n.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const n of this.memberNodes){const r=n.getValue();if(t(r,this))return;r instanceof tr&&r.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const n of this.memberNodes)t.has(n.getStrKey())||(t.add(n.getStrKey()),n.isRemoved()||(yield[n.getStrKey(),n.getValue()]))}}var Ge=(i=>(i.Local="local",i.Remote="remote",i.UndoRedo="undoredo",i))(Ge||{});class en{constructor(e,t){J(this,"parentCreatedAt");J(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ne(ee.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Sa{constructor(e){J(this,"value");J(this,"left");J(this,"right");J(this,"parent");J(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class ri{constructor(e){J(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ne(ee.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return this.splayNode(t),[t,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new ri(e.getLeft());t.root&&t.root.setParent();const n=new ri(e.getRight());if(n.root&&n.root.setParent(),t.root){const r=t.getRightmost();t.splayNode(r),t.root.setRight(n.root),n.root&&n.root.setParent(t.root),this.root=t.root}else this.root=n.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const n of t)n.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var ut=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(ut||{});class Xe extends ui{constructor(t,n){super(n);J(this,"valueType");J(this,"value");this.valueType=Xe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new Xe(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(o,s){r.setUint8(s,o)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Re.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Re.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${xn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=Xe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Re)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return Xe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=Re.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Ui extends Sa{constructor(t){super(t);J(this,"prev");J(this,"next");this.value=t}static createAfter(t,n){const r=new Ui(n),o=t.next;return t.next=r,r.prev=t,r.next=o,o&&(o.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class ii{constructor(){J(this,"dummyHead");J(this,"last");J(this,"nodeMapByIndex");J(this,"nodeMapByCreatedAt");const e=Xe.of(0,Xt);e.setRemovedAt(Xt),this.dummyHead=new Ui(e),this.last=this.dummyHead,this.nodeMapByIndex=new ri,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new ii}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,n),o=Ui.createAfter(r,t);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(e,t,n){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const o=this.nodeMapByCreatedAt.get(t.toIDString());if(!o)throw new ne(ee.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==o&&(!o.getValue().getMovedAt()||n.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(r.getCreatedAt(),o.getValue(),n),o.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ne(ee.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),r=n.isRemoved();return n.remove(t)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class Rt extends tr{constructor(t,n){super(t);J(this,"elements");this.elements=n}static create(t,n){if(!n)return new Rt(t,ii.create());const r=ii.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,r){this.elements.moveAfter(t,n,r)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const r=n.getValue();if(t(r,this))return;r instanceof tr&&r.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...a,value:a.value?{attributes:Pr(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,v,[c,c]]}setStyle(t,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),v=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):Xt:Yr;if(a.canStyle(r,b)){const w=v.get(p),y=a.getCreatedAt();(!w||y.after(w))&&v.set(p,y),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:Pr(n)}});for(const[w,y]of Object.entries(n)){const[h]=a.getValue().setAttr(w,y,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[v,l,c]}indexRangeToPosRange(t,n){const r=this.rgaTreeSplit.indexToPos(t);return t===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();t.push({attributes:Pr(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new qt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())t.push(r)}return t}}class fi extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"content");J(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(t,n,r,o,s,u,c){return new fi(t,n,r,o,s,u,c)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof qt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${t}.EDIT(${n},${r},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class hi extends en{constructor(t,n,r,o,s,u){super(t,u);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(t,n,r,o,s,u){return new hi(t,n,r,o,s,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof qt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)t.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${t}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const sc=2,ac="root",Fn="text";function Vr(i,e){let t=0;const n=i.children;for(let r=0;r0)throw new ne(ee.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Fn}get paddedSize(){return this.size+(this.isText?0:sc)}isAncestorOf(e){return uc(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=n;const o=this.cloneText(e+t);return o.value=r,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,e),o=this.children.slice(e);this._children=r,n._children=o,this.size=this._children.reduce((s,u)=>s+u.paddedSize,0),n.size=n._children.reduce((s,u)=>s+u.paddedSize,0);for(const s of n._children)s.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new ne(ee.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ne(ee.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function uc(i,e){if(i===e)return!1;for(;e.parent;){if(e.parent===i)return!0;e=e.parent}return!1}var st=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(st||{});function ka(i,e,t,n){if(e>t)throw new ne(ee.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>i.size)throw new ne(ee.ErrInvalidArgument,`from is out of range: ${e} > ${i.size}`);if(t>i.size)throw new ne(ee.ErrInvalidArgument,`to is out of range: ${t} > ${i.size}`);if(e===t)return;let r=0;for(const o of i.children){if(e-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),ka(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function xa(i,e,t=0){for(const n of i.children)xa(n,e,t+1);e(i,t)}function Wi(i,e,t=0){for(const n of i._children)Wi(n,e,t+1);e(i,t)}function mo(i,e,t=!0){if(e>i.size)throw new ne(ee.ErrInvalidArgument,`index is out of range: ${e} > ${i.size}`);if(i.isText)return{node:i,offset:e};let n=0,r=0;for(const o of i.children){if(t&&o.isText&&o.size>=e-r)return mo(o,e-r,t);if(e===r)return{node:i,offset:n};if(!t&&o.paddedSize===e-r)return{node:i,offset:n+1};if(o.paddedSize>e-r)return mo(o,e-r-1,t);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function Na(i){return i.isText||i.children.length===0?i:Na(i.children[0])}function cc(i,e){if(i.sizei===e?0:i0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,o=t;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new dc(e,t,!0);const r=this.comparator(e,n.key);return r<0?n.left=this.putInternal(e,t,n.left):r>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Zt{constructor(e,t){J(this,"parentID");J(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Zt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,r;return n.isText?(n.parent.children[0]===n&&t===0?r=n.parent:r=n,n=n.parent):t===0?r=n:r=n.children[t-1],Zt.of(n.id,gt.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Zt.of(gt.of(Ot.fromStruct(e.parentID.createdAt),e.parentID.offset),gt.of(Ot.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),r=e.findFloorNode(t);let o=e.findFloorNode(n);if(!r||!o)throw new ne(ee.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=e.findFloorNode(o.insPrevID)),[r,o]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class gt{constructor(e,t){J(this,"createdAt");J(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new gt(e,t)}static fromStruct(e){return gt.of(Ot.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const o=r.deepcopy();return o.parent=t,o}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ne(ee.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new ne(ee.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new Ct(gt.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ct(gt.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,r){const o=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(o){if(o.insPrevID=this.id,this.insNextID){const s=t.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,t.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new Un);const r=new Array;for(const[o,s]of Object.entries(t))r.push(this.attrs.set(o,s,n));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function yo(i){var t;if(i.isText){const n=i;return{type:n.type,value:n.value}}const e={type:i.type,children:i.children.map(yo)};return i.attrs&&(e.attributes=Pr((t=i.attrs)==null?void 0:t.toObject())),e}function xo(i){if(i.isText)return i.value;let e="";return i.attrs&&i.attrs.size()&&(e=" "+Array.from(i.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${xn(t.getValue())}"`}).join(" ")),`<${i.type}${e}>${i.children.map(t=>xo(t)).join("")}`}function Pa(i){if(i.isText){const e=i;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:i.type,children:i.children.map(Pa),size:i.size,isRemoved:i.isRemoved}}class Ft extends ui{constructor(t,n){super(n);J(this,"indexTree");J(this,"nodeMapByID");this.indexTree=new fc(t),this.nodeMapByID=new Ia(gt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,n){return new Ft(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[r,o]=t.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,t.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,v=u?0:m.indexOf(s)+1;for(let d=v;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):Xt:Yr;if(p.canStyle(r,w)&&n){const y=l.get(b),h=p.getCreatedAt();(!y||h.after(y))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((_,[,S])=>(S&&(_[S.getKey()]=d[S.getKey()]),_),{}),A=p.parent,T=p.prevSibling||p.parent;Object.keys(f).length>0&&v.push({type:"style",from:this.toIndex(A,T),to:this.toIndex(p,p),fromPath:this.toPath(A,T),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[_]of g)_&&a.push({parent:p,child:_})}}),[l,a,v]}removeStyle(t,n,r,o){const[s,u]=this.findNodesAndSplitText(t[0],r),[c,m]=this.findNodesAndSplitText(t[1],r),v=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):Xt:Yr;if(a.canStyle(r,b)&&n){const w=d.get(p),y=a.getCreatedAt();(!w||y.after(w))&&d.set(p,y),a.attrs||(a.attrs=new Un);for(const f of n){const A=a.attrs.remove(f,r);for(const T of A)l.push({parent:a,child:T})}const h=a.parent,g=a.prevSibling||a.parent;v.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,v]}edit(t,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(t[0],o),[v,d]=this.findNodesAndSplitText(t[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],y=new Map;this.traverseInPosRange(c,m,v,d,([f,A],T)=>{if(A===st.Start&&!T)for(const I of f.children)w.push(I);const _=f.getCreatedAt().getActorID(),S=u?u.has(_)?u.get(_):Xt:Yr;if(f.canDelete(o,S)||p.includes(f.parent)){const I=y.get(_),O=f.getCreatedAt();(!I||O.after(I))&&y.set(_,O),(A===st.Text||A===st.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,T=m;for(;f{c.isRemoved&&(_.remove(o),g.push({parent:this,child:_})),this.nodeMapByID.put(_.id,_)}),T.isRemoved||f.push(T);if(f.length){const T=f.map(_=>yo(_));h.length&&h[h.length-1].from===l?h[h.length-1].value=T:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:T})}}return[h,g,y]}editT(t,n,r,o,s){const u=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([u,c],n,r,o,s)}move(t,n,r){throw new ne(ee.ErrUnimplemented,`not implemented: ${t}, ${n}, ${r}`)}purge(t){var o;(o=t.parent)==null||o.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,r=t.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const r of n.getGCPairs())t.push(r)}),t}findPos(t,n=!0){const r=this.indexTree.findTreePos(t,n);return Zt.fromTreePos(r)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return xo(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,v;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),v=Zt.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?Pr((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:v};for(let y=0;y0&&y===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:y,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([t,n]){if(n===st.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?st.Text:st.Start]:[t,st.End]}const r=t.parent,o=r.allChildren,s=o.indexOf(t);if(r&&s===o.length-1)return[r,st.End];const u=o[s+1];return[u,u.isText?st.Text:st.Start]}findLeftToken([t,n]){if(n===st.End){const c=t.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?st.Text:st.End]}return[t,st.Start]}const r=t.parent,o=r.allChildren,s=o.indexOf(t);if(r&&s===0)return[r,st.Start];const u=o[s-1];return[u,u.isText?st.Text:st.End]}}class di extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"contents");J(this,"splitLevel");J(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(t,n,r,o,s,u,c){return new di(t,n,r,o,s,u,c)}execute(t){var c;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Ft))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Ot.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)t.registerGCPair(m);return{opInfos:s.map(({from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${t}.EDIT(${n},${r},${o.map(s=>xo(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Qn{constructor(e,t,n,r){J(this,"clientSeq");J(this,"serverSeq");J(this,"lamport");J(this,"actor");this.clientSeq=e,this.serverSeq=r,this.lamport=t,this.actor=n}static of(e,t,n,r){return new Qn(e,t,n,r)}next(){return new Qn(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new Qn(this.clientSeq,e,this.actor):new Qn(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return Ot.of(this.lamport,e,this.actor)}setActor(e){return new Qn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const pc=new Qn(0,Re.fromInt(0,!0),Hi);class Br{constructor({id:e,operations:t,presenceChange:n,message:r}){J(this,"id");J(this,"operations");J(this,"presenceChange");J(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=r}static create({id:e,operations:t,presenceChange:n,message:r}){return new Br({id:e,operations:t,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(e,n);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===ir.Put?t.set(this.id.getActorID(),Gt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ct.bytesToHex(ct.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ct.bytesToHex(ct.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:r,message:o}=e;return Br.create({id:ct.bytesToChangeID(ct.hexToBytes(t)),operations:n==null?void 0:n.map(s=>ct.bytesToOperation(ct.hexToBytes(s))),presenceChange:r,message:o})}}class Gi{constructor(e,t,n,r,o,s){J(this,"documentKey");J(this,"checkpoint");J(this,"isRemoved");J(this,"changes");J(this,"snapshot");J(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=r,this.snapshot=o,this.minSyncedTicket=s}static create(e,t,n,r,o,s){return new Gi(e,t,n,r,o,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Cr{constructor(e,t){J(this,"serverSeq");J(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new Cr(e,t)}increaseClientSeq(e){return e===0?this:new Cr(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return Cr.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const mc=new Cr(Re.fromInt(0,!0),0);class Nn{constructor(e,t){J(this,"createdAt");J(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Nn(e,t)}static fromStruct(e){return Nn.of(Ot.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Nn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const yc=Nn.of(Xt,0);class Qt{constructor(e,t){J(this,"id");J(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Qt(e,t)}static fromStruct(e){const t=Nn.fromStruct(e.id);return Qt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Nn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class nr extends Sa{constructor(t,n,r){super(n);J(this,"id");J(this,"removedAt");J(this,"prev");J(this,"next");J(this,"insPrev");J(this,"insNext");this.id=t,this.removedAt=r}static create(t,n){return new nr(t,n)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let r=e;for(;r&&r!==t;)n.push(r),r=r.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new ne(ee.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const r=e.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(e,t,n),s=new Map,u=new Map,c=this.makeChanges(o,t);for(const m of r){const v=m.getCreatedAt().getActorID();(!s.has(v)||m.getID().getCreatedAt().after(s.get(v)))&&s.set(v,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(t)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(e,t,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(e);s.push(u);for(const m of e){const v=m.getCreatedAt().getActorID(),d=r?n.has(v)?n.get(v):Xt:Yr;m.canDelete(t,d)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var In=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(In||{});class Dt extends ui{constructor(t,n,r){super(r);J(this,"valueType");J(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Re.fromNumber(n).toInt():this.value=vs(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Re.fromNumber(n):this.value=n;break;default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,r){return new Dt(t,n,r)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Re.fromBytesLE(Array.from(n));default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=Dt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Re?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!Dt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(ee.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ut.Long?this.value=this.value+t.getValue().toInt():this.value=Re.fromNumber(this.value+vs(t.getValue())).toInt(),this}}class Fr extends en{constructor(t,n,r){super(t,r);J(this,"value");this.value=n}static create(t,n,r){return new Fr(t,n,r)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Dt))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===ut.Long?t.getValue().multiply(-1):t.getValue()*-1;return Fr.create(this.getParentCreatedAt(),Xe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class jn extends en{constructor(t,n,r,o,s,u,c){super(t,c);J(this,"fromPos");J(this,"toPos");J(this,"maxCreatedAtMapByActor");J(this,"attributes");J(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(t,n,r,o,s,u){return new jn(t,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(t,n,r,o,s,u){return new jn(t,n,r,o,new Map,s,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(ee.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Ft))throw new ne(ee.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)t.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:v,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:v,toPath:d,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([o,s])=>`${o}:"${s}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function vc(i){const e=new Eo,t=e.data;for(const[n,r]of Object.entries(i))t[n]=JSON.stringify(r);return e}function bc(i){if(i.type===ir.Put)return new go({type:ti.PUT,presence:vc(i.presence)});if(i.type===ir.Clear)return new go({type:ti.CLEAR});throw new ne(ee.ErrUnimplemented,"unimplemented type")}function wc(i){return new wa({serverSeq:i.getServerSeqAsString(),clientSeq:i.getClientSeq()})}function Ca(i){return new Vi({clientSeq:i.getClientSeq(),lamport:i.getLamportAsString(),actorId:Lo(i.getActorID())})}function Ee(i){if(i)return new ke({lamport:i.getLamportAsString(),delimiter:i.getDelimiter(),actorId:Lo(i.getActorID())})}function Ra(i){switch(i){case ut.Null:return Le.NULL;case ut.Boolean:return Le.BOOLEAN;case ut.Integer:return Le.INTEGER;case ut.Long:return Le.LONG;case ut.Double:return Le.DOUBLE;case ut.String:return Le.STRING;case ut.Bytes:return Le.BYTES;case ut.Date:return Le.DATE;default:throw new ne(ee.ErrInvalidType,`unsupported type: ${i}`)}}function Da(i){switch(i){case In.IntegerCnt:return Le.INTEGER_CNT;case In.LongCnt:return Le.LONG_CNT;default:throw new ne(ee.ErrInvalidType,`unsupported type: ${i}`)}}function oo(i){if(i instanceof St)return new Dn({type:Le.JSON_OBJECT,createdAt:Ee(i.getCreatedAt()),value:Ha(i)});if(i instanceof Rt)return new Dn({type:Le.JSON_ARRAY,createdAt:Ee(i.getCreatedAt()),value:Gc(i)});if(i instanceof qt)return new Dn({type:Le.TEXT,createdAt:Ee(i.getCreatedAt())});if(i instanceof Xe)return new Dn({type:Ra(i.getType()),createdAt:Ee(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Dn({type:Da(i.getType()),createdAt:Ee(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Ft)return new Dn({type:Le.TREE,createdAt:Ee(i.getCreatedAt()),value:Zc(i)});throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Ac(i){return new ho({createdAt:Ee(i.getCreatedAt()),offset:i.getOffset()})}function Ei(i){return new mr({createdAt:Ee(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function Oi(i){return new ei({parentId:Zr(i.getParentID()),leftSiblingId:Zr(i.getLeftSiblingID())})}function Zr(i){return new Ir({createdAt:Ee(i.getCreatedAt()),offset:i.getOffset()})}function La(i){const e=new Ao;if(i instanceof yr){const t=i,n=new na;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.key=t.getKey(),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(i instanceof ci){const t=i,n=new ra;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.prevCreatedAt=Ee(t.getPrevCreatedAt()),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(i instanceof er){const t=i,n=new ia;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.prevCreatedAt=Ee(t.getPrevCreatedAt()),n.createdAt=Ee(t.getCreatedAt()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(i instanceof or){const t=i,n=new oa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.createdAt=Ee(t.getCreatedAt()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(i instanceof fi){const t=i,n=new sa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Ei(t.getFromPos()),n.to=Ei(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);n.content=t.getContent();const o=n.attributes;for(const[s,u]of t.getAttributes())o[s]=u;n.executedAt=Ee(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(i instanceof hi){const t=i,n=new aa;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Ei(t.getFromPos()),n.to=Ei(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);const o=n.attributes;for(const[s,u]of t.getAttributes())o[s]=u;n.executedAt=Ee(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(i instanceof Fr){const t=i,n=new la;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.value=oo(t.getValue()),n.executedAt=Ee(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(i instanceof di){const t=i,n=new ua,r=n.createdAtMapByActor;for(const[o,s]of t.getMaxCreatedAtMapByActor())r[o]=Ee(s);n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Oi(t.getFromPos()),n.to=Oi(t.getToPos()),n.contents=xc(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=Ee(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(i instanceof jn){const t=i,n=new ca;n.parentCreatedAt=Ee(t.getParentCreatedAt()),n.from=Oi(t.getFromPos()),n.to=Oi(t.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of t.getMaxCreatedAtMapByActor())r[s]=Ee(u);const o=t.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of t.getAttributes())s[u]=c}n.executedAt=Ee(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new ne(ee.ErrUnimplemented,"unimplemented operation");return e}function Tc(i){const e=[];for(const t of i)e.push(La(t));return e}function _c(i){const e=new ta({id:Ca(i.getID()),message:i.getMessage()});return i.hasOperations()&&(e.operations=Tc(i.getOperations())),i.hasPresenceChange()&&(e.presenceChange=bc(i.getPresenceChange())),e}function Ec(i){const e=[];for(const t of i)e.push(_c(t));return e}function Oc(i){const e=[];for(const t of i)e.push(new ya({key:t.getStrKey(),element:Io(t.getValue())}));return e}function Sc(i){const e=[];for(const t of i)e.push(new To({element:Io(t.getValue())}));return e}function kc(i){const e=[];for(const t of i){const n=new va;n.id=Ac(t.getID()),n.value=t.getValue().getContent(),n.removedAt=Ee(t.getRemovedAt());const r=n.attributes,o=t.getValue().getAttrs();for(const s of o){const u=new Ki;u.value=s.getValue(),u.updatedAt=Ee(s.getUpdatedAt()),r[s.getKey()]=u}e.push(n)}return e}function xc(i){const e=[];if(!i||!i.length)return e;for(const t of i)e.push(new ba({content:No(t)}));return e}function Nc(i){const e={};for(const t of i)e[t.getKey()]=new Ki({value:t.getValue(),updatedAt:Ee(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function No(i){if(!i)return[];const e=[];return Wi(i,(t,n)=>{const r=new _o({id:Zr(t.id),type:t.type,removedAt:Ee(t.removedAt),depth:n});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Zr(t.insPrevID)),t.insNextID&&(r.insNextId=Zr(t.insNextID)),t.attrs&&(r.attributes=Nc(t.attrs)),e.push(r)}),e}function Ic(i){const e=new jt;return e.body.case="jsonObject",e.body.value=new fa({nodes:Oc(i.getRHT()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Ma(i){const e=new jt;return e.body.case="jsonArray",e.body.value=new ha({nodes:Sc(i.getElements()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Pc(i){const e=new jt;return e.body.case="primitive",e.body.value=new da({type:Ra(i.getType()),value:i.toBytes(),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Cc(i){const e=new jt;return e.body.case="text",e.body.value=new ga({nodes:kc(i.getRGATreeSplit()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Rc(i){const e=new jt;return e.body.case="counter",e.body.value=new pa({type:Da(i.getType()),value:i.toBytes(),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Ba(i){const e=new jt;return e.body.case="tree",e.body.value=new ma({nodes:No(i.getRoot()),createdAt:Ee(i.getCreatedAt()),movedAt:Ee(i.getMovedAt()),removedAt:Ee(i.getRemovedAt())}),e}function Io(i){if(i instanceof St)return Ic(i);if(i instanceof Rt)return Ma(i);if(i instanceof Xe)return Pc(i);if(i instanceof qt)return Cc(i);if(i instanceof Dt)return Rc(i);if(i instanceof Ft)return Ba(i);throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Dc(i){return new $n({documentKey:i.getDocumentKey(),checkpoint:wc(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:Ec(i.getChanges()),snapshot:i.getSnapshot(),minSyncedTicket:Ee(i.getMinSyncedTicket())})}function bs(i){const e=i.findDetails(Xu);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function qa(i){let e;return i.serverSeq&&(e=Re.fromString(i.serverSeq,!0)),Qn.of(i.clientSeq,Re.fromString(i.lamport,!0),Do(i.actorId),e)}function Se(i){if(i)return Ot.of(Re.fromString(i.lamport,!0),i.delimiter,Do(i.actorId))}function Po(i){const e={};return Object.entries(i.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Lc(i){const e=i.type;if(e===ti.PUT){const t=Po(i.presence);return{type:ir.Put,presence:t}}if(e===ti.CLEAR)return{type:ir.Clear};throw new ne(ee.ErrInvalidType,`unsupported type: ${e}`)}function Mc(i){const e=new Map;return Object.entries(i).forEach(([t,n])=>{e.set(t,Po(n))}),e}function Fa(i){switch(i){case Le.NULL:return ut.Null;case Le.BOOLEAN:return ut.Boolean;case Le.INTEGER:return ut.Integer;case Le.LONG:return ut.Long;case Le.DOUBLE:return ut.Double;case Le.STRING:return ut.String;case Le.BYTES:return ut.Bytes;case Le.DATE:return ut.Date}throw new ne(ee.ErrUnimplemented,`unimplemented value type: ${i}`)}function $i(i){switch(i){case Le.INTEGER_CNT:return In.IntegerCnt;case Le.LONG_CNT:return In.LongCnt}throw new ne(ee.ErrUnimplemented,`unimplemented value type: ${i}`)}function so(i){switch(i.type){case Le.JSON_OBJECT:return i.value?Ka(i.value):St.create(Se(i.createdAt));case Le.JSON_ARRAY:return i.value?Wc(i.value):Rt.create(Se(i.createdAt));case Le.TEXT:return qt.create(qr.create(),Se(i.createdAt));case Le.TREE:return Yc(i.value);case Le.NULL:case Le.BOOLEAN:case Le.INTEGER:case Le.LONG:case Le.DOUBLE:case Le.STRING:case Le.BYTES:case Le.DATE:return Xe.of(Xe.valueFromBytes(Fa(i.type),i.value),Se(i.createdAt));case Le.INTEGER_CNT:case Le.LONG_CNT:return Dt.create($i(i.type),Dt.valueFromBytes($i(i.type),i.value),Se(i.createdAt))}}function Si(i){return Qt.of(Nn.of(Se(i.createdAt),i.offset),i.relativeOffset)}function ja(i){return Nn.of(Se(i.createdAt),i.offset)}function Bc(i){const e=oi.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{e.setAttr(n,r.value,Se(r.updatedAt))});const t=nr.create(ja(i.id),e);return t.remove(Se(i.removedAt)),t}function Er(i){return Zt.of(Xr(i.parentId),Xr(i.leftSiblingId))}function Xr(i){return gt.of(Se(i.createdAt),i.offset)}function qc(i){if(!i.length)return;const e=[];return i.forEach(t=>{const n=Co(t.content);e.push(n)}),e}function Co(i){if(i.length===0)return;const e=[];for(const r of i)e.push(jc(r));const t=e[e.length-1],n=new Map;n.set(i[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(e[r]),n.set(i[r].depth,e[r]);return t.updateDescendantsSize(),Ft.create(t,Xt).getRoot()}function Fc(i){const e=Un.create();for(const[t,n]of Object.entries(i))e.setInternal(t,n.value,Se(n.updatedAt),n.isRemoved);return e}function jc(i){const e=Xr(i.id),t=Ct.create(e,i.type),n=Object.entries(i.attributes);return t.isText?t.value=i.value:n.length&&(t.attrs=Fc(i.attributes)),i.insPrevId&&(t.insPrevID=Xr(i.insPrevId)),i.insNextId&&(t.insNextID=Xr(i.insNextId)),t.removedAt=Se(i.removedAt),t}function Ua(i){if(i.body.case==="set"){const e=i.body.value;return yr.create(e.key,so(e.value),Se(e.parentCreatedAt),Se(e.executedAt))}else if(i.body.case==="add"){const e=i.body.value;return ci.create(Se(e.parentCreatedAt),Se(e.prevCreatedAt),so(e.value),Se(e.executedAt))}else if(i.body.case==="move"){const e=i.body.value;return er.create(Se(e.parentCreatedAt),Se(e.prevCreatedAt),Se(e.createdAt),Se(e.executedAt))}else if(i.body.case==="remove"){const e=i.body.value;return or.create(Se(e.parentCreatedAt),Se(e.createdAt),Se(e.executedAt))}else if(i.body.case==="edit"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,o])=>{t.set(r,Se(o))});const n=new Map;return Object.entries(e.attributes).forEach(([r,o])=>{n.set(r,o)}),fi.create(Se(e.parentCreatedAt),Si(e.from),Si(e.to),t,e.content,n,Se(e.executedAt))}else if(i.body.case==="style"){const e=i.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,o])=>{t.set(r,Se(o))});const n=new Map;return Object.entries(e.attributes).forEach(([r,o])=>{n.set(r,o)}),hi.create(Se(e.parentCreatedAt),Si(e.from),Si(e.to),t,n,Se(e.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const e=i.body.value;return Fr.create(Se(e.parentCreatedAt),so(e.value),Se(e.executedAt))}else if(i.body.case==="treeEdit"){const e=i.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,r])=>{t.set(n,Se(r))}),di.create(Se(e.parentCreatedAt),Er(e.from),Er(e.to),qc(e.contents),e.splitLevel,t,Se(e.executedAt))}else if(i.body.case==="treeStyle"){const e=i.body.value,t=new Map,n=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Se(s))}),(n==null?void 0:n.length)>0?jn.createTreeRemoveStyleOperation(Se(e.parentCreatedAt),Er(e.from),Er(e.to),r,n,Se(e.executedAt)):(Object.entries(e.attributes).forEach(([o,s])=>{t.set(o,s)}),jn.create(Se(e.parentCreatedAt),Er(e.from),Er(e.to),r,t,Se(e.executedAt)))}else throw new ne(ee.ErrUnimplemented,"unimplemented operation")}}function Uc(i){const e=[];for(const t of i){const n=Ua(t);n&&e.push(n)}return e}function $a(i){const e=[];for(const t of i)e.push(Br.create({id:qa(t.id),operations:Uc(t.operations),presenceChange:t.presenceChange?Lc(t.presenceChange):void 0,message:t.message}));return e}function $c(i){return Cr.of(Re.fromString(i.serverSeq,!0),i.clientSeq)}function zc(i){return Gi.create(i.documentKey,$c(i.checkpoint),i.isRemoved,$a(i.changes),i.snapshot,Se(i.minSyncedTicket))}function za(i){const e=new ni;for(const n of i.nodes){const r=Ro(n.element);e.set(n.key,r,r.getPositionedAt())}const t=new St(Se(i.createdAt),e);return t.setMovedAt(Se(i.movedAt)),t.setRemovedAt(Se(i.removedAt)),t}function Ja(i){const e=new ii;for(const n of i.nodes)e.insert(Ro(n.element));const t=new Rt(Se(i.createdAt),e);return t.setMovedAt(Se(i.movedAt)),t.setRemovedAt(Se(i.removedAt)),t}function Jc(i){const e=Xe.of(Xe.valueFromBytes(Fa(i.type),i.value),Se(i.createdAt));return e.setMovedAt(Se(i.movedAt)),e.setRemovedAt(Se(i.removedAt)),e}function Vc(i){const e=new qr;let t=e.getHead();for(const r of i.nodes){const o=e.insertAfter(t,Bc(r));r.insPrevId&&o.setInsPrev(e.findNode(ja(r.insPrevId))),t=o}const n=new qt(e,Se(i.createdAt));return n.setMovedAt(Se(i.movedAt)),n.setRemovedAt(Se(i.removedAt)),n}function Kc(i){const e=Dt.create($i(i.type),Dt.valueFromBytes($i(i.type),i.value),Se(i.createdAt));return e.setMovedAt(Se(i.movedAt)),e.setRemovedAt(Se(i.removedAt)),e}function Va(i){const e=Co(i.nodes);return Ft.create(e,Se(i.createdAt))}function Ro(i){if(i.body.case==="jsonObject")return za(i.body.value);if(i.body.case==="jsonArray")return Ja(i.body.value);if(i.body.case==="primitive")return Jc(i.body.value);if(i.body.case==="text")return Vc(i.body.value);if(i.body.case==="counter")return Kc(i.body.value);if(i.body.case==="tree")return Va(i.body.value);throw new ne(ee.ErrUnimplemented,"unimplemented element")}function Hc(i){if(!i)return{root:St.create(Xt),presences:new Map};const e=xu.fromBinary(i);return{root:Ro(e.root),presences:Mc(e.presences)}}function Ka(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return za(e.body.value)}function Ha(i){return Io(i).toBinary()}function Wc(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return Ja(e.body.value)}function Gc(i){return Ma(i).toBinary()}function Yc(i){if(!i)throw new ne(ee.ErrInvalidArgument,"bytes is empty");const e=jt.fromBinary(i);return Va(e.body.value)}function Zc(i){return Ba(i).toBinary()}function Wa(i){return i?Array.from(i).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function Do(i){return Wa(i)}function Ga(i){return new Uint8Array(i.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Lo(i){return Ga(i)}function Xc(i){const e=Vi.fromBinary(i);return qa(e)}function Qc(i){const e=Ao.fromBinary(i);return Ua(e)}const ct={fromPresence:Po,toChangePack:Dc,fromChangePack:zc,fromChanges:$a,toTreeNodes:No,fromTreeNodes:Co,objectToBytes:Ha,bytesToObject:Ka,bytesToSnapshot:Hc,bytesToHex:Wa,hexToBytes:Ga,toHexString:Do,toUint8Array:Lo,toOperation:La,toChangeID:Ca,PbChangeID:Vi,bytesToChangeID:Xc,bytesToOperation:Qc};var bt=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(bt||{});let lr=3;function Ya(i){lr=i}const xe={trivial:(...i)=>{lr>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{lr>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{lr>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{lr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{lr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>lr<=i};function Za(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}class ef{constructor(e,t,n,r,o){J(this,"reconnectStreamDelay");J(this,"doc");J(this,"docID");J(this,"syncMode");J(this,"remoteChangeEventReceived");J(this,"watchStream");J(this,"watchLoopTimerID");J(this,"watchAbortController");J(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Mi.RealtimeSyncOff?!1:this.syncMode===Mi.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Mi.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const ao=()=>{};class tf{constructor(e){J(this,"finalized",!1);J(this,"observers",[]);J(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(!e)throw new ne(ee.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(ee.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:n},r.next===void 0&&(r.next=ao),r.error===void 0&&(r.error=ao),r.complete===void 0&&(r.complete=ao);const o=Za(),s=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(u){xe.warn(u)}return s}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Nr{constructor(e,t,n,r){J(this,"id");J(this,"delimiter");J(this,"message");J(this,"root");J(this,"operations");J(this,"presenceChange");J(this,"previousPresence");J(this,"reversePresenceKeys");this.id=e,this.delimiter=So,this.root=t,this.operations=[],this.previousPresence=Gt(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,n,r){return new Nr(e,t,n,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Br.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class si{constructor(e){J(this,"rootObject");J(this,"elementPairMapByCreatedAt");J(this,"gcElementSetByCreatedAt");J(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof qt||t instanceof Ft)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new si(St.create(Xt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const r=t.element.getCreatedAt(),o=t.parent.subPathOf(r);if(o===void 0)throw new ne(ee.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tr&&e.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(e){let t=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),t++};return n(e),e instanceof tr&&e.getDescendants(r=>(n(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof tr&&n.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new si(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n);r.element.getRemovedAt()&&e.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r!==void 0&&e.compare(r)>=0&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Xa(i,e){const t=new ai(i);return new Proxy(e,t.getHandlers())}class ai{constructor(e){J(this,"context");J(this,"handlers");this.context=e,this.handlers={set:(t,n,r)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]=${JSON.stringify(r)}`),ai.setInternal(e,t,n,r),!0),get:(t,n)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():ur(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`obj[${n}]`),ai.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,r){if(n.includes("."))throw new ne(ee.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),s=zi(e,r,o),u=t.set(n,s,o);e.registerElement(s,t),u&&e.registerRemovedElement(u),e.push(yr.create(n,s.deepcopy(),t.getCreatedAt(),o))}static buildObjectMembers(e,t){const n={};for(const[r,o]of Object.entries(t)){if(r.includes("."))throw new ne(ee.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),u=zi(e,o,s);n[r]=u}return n}static deleteInternal(e,t,n){const r=e.issueTimeTicket(),o=t.deleteByKey(n,r);o&&(e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o))}getHandlers(){return this.handlers}}function rf(i,e){const t=new et(i,e);return new Proxy(e,t.getHandlers())}function of(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function sf(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class et{constructor(e,t){J(this,"context");J(this,"handlers");J(this,"array");this.context=e,this.array=t,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return Wn(e,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return Wn(e,u)}:r==="getLast"?()=>Wn(e,n.getLast()):r==="deleteByID"?s=>{const u=et.deleteInternalByID(e,n,s);return Wn(e,u)}:r==="insertAfter"?(s,u)=>{const c=et.insertAfterInternal(e,n,s,u);return Wn(e,c)}:r==="insertBefore"?(s,u)=>{const c=et.insertBeforeInternal(e,n,s,u);return Wn(e,c)}:r==="moveBefore"?(s,u)=>{et.moveBeforeInternal(e,n,s,u)}:r==="moveAfter"?(s,u)=>{et.moveAfterInternal(e,n,s,u)}:r==="moveFront"?s=>{et.moveFrontInternal(e,n,s)}:r==="moveLast"?s=>{et.moveLastInternal(e,n,s)}:of(r)?ur(e,n.get(Number(r))):r==="push"?s=>et.pushInternal(e,n,s):r==="splice"?(s,u,...c)=>et.splice(e,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?et.iteratorInternal.bind(this,e,n):r==="includes"?(s,u)=>et.includes(e,n,s,u):r==="indexOf"?(s,u)=>et.indexOf(e,n,s,u):r==="lastIndexOf"?(s,u)=>et.lastIndexOf(e,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>et.toTestString(n):typeof r=="string"&&sf(r)?(...s)=>{const u=Array.from(n).map(c=>ur(e,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(xe.isEnabled(bt.Trivial)&&xe.trivial(`array[${r}]`),et.deleteInternalByIndex(e,n,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield Wn(e,n)}static buildArrayElements(e,t){const n=[];for(const r of t){const o=e.issueTimeTicket(),s=zi(e,r,o);n.push(s)}return n}static pushInternal(e,t,n){return et.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,r){const o=e.issueTimeTicket(),s=t.getPrevCreatedAt(n);t.moveAfter(s,r,o),e.push(er.create(t.getCreatedAt(),s,r,o))}static moveAfterInternal(e,t,n,r){const o=e.issueTimeTicket();t.moveAfter(n,r,o),e.push(er.create(t.getCreatedAt(),n,r,o))}static moveFrontInternal(e,t,n){const r=e.issueTimeTicket(),o=t.getHead();t.moveAfter(o.getCreatedAt(),n,r),e.push(er.create(t.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(e,t,n){const r=e.issueTimeTicket(),o=t.getLastCreatedAt();t.moveAfter(o,n,r),e.push(er.create(t.getCreatedAt(),o,n,r))}static insertAfterInternal(e,t,n,r){const o=e.issueTimeTicket(),s=zi(e,r,o);return t.insertAfter(n,s),e.registerElement(s,t),e.push(ci.create(t.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(e,t,n,r){return et.insertAfterInternal(e,t,t.getPrevCreatedAt(n),r)}static deleteInternalByIndex(e,t,n){const r=e.issueTimeTicket(),o=t.deleteByIndex(n,r);if(o)return e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o),o}static deleteInternalByID(e,t,n){const r=e.issueTimeTicket(),o=t.delete(n,r);return e.push(or.create(t.getCreatedAt(),o.getCreatedAt(),r)),e.registerRemovedElement(o),o}static splice(e,t,n,r,...o){const s=t.length,u=n>=0?Math.min(n,s):Math.max(s+n,0),c=r===void 0?s:r<0?u:Math.min(u+r,s),m=[];for(let v=u;v=o)return!1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).includes(n,s);for(let c=s;c=o)return-1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(Xe.isSupport(n))return Array.from(t).map(m=>ur(e,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=t.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let Yi=class{constructor(e,t){J(this,"context");J(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,r){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(e,t);xe.isEnabled(bt.Debug)&&xe.debug(`EDIT: f:${e}->${o[0].toTestString()}, t:${t}->${o[1].toTestString()} c:${n}`);const s=r?Mr(r):void 0,u=this.context.issueTimeTicket(),[c,,m,v]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new fi(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(v)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);xe.isEnabled(bt.Debug)&&xe.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Mr(n),s=this.context.issueTimeTicket(),[u,c]=this.text.setStyle(r,o,s);for(const m of c)this.context.registerGCPair(m);return this.context.push(new hi(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Qt.fromStruct(e[0]),Qt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ne(ee.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class Zi{constructor(e,t){J(this,"valueType");J(this,"value");J(this,"context");J(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ne(ee.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=Xe.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Fr.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(ee.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Mo(i,e,t){const{type:n}=i,r=t.issueTimeTicket();if(n===Fn){Qa(i);const{value:o}=i,s=Ct.create(gt.of(r,0),n,o);e.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!Oa(s)){const m=Mr(s);u=new Un;for(const[v,d]of Object.entries(m))u.set(v,d,r)}const c=Ct.create(gt.of(r,0),n,void 0,u);e.append(c);for(const m of o)Mo(m,c,t)}}function af(i,e){const{type:t}=e,n=i.issueTimeTicket();let r;if(e.type===Fn){const{value:o}=e;r=Ct.create(gt.of(n,0),t,o)}else if(e){const{children:o=[]}=e,{attributes:s}=e;let u;if(typeof s=="object"&&!Oa(s)){const c=Mr(s);u=new Un;for(const[m,v]of Object.entries(c))u.set(m,v,n)}r=Ct.create(gt.of(i.issueTimeTicket(),0),t,void 0,u);for(const c of o)Mo(c,r,i)}return r}function Qa(i){if(!i.value.length)throw new ne(ee.ErrInvalidArgument,"text node cannot have empty value");return!0}function ws(i){if(!i.length)return!0;if(i[0].type===Fn)for(const t of i){const{type:n}=t;if(n!==Fn)throw new ne(ee.ErrInvalidArgument,"element node and text node cannot be passed together");Qa(t)}else for(const t of i){const{type:n}=t;if(n===Fn)throw new ne(ee.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Xi{constructor(e){J(this,"initialRoot");J(this,"context");J(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ct.create(gt.of(e.issueTimeTicket(),0),ac);const t=Ct.create(gt.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Mo(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(e),o=this.context.issueTimeTicket(),s=t?Mr(t):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(jn.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(e,t,n){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),o=this.tree.findPos(t),s=this.context.issueTimeTicket(),u=n?Mr(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const v of m)this.context.registerGCPair(v);this.context.push(jn.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),o=this.tree.findPos(t),s=this.context.issueTimeTicket(),[u,c]=this.tree.removeStyle([r,o],n,s);for(const m of c)this.context.registerGCPair(m);this.context.push(jn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(e,t,n,r=0){var m;if(n.length!==0&&n[0]&&(ws(n),n[0].type!==Fn))for(const v of n){const{children:d=[]}=v;ws(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Fn){let v="";for(const d of n){const{value:l}=d;v+=l}s.push(Ct.create(gt.of(this.context.issueTimeTicket(),0),Fn,v))}else s=n.map(v=>v&&af(this.context,v)).filter(v=>v);const[,u,c]=this.tree.edit([e,t],s.length?s.map(v=>v==null?void 0:v.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const v of u)this.context.registerGCPair(v);return this.context.push(di.create(this.tree.getCreatedAt(),e,t,s.length?s:void 0,r,c,o)),!0}editByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ne(ee.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ne(ee.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ne(ee.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(o,s,n,r)}edit(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(o,s,n?[n]:[],r)}editBulk(e,t,n,r=0){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ne(ee.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[Zt.fromStruct(e[0]),Zt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ne(ee.ErrNotInitialized,"Tree is not initialized yet");const t=[Zt.fromStruct(e[0]),Zt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function As(i,e){return Xa(i,e)}function Wn(i,e){if(e){if(e instanceof Xe)return e;if(e instanceof St)return Xa(i,e);if(e instanceof Rt)return rf(i,e);if(e instanceof qt)return new Yi(i,e);if(e instanceof Dt){const t=new Zi(In.IntegerCnt,0);return t.initialize(i,e),t}else if(e instanceof Ft){const t=new Xi;return t.initialize(i,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ur(i,e){const t=Wn(i,e);return t instanceof Xe?t.getValue():t}function zi(i,e,t){let n;if(Xe.isSupport(e))n=Xe.of(e,t);else if(Array.isArray(e))n=Rt.create(t,et.buildArrayElements(i,e));else if(typeof e=="object")e instanceof Yi?(n=qt.create(qr.create(),t),e.initialize(i,n)):e instanceof Zi?(n=Dt.create(e.getValueType(),e.getValue(),t),e.initialize(i,n)):e instanceof Xi?(n=Ft.create(e.buildRoot(i),t),e.initialize(i,n)):n=St.create(t,ai.buildObjectMembers(i,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Ts=50;class lf{constructor(){J(this,"undoStack",[]);J(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Ts&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Ts&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const uf="yorkie-devtools-panel",cf="yorkie-devtools-sdk";let Or="disconnected";const _s=new Map,Li=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Li);function ki(i,e){(e!=null&&e.force||Or!=="disconnected")&&window.postMessage({source:cf,...i},"*")}function ff(i){if(!i.isEnableDevtools()||typeof window>"u"||_s.has(i.getKey()))return;Li.set(i.getKey(),[]);const e=i.subscribe("all",t=>{t.some(n=>n.type!==dt.StatusChanged&&n.type!==dt.Snapshot&&n.type!==dt.LocalChange&&n.type!==dt.RemoteChange&&n.type!==dt.Initialized&&n.type!==dt.Watched&&n.type!==dt.Unwatched&&n.type!==dt.PresenceChanged)||(Li.get(i.getKey()).push(t),Or==="synced"&&ki({msg:"doc::sync::partial",docKey:i.getKey(),event:t}))});_s.set(i.getKey(),[e]),ki({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==uf)return;switch(t.data.msg){case"devtools::connect":if(Or!=="disconnected")break;Or="connected",ki({msg:"doc::available",docKey:i.getKey()}),xe.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Or="disconnected",xe.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Or="synced",ki({msg:"doc::sync::full",docKey:i.getKey(),events:Li.get(i.getKey())}),xe.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var Gn=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(Gn||{}),dt=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(dt||{}),li=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(li||{}),vo=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(vo||{});class el{constructor(e,t){J(this,"key");J(this,"status");J(this,"opts");J(this,"changeID");J(this,"checkpoint");J(this,"localChanges");J(this,"root");J(this,"clone");J(this,"eventStream");J(this,"eventStreamObserver");J(this,"onlineClients");J(this,"presences");J(this,"history");J(this,"internalHistory");J(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=si.create(),this.changeID=pc,this.checkpoint=mc,this.localChanges=[],this.eventStream=nf(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new lf,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ff(this)}update(e,t){if(this.getStatus()==="removed")throw new ne(ee.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const o=As(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(o,new io(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){xe.isEnabled(bt.Trivial)&&xe.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ge.Local),c=r.getReversePresence();c&&u.push({type:"presence",value:c}),this.localChanges.push(o),u.length>0&&this.internalHistory.pushUndo(u),s.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const m=[];s.length>0&&m.push({type:"local-change",source:Ge.Local,value:{message:o.getMessage()||"",operations:s,actor:n,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&m.push({type:"presence-changed",source:Ge.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),xe.isEnabled(bt.Trivial)&&xe.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,r){if(typeof e=="string"){if(typeof t!="function")throw new ne(ee.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||u(m)},n,r)}if(e==="my-presence"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="presence-changed"||m.type==="presence-changed"&&m.value.clientID!==this.changeID.getActorID()||u(m)},n,r)}if(e==="others"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||m.value.clientID!==this.changeID.getActorID()&&u(m)},n,r)}if(e==="connection"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(e==="status"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(e==="sync"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(e==="local-broadcast"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(e==="broadcast"){const u=t;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(e==="all"){const u=t;return this.eventStream.subscribe(u,n,r)}const o=e,s=t;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const v of c.value.operations)this.isSameElementOrChildOf(v.path,o)&&m.push(v);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof e=="function"){const o=e,s=t,u=n;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="snapshot"&&m.type!=="local-change"&&m.type!=="remote-change"||o(m)},s,u)}throw new ne(ee.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((o,s)=>o===n[s])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Ge.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,Ge.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),xe.isEnabled(bt.Trivial)&&xe.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Gt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Gi.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return As(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:n,presences:r}=ct.bytesToSnapshot(t);this.root=new si(n),this.presences=r,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:Ge.Remote,value:{snapshot:this.isEnableDevtools()?ct.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){xe.isEnabled(bt.Debug)&&xe.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),xe.isEnabled(bt.Trivial)&&xe.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` `));for(const n of e)this.applyChange(n,t);xe.isEnabled(bt.Debug)&&xe.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const s=e.getPresenceChange();switch(s.type){case ir.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ge.Remote,value:{clientID:r,presence:s.presence}});break;case ir.Clear:n.push({type:"unwatched",source:Ge.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),o.length>0){const s=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===Ge.Remote?{type:"remote-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const r of t)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ge.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,r=[];if(t===Gr.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ge.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(t===Gr.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ge.Remote,value:{clientID:n,presence:o}})}else if(t===Gr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:o,payload:s}=e.body.value.body,u=new TextDecoder;r.push({type:"broadcast",value:{clientID:n,topic:o,payload:JSON.parse(u.decode(s))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Hi),this.publish([{source:e==="removed"?Ge.Remote:Ge.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n}=e.value;if(!t)return;this.applySnapshot(Re.fromString(n),ct.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=Br.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:r}of e.value)t.add(n),this.presences.set(n,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new ne(ee.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const r of t)if(n=n[r],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Gt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Gt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Gt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Gt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Gt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(ee.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new ne(ee.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of e){if(!(m instanceof en)){new io(t,Gt(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=t.issueTimeTicket();m.setExecutedAt(v),t.push(m)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,Ge.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ge.UndoRedo),s=t.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushRedo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ge.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ge.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(ee.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new ne(ee.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of e){if(!(m instanceof en)){new io(t,Gt(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=t.issueTimeTicket();m.setExecutedAt(v),t.push(m)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,Ge.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ge.UndoRedo),s=t.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushUndo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ge.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ge.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const r={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([r])}}function hf(i,e){return t=>async n=>(i&&n.header.set("x-api-key",i),e&&n.header.set("authorization",e),await t(n))}const df="yorkie-js-sdk",gf="0.5.0",pf="Yorkie JS SDK",mf="./src/yorkie.ts",yf={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},vf=["dist"],bf={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},wf={node:">=18.0.0",npm:">=7.1.0"},Af={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Tf={name:"hackerwins",email:"susukang98@gmail.com"},_f="Apache-2.0",Ef={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Of="https://github.com/yorkie-team/yorkie-js-sdk#readme",Sf={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},kf={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Es={name:df,version:gf,description:pf,main:mf,publishConfig:yf,files:vf,scripts:bf,engines:wf,repository:Af,author:Tf,license:_f,bugs:Ef,homepage:Of,devDependencies:Sf,dependencies:kf};function xf(){return i=>async e=>(e.header.set("x-yorkie-user-agent",Es.name+"/"+Es.version),await i(e))}const Nf=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Mi=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Mi||{});const xi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},lo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class tl{constructor(e,t){J(this,"id");J(this,"key");J(this,"status");J(this,"attachmentMap");J(this,"apiKey");J(this,"conditions");J(this,"syncLoopDuration");J(this,"reconnectStreamDelay");J(this,"retrySyncLoopDelay");J(this,"rpcClient");J(this,"taskQueue");J(this,"processing",!1);t=t||xi,this.key=t.key?t.key:Za(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||xi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||xi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||xi.retrySyncLoopDelay,this.rpcClient=ou(Yu,ku({baseUrl:e,interceptors:[hf(t.apiKey,t.token),xf()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),xe.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw xe.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),xe.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw xe.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new ne(ee.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((o,s)=>s.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async o=>{var v;const{topic:s,payload:u}=o.value,c=(v=o.options)==null?void 0:v.error,m=o.options;try{await this.broadcast(e.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ct.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async o=>{const s=ct.fromChangePack(o.changePack);return e.applyChangePack(s),e.getStatus()===Gn.Removed||(e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new ef(this.reconnectStreamDelay,e,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(e.getKey()),xe.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(o=>{throw xe.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(e,t={}){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new ne(ee.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:ct.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const o=ct.fromChangePack(r.changePack);return e.applyChangePack(o),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),xe.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw xe.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new ne(ee.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=n.syncMode;return r===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new ne(ee.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw xe.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw xe.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new ne(ee.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=ct.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const o=ct.fromChangePack(r.changePack);e.applyChangePack(o),this.detachInternal(e.getKey()),xe.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw xe.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,r){if(!this.isActive())throw new ne(ee.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(e);if(!o)throw new ne(ee.ErrDocumentNotAttached,`${e} is not attached`);if(!Nf(n))throw new ne(ee.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??lo.maxRetries,u=lo.maxBackoff;let c=0;const m=d=>Math.min(lo.initialRetryInterval*2**d,u),v=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{xe.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(d=>{if(xe.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cv(),m(c-1)),xe.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw xe.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return v()}runSyncLoop(){const e=()=>{if(!this.isActive()){xe.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{xe.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};xe.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new ne(ee.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(ee.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:r.signal});return t.doc.publish([{type:dt.ConnectionChanged,value:li.Connected}]),xe.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(t,m),m.body.case==="initialization"&&s([o,r])}catch(m){t.doc.resetOnlineClients(),t.doc.publish([{type:dt.Initialized,source:Ge.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:dt.ConnectionChanged,value:li.Disconnected}]),xe.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Gr.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Gn.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:r}=e,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:ct.toChangePack(o),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=ct.fromChangePack(s.changePack);if(u.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),e.doc.publish([{type:dt.SyncStatusChanged,value:vo.Synced}]),n.getStatus()===Gn.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return xe.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:dt.SyncStatusChanged,value:vo.SyncFailed}]),xe.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(e){return e instanceof at?e.code===We.Canceled||e.code===We.Unknown||e.code===We.ResourceExhausted||e.code===We.Unavailable?!0:((bs(e)===ee.ErrClientNotActivated||bs(e)===ee.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{xe.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const uo={Client:tl,Document:el,Primitive:Xe,Text:Yi,Counter:Zi,Tree:Xi,LogLevel:bt,setLogLevel:Ya,IntType:In.IntegerCnt,LongType:In.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:tl,Document:el,Primitive:Xe,Text:Yi,Counter:Zi,Tree:Xi,LogLevel:bt,setLogLevel:Ya,IntType:In.IntegerCnt,LongType:In.LongCnt});var If=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function nl(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var rl={exports:{}};/*! * Quill Editor v1.3.7 * https://quilljs.com/ diff --git a/examples/vanilla-quill/index.html b/examples/vanilla-quill/index.html index 6cd43b848..2467c4e72 100644 --- a/examples/vanilla-quill/index.html +++ b/examples/vanilla-quill/index.html @@ -4,7 +4,7 @@ Yorkie + Quill Example - + diff --git a/examples/vuejs-kanban/assets/index-D-1FOS7C.js b/examples/vuejs-kanban/assets/index-CYjMH9QM.js similarity index 61% rename from examples/vuejs-kanban/assets/index-D-1FOS7C.js rename to examples/vuejs-kanban/assets/index-CYjMH9QM.js index baeefe292..411e812b3 100644 --- a/examples/vuejs-kanban/assets/index-D-1FOS7C.js +++ b/examples/vuejs-kanban/assets/index-CYjMH9QM.js @@ -19,5 +19,5 @@ var fu=Object.defineProperty;var hu=(n,e,t)=>e in n?fu(n,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var He=null;try{He=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function xe(n){return(n&&n.__isLong__)===!0}function Da(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=xe;var Ra={},_a={};function On(n,e){var t,r,s;return e?(n>>>=0,(s=0<=n&&n<256)&&(r=_a[n],r)?r:(t=Z(n,0,!0),s&&(_a[n]=t),t)):(n|=0,(s=-128<=n&&n<128)&&(r=Ra[n],r)?r:(t=Z(n,n<0?-1:0,!1),s&&(Ra[n]=t),t))}q.fromInt=On;function Ge(n,e){if(isNaN(n))return e?Jt:ot;if(e){if(n<0)return Jt;if(n>=xl)return Ol}else{if(n<=-Ma)return Be;if(n+1>=Ma)return Cl}return n<0?Ge(-n,e).neg():Z(n%Xn|0,n/Xn|0,e)}q.fromNumber=Ge;function Z(n,e,t){return new q(n,e,t)}q.fromBits=Z;var bs=Math.pow;function ro(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?Jt:ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return ro(n.substring(1),e,t).neg();for(var s=Ge(bs(t,8)),i=ot,o=0;o>>0:this.low};E.toNumber=function(){return this.unsigned?(this.high>>>0)*Xn+(this.low>>>0):this.high*Xn+(this.low>>>0)};E.toString=function(e){if(e=e||10,e<2||36>>0,u=l.toString(e);if(o=c,o.isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}};E.getHighBits=function(){return this.high};E.getHighBitsUnsigned=function(){return this.high>>>0};E.getLowBits=function(){return this.low};E.getLowBitsUnsigned=function(){return this.low>>>0};E.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Be)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};E.isOdd=function(){return(this.low&1)===1};E.isEven=function(){return(this.low&1)===0};E.equals=function(e){return xe(e)||(e=ht(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};E.eq=E.equals;E.notEquals=function(e){return!this.eq(e)};E.neq=E.notEquals;E.ne=E.notEquals;E.lessThan=function(e){return this.comp(e)<0};E.lt=E.lessThan;E.lessThanOrEqual=function(e){return this.comp(e)<=0};E.lte=E.lessThanOrEqual;E.le=E.lessThanOrEqual;E.greaterThan=function(e){return this.comp(e)>0};E.gt=E.greaterThan;E.greaterThanOrEqual=function(e){return this.comp(e)>=0};E.gte=E.greaterThanOrEqual;E.ge=E.greaterThanOrEqual;E.compare=function(e){if(xe(e)||(e=ht(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};E.comp=E.compare;E.negate=function(){return!this.unsigned&&this.eq(Be)?Be:this.not().add(Bn)};E.neg=E.negate;E.add=function(e){xe(e)||(e=ht(e));var t=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,c=e.low>>>16,l=e.low&65535,u=0,h=0,v=0,g=0;return g+=i+l,v+=g>>>16,g&=65535,v+=s+c,h+=v>>>16,v&=65535,h+=r+a,u+=h>>>16,h&=65535,u+=t+o,u&=65535,Z(v<<16|g,u<<16|h,this.unsigned)};E.subtract=function(e){return xe(e)||(e=ht(e)),this.add(e.neg())};E.sub=E.subtract;E.multiply=function(e){if(this.isZero())return this;if(xe(e)||(e=ht(e)),He){var t=He.mul(this.low,this.high,e.low,e.high);return Z(t,He.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Jt:ot;if(this.eq(Be))return e.isOdd()?Be:ot;if(e.eq(Be))return this.isOdd()?Be:ot;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Ba)&&e.lt(Ba))return Ge(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,c=e.high&65535,l=e.low>>>16,u=e.low&65535,h=0,v=0,g=0,A=0;return A+=o*u,g+=A>>>16,A&=65535,g+=i*u,v+=g>>>16,g&=65535,g+=o*l,v+=g>>>16,g&=65535,v+=s*u,h+=v>>>16,v&=65535,v+=i*l,h+=v>>>16,v&=65535,v+=o*c,h+=v>>>16,v&=65535,h+=r*u+s*l+i*c+o*a,h&=65535,Z(g<<16|A,h<<16|v,this.unsigned)};E.mul=E.multiply;E.divide=function(e){if(xe(e)||(e=ht(e)),e.isZero())throw Error("division by zero");if(He){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?He.div_u:He.div_s)(this.low,this.high,e.low,e.high);return Z(t,He.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Jt:ot;var r,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Jt;if(e.gt(this.shru(1)))return Nl;i=Jt}else{if(this.eq(Be)){if(e.eq(Bn)||e.eq(Si))return Be;if(e.eq(Be))return Bn;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(ot)?e.isNegative()?Bn:Si:(s=this.sub(e.mul(r)),i=r.add(s.div(e)),i)}else if(e.eq(Be))return this.unsigned?Jt:ot;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=ot}for(s=this;s.gte(e);){r=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),c=a<=48?1:bs(2,a-48),l=Ge(r),u=l.mul(e);u.isNegative()||u.gt(s);)r-=c,l=Ge(r,this.unsigned),u=l.mul(e);l.isZero()&&(l=Bn),i=i.add(l),s=s.sub(u)}return i};E.div=E.divide;E.modulo=function(e){if(xe(e)||(e=ht(e)),He){var t=(this.unsigned?He.rem_u:He.rem_s)(this.low,this.high,e.low,e.high);return Z(t,He.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};E.mod=E.modulo;E.rem=E.modulo;E.not=function(){return Z(~this.low,~this.high,this.unsigned)};E.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};E.clz=E.countLeadingZeros;E.countTrailingZeros=function(){return this.low?Da(this.low):Da(this.high)+32};E.ctz=E.countTrailingZeros;E.and=function(e){return xe(e)||(e=ht(e)),Z(this.low&e.low,this.high&e.high,this.unsigned)};E.or=function(e){return xe(e)||(e=ht(e)),Z(this.low|e.low,this.high|e.high,this.unsigned)};E.xor=function(e){return xe(e)||(e=ht(e)),Z(this.low^e.low,this.high^e.high,this.unsigned)};E.shiftLeft=function(e){return xe(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Z(this.low<>>32-e,this.unsigned):Z(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Z(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};E.shr=E.shiftRight;E.shiftRightUnsigned=function(e){return xe(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Z(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Z(this.high,0,this.unsigned):Z(this.high>>>e-32,0,this.unsigned)};E.shru=E.shiftRightUnsigned;E.shr_u=E.shiftRightUnsigned;E.rotateLeft=function(e){var t;return xe(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Z(this.high,this.low,this.unsigned):e<32?(t=32-e,Z(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Z(this.high<>>t,this.low<>>t,this.unsigned))};E.rotl=E.rotateLeft;E.rotateRight=function(e){var t;return xe(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Z(this.high,this.low,this.unsigned):e<32?(t=32-e,Z(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Z(this.low<>>e,this.high<>>e,this.unsigned))};E.rotr=E.rotateRight;E.toSigned=function(){return this.unsigned?Z(this.low,this.high,!1):this};E.toUnsigned=function(){return this.unsigned?this:Z(this.low,this.high,!0)};E.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};E.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};E.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const Pg=y.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);y.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:$t}]);y.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);y.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:Dg,repeated:!0}]);const Dg=y.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});y.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:Rg,repeated:!0}]);const Rg=y.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});y.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:_g,repeated:!0}]);const _g=y.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});y.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);y.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);y.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:Fg,repeated:!0}]);const Fg=y.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});y.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var p=(n=>(n.Ok="ok",n.ErrClientNotActivated="ErrClientNotActivated",n.ErrClientNotFound="ErrClientNotFound",n.ErrUnimplemented="ErrUnimplemented",n.ErrInvalidType="ErrInvalidType",n.ErrDummy="ErrDummy",n.ErrDocumentNotAttached="ErrDocumentNotAttached",n.ErrDocumentNotDetached="ErrDocumentNotDetached",n.ErrDocumentRemoved="ErrDocumentRemoved",n.ErrInvalidObjectKey="ErrInvalidObjectKey",n.ErrInvalidArgument="ErrInvalidArgument",n.ErrNotInitialized="ErrNotInitialized",n.ErrNotReady="ErrNotReady",n.ErrRefused="ErrRefused",n.ErrContextNotProvided="ErrContextNotProvided",n))(p||{});class T extends Error{constructor(t,r){super(r);d(this,"name","YorkieError");d(this,"stack");this.code=t,this.message=r,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function nt(n){if(n instanceof Map){const e=Array.from(n);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(n))}const Pl=n=>n?Object.entries(n).length===0:!0,Zn=n=>{const e={};for(const[t,r]of Object.entries(n))e[t]=JSON.stringify(r);return e},Kn=n=>{const e={};for(const[t,r]of Object.entries(n))e[t]=JSON.parse(r);return e};var ln=(n=>(n.Put="put",n.Clear="clear",n))(ln||{});class ni{constructor(e,t){d(this,"context");d(this,"presence");this.context=e,this.presence=t}set(e,t){for(const r of Object.keys(e))this.presence[r]=e[r];this.context.setPresenceChange({type:"put",presence:nt(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const Ls="000000000000000000000000",Mg="FFFFFFFFFFFFFFFFFFFFFFFF";class Le{constructor(e,t,r){d(this,"lamport");d(this,"delimiter");d(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=r}static of(e,t,r){return new Le(e,t,r)}static fromStruct(e){return Le.of(q.fromString(e.lamport,!0),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new Le(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport.greaterThan(e.lamport))return 1;if(e.lamport.greaterThan(this.lamport))return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const so=0,Bg=4294967295,Lg=q.MAX_VALUE,lt=new Le(q.fromNumber(0),so,Ls);new Le(q.fromNumber(1),so+1,Ls);const pr=new Le(Lg,Bg,Mg);function Nt(n){return n.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` -`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class _r{constructor(e){d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class sn extends _r{constructor(e){super(e)}}class io{constructor(e,t){d(this,"strKey");d(this,"value");this.strKey=e,this.value=t}static of(e,t){return new io(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Nr{constructor(){d(this,"nodeMapByKey");d(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Nr}set(e,t,r){let s;const i=this.nodeMapByKey.get(e);i!=null&&!i.isRemoved()&&i.remove(r)&&(s=i.getValue());const o=io.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(i==null||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(r)),s}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(p.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new T(p.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(t))return r.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class $e extends sn{constructor(t,r){super(t);d(this,"memberNodes");this.memberNodes=r}static create(t,r){if(!r)return new $e(t,Nr.create());const s=Nr.create();for(const[i,o]of Object.entries(r))s.set(i,o.deepcopy(),o.getCreatedAt());return new $e(t,s)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,r,s){return this.memberNodes.set(t,r,s)}delete(t,r){return this.memberNodes.delete(t,r)}deleteByKey(t,r){return this.memberNodes.deleteByKey(t,r)}get(t){const r=this.memberNodes.get(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.memberNodes.getByID(t);return r==null?void 0:r.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[r,s]of this)t.push(`"${Nt(r)}":${s.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[r,s]of this){const{createdAt:i,value:o,type:a}=s.toJSForTest();t[r]={key:r,createdAt:i,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[r]of this)t.push(r);return t}toSortedJSON(){var s;const t=Array();for(const[i]of this)t.push(i);const r=[];for(const i of t.sort()){const o=(s=this.memberNodes.get(i))==null?void 0:s.getValue();r.push(`"${Nt(i)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=$e.create(this.getCreatedAt());for(const r of this.memberNodes)t.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const r of this.memberNodes){const s=r.getValue();if(t(s,this))return;s instanceof sn&&s.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const r of this.memberNodes)t.has(r.getStrKey())||(t.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var re=(n=>(n.Local="local",n.Remote="remote",n.UndoRedo="undoredo",n))(re||{});class ft{constructor(e,t){d(this,"parentCreatedAt");d(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(p.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Dl{constructor(e){d(this,"value");d(this,"left");d(this,"right");d(this,"parent");d(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Cr{constructor(e){d(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new T(p.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return[t,e]}indexOf(e){if(!e||e!==this.root&&!e.hasLinks())return-1;let t=0,r=e,s;for(;r;)(!s||s===r.getRight())&&(t+=r.getLength()+(r.hasLeft()?r.getLeftWeight():0)),s=r,r=r.getParent();return t-e.getLength()}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Cr(e.getLeft());t.root&&t.root.setParent();const r=new Cr(e.getRight());if(r.root&&r.root.setParent(),t.root){const s=t.getRightmost();t.splayNode(s),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const r of t)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class ce extends _r{constructor(t,r){super(r);d(this,"valueType");d(this,"value");this.valueType=ce.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ce(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const s=new DataView(r.buffer);return r.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${Nt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ce.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ce.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(p.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class As extends Dl{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,r){const s=new As(r),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Or{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=ce.of(0,lt);e.setRemovedAt(lt),this.dummyHead=new As(e),this.last=this.dummyHead,this.nodeMapByIndex=new Cr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Or}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(p.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,r),i=As.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new T(p.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new T(p.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new T(p.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),s=r.isRemoved();return r.remove(t)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class Ke extends sn{constructor(t,r){super(t);d(this,"elements");this.elements=r}static create(t,r){if(!r)return new Ke(t,Or.create());const s=Or.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new Ke(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,s){this.elements.moveAfter(t,r,s)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const s=r.getValue();if(t(s,this))return;s instanceof sn&&s.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...g,value:g.value?{attributes:Kn(g.value.getAttributes()),content:g.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,u,[c,c]]}setStyle(t,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),c=[],l=this.rgaTreeSplit.findBetween(a,o),u=new Map,h=[];for(const g of l){const A=g.getCreatedAt().getActorID(),x=i!=null&&i.size?i.has(A)?i.get(A):lt:pr;if(g.canStyle(s,x)){const R=u.get(A),L=g.getCreatedAt();(!R||L.after(R))&&u.set(A,L),h.push(g)}}const v=[];for(const g of h){if(g.isRemoved())continue;const[A,x]=this.rgaTreeSplit.findIndexesFromRange(g.createPosRange());c.push({type:"style",actor:s.getActorID(),from:A,to:x,value:{attributes:Kn(r)}});for(const[R,L]of Object.entries(r)){const[$]=g.getValue().setAttr(R,L,s);$!==void 0&&v.push({parent:g.getValue(),child:$})}}return[u,v,c]}indexRangeToPosRange(t,r){const s=this.rgaTreeSplit.indexToPos(t);return t===r?[s,s]:[s,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();t.push({attributes:Kn(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Ye(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())t.push(s)}return t}}class Mr extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,r,s,i,o,a,c){return new Mr(t,r,s,i,o,a,c)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ye))throw new T(p.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:l})=>({type:"edit",from:a,to:c,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Br extends ft{constructor(t,r,s,i,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,r,s,i,o,a){return new Br(t,r,s,i,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ye))throw new T(p.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:c,value:l})=>({type:"style",from:a,to:c,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const $g=2,Ug="root",zt="text";function cr(n,e){let t=0;const r=n.children;for(let s=0;s0)throw new T(p.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===zt}get paddedSize(){return this.size+(this.isText?0:$g)}isAncestorOf(e){return zg(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=r;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new T(p.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,r._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function zg(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var me=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(me||{});function Rl(n,e,t,r){if(e>t)throw new T(p.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new T(p.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new T(p.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let s=0;for(const i of n.children){if(e-i.paddedSizei.size;(i.isText||c)&&r([i,i.isText?"Text":"Start"],l),Rl(i,Math.max(0,o),Math.min(a,i.size),r),l&&r([i,"End"],l)}s+=i.paddedSize}}function _l(n,e,t=0){for(const r of n.children)_l(r,e,t+1);e(n,t)}function $s(n,e,t=0){for(const r of n._children)$s(r,e,t+1);e(n,t)}function ki(n,e,t=!0){if(e>n.size)throw new T(p.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,s=0;for(const i of n.children){if(t&&i.isText&&i.size>=e-s)return ki(i,e-s,t);if(e===s)return{node:n,offset:r};if(!t&&i.paddedSize===e-s)return{node:n,offset:r+1};if(i.paddedSize>e-s)return ki(i,e-s-1,t);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Fl(n){return n.isText||n.children.length===0?n:Fl(n.children[0])}function qg(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new Vg(e,t,!0);const s=this.comparator(e,r.key);return s<0?r.left=this.putInternal(e,t,r.left):s>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class at{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new at(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,s;return r.isText?(r.parent.children[0]===r&&t===0?s=r.parent:s=r,r=r.parent):t===0?s=r:s=r.children[t-1],at.of(r.id,be.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return at.of(be.of(Le.fromStruct(e.parentID.createdAt),e.parentID.offset),be.of(Le.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(r);if(!s||!i)throw new T(p.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class be{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new be(e,t)}static fromStruct(e){return be.of(Le.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new T(p.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new T(p.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new qe(be.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new qe(be.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new jt);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,r));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Ei(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(Ei)};return n.attrs&&(e.attributes=Kn((t=n.attrs)==null?void 0:t.toObject())),e}function oo(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${Nt(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>oo(t)).join("")}`}function Bl(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(Bl),size:n.size,isRemoved:n.isRemoved}}class Xe extends _r{constructor(t,r){super(r);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new Kg(t),this.nodeMapByID=new Ml(be.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,r){return new Xe(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,c=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const l=c.allChildren,u=a?0:l.indexOf(o)+1;for(let h=u;h{const x=A.getCreatedAt().getActorID(),R=i?i.has(x)?i.get(x):lt:pr;if(A.canStyle(s,R)&&r){const L=v.get(x),$=A.getCreatedAt();(!L||$.after(L))&&v.set(x,$);const Y=A.setAttrs(r,s),P=Y.reduce((oe,[,Ie])=>(Ie&&(oe[Ie.getKey()]=h[Ie.getKey()]),oe),{}),H=A.parent,Q=A.prevSibling||A.parent;Object.keys(P).length>0&&u.push({type:"style",from:this.toIndex(H,Q),to:this.toIndex(A,A),fromPath:this.toPath(H,Q),toPath:this.toPath(A,A),actor:s.getActorID(),value:P});for(const[oe]of Y)oe&&g.push({parent:A,child:oe})}}),[v,g,u]}removeStyle(t,r,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[c,l]=this.findNodesAndSplitText(t[1],s),u=[],h=new Map,v=[];return this.traverseInPosRange(o,a,c,l,([g])=>{const A=g.getCreatedAt().getActorID(),x=i?i.has(A)?i.get(A):lt:pr;if(g.canStyle(s,x)&&r){const R=h.get(A),L=g.getCreatedAt();(!R||L.after(R))&&h.set(A,L),g.attrs||(g.attrs=new jt);for(const P of r){const H=g.attrs.remove(P,s);for(const Q of H)v.push({parent:g,child:Q})}const $=g.parent,Y=g.prevSibling||g.parent;u.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex($,Y),to:this.toIndex(g,g),fromPath:this.toPath($,Y),toPath:this.toPath(g,g),value:r})}}),[h,v,u]}edit(t,r,s,i,o,a){const[c,l]=this.findNodesAndSplitText(t[0],i),[u,h]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(c,l),g=this.toPath(c,l),A=[],x=[],R=[],L=new Map;this.traverseInPosRange(c,l,u,h,([P,H],Q)=>{if(H===me.Start&&!Q)for(const Qe of P.children)R.push(Qe);const oe=P.getCreatedAt().getActorID(),Ie=a?a.has(oe)?a.get(oe):lt:pr;if(P.canDelete(i,Ie)||A.includes(P.parent)){const Qe=L.get(oe),Ve=P.getCreatedAt();(!Qe||Ve.after(Qe))&&L.set(oe,Ve),(H===me.Text||H===me.Start)&&A.push(P),x.push([P,H])}});const $=this.makeDeletionChanges(x,i),Y=[];for(const P of A)P.remove(i),P.isRemoved&&Y.push({parent:this,child:P});for(const P of R)P.removedAt||c.append(P);if(s>0){let P=0,H=c,Q=l;for(;P{c.isRemoved&&(oe.remove(i),Y.push({parent:this,child:oe})),this.nodeMapByID.put(oe.id,oe)}),Q.isRemoved||P.push(Q);if(P.length){const Q=P.map(oe=>Ei(oe));$.length&&$[$.length-1].from===v?$[$.length-1].value=Q:$.push({type:"content",from:v,to:v,fromPath:g,toPath:g,actor:i.getActorID(),value:Q})}}return[$,Y,L]}editT(t,r,s,i,o){const a=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([a,c],r,s,i,o)}move(t,r,s){throw new T(p.ErrUnimplemented,`not implemented: ${t}, ${r}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,s=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const s of r.getGCPairs())t.push(s)}),t}findPos(t,r=!0){const s=this.indexTree.findTreePos(t,r);return at.fromTreePos(s)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return oo(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,a=0)=>{var g,A,x,R;let c,l,u;const h=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;h&&(c=this.indexTree.indexOf(h),l=this.indexTree.treePosToPath(h),u=at.fromTreePos(h).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(g=s.removedAt)==null?void 0:g.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(x=s.insNextID)==null?void 0:x.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?Kn((R=s.attrs)==null?void 0:R.toObject()):void 0,index:c,path:l,pos:u};for(let L=0;L0&&L===s[s.length-1].to?(s[s.length-1].to=$,s[s.length-1].toPath=this.toPath(R,g)):s.push({type:"content",from:L,to:$,fromPath:this.toPath(x,h),toPath:this.toPath(R,g),actor:r.getActorID()}))}return s.reverse()}findRightToken([t,r]){if(r===me.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?me.Text:me.Start]:[t,me.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,me.End];const a=i[o+1];return[a,a.isText?me.Text:me.Start]}findLeftToken([t,r]){if(r===me.End){const c=t.allChildren;if(c.length>0){const l=c[c.length-1];return[l,l.isText?me.Text:me.End]}return[t,me.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,me.Start];const a=i[o-1];return[a,a.isText?me.Text:me.End]}}class Lr extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,s,i,o,a,c){return new Lr(t,r,s,i,o,a,c)}execute(t){var c;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Xe))throw new T(p.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,a]=i.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>Le.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:u,value:h,splitLevel:v,fromPath:g,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:u,value:h,splitLevel:v,fromPath:g,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${r},${s},${i.map(o=>oo(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class en{constructor(e,t,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.actor=r}static of(e,t,r,s){return new en(e,t,r,s)}next(){return new en(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new en(this.clientSeq,e,this.actor):new en(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return Le.of(this.lamport,e,this.actor)}setActor(e){return new en(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Hg=new en(0,q.fromInt(0,!0),Ls);class Qn{constructor({id:e,operations:t,presenceChange:r,message:s}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=s}static create({id:e,operations:t,presenceChange:r,message:s}){return new Qn({id:e,operations:t,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:c,reverseOp:l}=a;s.push(...c),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===ln.Put?t.set(this.id.getActorID(),nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:Te.bytesToHex(Te.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>Te.bytesToHex(Te.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:s,message:i}=e;return Qn.create({id:Te.bytesToChangeID(Te.hexToBytes(t)),operations:r==null?void 0:r.map(o=>Te.bytesToOperation(Te.hexToBytes(o))),presenceChange:s,message:i})}}class Us{constructor(e,t,r,s,i,o){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(e,t,r,s,i,o){return new Us(e,t,r,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class jn{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new jn(e,t)}increaseClientSeq(e){return e===0?this:new jn(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return jn.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Gg=new jn(q.fromInt(0,!0),0);class Ot{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ot(e,t)}static fromStruct(e){return Ot.of(Le.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Ot(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Yg=Ot.of(lt,0);class ut{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new ut(e,t)}static fromStruct(e){const t=Ot.fromStruct(e.id);return ut.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ot.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class on extends Dl{constructor(t,r,s){super(r);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=s}static create(t,r){return new on(t,r)}static createComparator(){return(t,r)=>{const s=t.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let s=e;for(;s&&s!==t;)r.push(s),s=s.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new T(p.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const s=e.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,r),o=new Map,a=new Map,c=this.makeChanges(i,t);for(const l of s){const u=l.getCreatedAt().getActorID();(!o.has(u)||l.getID().getCreatedAt().after(o.get(u)))&&o.set(u,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[c,o,a]}filterNodes(e,t,r){const s=!!r,i=[],o=[],[a,c]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const u=l.getCreatedAt().getActorID(),h=s?r.has(u)?r.get(u):lt:pr;l.canDelete(t,h)?i.push(l):o.push(l)}return o.push(c),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pt=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pt||{});class je extends _r{constructor(t,r,s){super(s);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=La(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,s){return new je(t,r,s)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=je.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!je.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(p.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+La(t.getValue())).toInt(),this}}class tr extends ft{constructor(t,r,s){super(t,s);d(this,"value");this.value=r}static create(t,r,s){return new tr(t,r,s)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof je))throw new T(p.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return tr.create(this.getParentCreatedAt(),ce.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class qt extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,r,s,i,o,a){return new qt(t,r,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,s,i,o,a){return new qt(t,r,s,i,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Xe))throw new T(p.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([c,l])=>a[c]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:l,fromPath:u,toPath:h})=>({type:"tree-style",from:a,to:c,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:u,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Xg(n){const e=new no,t=e.data;for(const[r,s]of Object.entries(n))t[r]=JSON.stringify(s);return e}function Zg(n){if(n.type===ln.Put)return new Ii({type:xr.PUT,presence:Xg(n.presence)});if(n.type===ln.Clear)return new Ii({type:xr.CLEAR});throw new T(p.ErrUnimplemented,"unimplemented type")}function Qg(n){return new El({serverSeq:n.getServerSeqAsString(),clientSeq:n.getClientSeq()})}function Ll(n){return new Ms({clientSeq:n.getClientSeq(),lamport:n.getLamportAsString(),actorId:go(n.getActorID())})}function F(n){if(n)return new B({lamport:n.getLamportAsString(),delimiter:n.getDelimiter(),actorId:go(n.getActorID())})}function $l(n){switch(n){case ve.Null:return V.NULL;case ve.Boolean:return V.BOOLEAN;case ve.Integer:return V.INTEGER;case ve.Long:return V.LONG;case ve.Double:return V.DOUBLE;case ve.String:return V.STRING;case ve.Bytes:return V.BYTES;case ve.Date:return V.DATE;default:throw new T(p.ErrInvalidType,`unsupported type: ${n}`)}}function Ul(n){switch(n){case Pt.IntegerCnt:return V.INTEGER_CNT;case Pt.LongCnt:return V.LONG_CNT;default:throw new T(p.ErrInvalidType,`unsupported type: ${n}`)}}function ri(n){if(n instanceof $e)return new Bt({type:V.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ql(n)});if(n instanceof Ke)return new Bt({type:V.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:Nm(n)});if(n instanceof Ye)return new Bt({type:V.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ce)return new Bt({type:$l(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof je)return new Bt({type:Ul(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Xe)return new Bt({type:V.TREE,createdAt:F(n.getCreatedAt()),value:Om(n)});throw new T(p.ErrUnimplemented,"unimplemented element")}function em(n){return new Ai({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Xr(n){return new xn({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function Zr(n){return new Er({parentId:yr(n.getParentID()),leftSiblingId:yr(n.getLeftSiblingID())})}function yr(n){return new qn({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Jl(n){const e=new Qi;if(n instanceof Nn){const t=n,r=new cl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Fr){const t=n,r=new ll;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof tn){const t=n,r=new ul;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof un){const t=n,r=new fl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Mr){const t=n,r=new hl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Xr(t.getFromPos()),r.to=Xr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);r.content=t.getContent();const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Br){const t=n,r=new dl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Xr(t.getFromPos()),r.to=Xr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof tr){const t=n,r=new gl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Lr){const t=n,r=new ml,s=r.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zr(t.getFromPos()),r.to=Zr(t.getToPos()),r.contents=am(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof qt){const t=n,r=new pl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zr(t.getFromPos()),r.to=Zr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);const i=t.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[a,c]of t.getAttributes())o[a]=c}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(p.ErrUnimplemented,"unimplemented operation");return e}function tm(n){const e=[];for(const t of n)e.push(Jl(t));return e}function nm(n){const e=new al({id:Ll(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=tm(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=Zg(n.getPresenceChange())),e}function rm(n){const e=[];for(const t of n)e.push(nm(t));return e}function sm(n){const e=[];for(const t of n)e.push(new Il({key:t.getStrKey(),element:co(t.getValue())}));return e}function im(n){const e=[];for(const t of n)e.push(new eo({element:co(t.getValue())}));return e}function om(n){const e=[];for(const t of n){const r=new Sl;r.id=em(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const s=r.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new Bs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),s[o.getKey()]=a}e.push(r)}return e}function am(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new kl({content:ao(t)}));return e}function cm(n){const e={};for(const t of n)e[t.getKey()]=new Bs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ao(n){if(!n)return[];const e=[];return $s(n,(t,r)=>{const s=new to({id:yr(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=yr(t.insPrevID)),t.insNextID&&(s.insNextId=yr(t.insNextID)),t.attrs&&(s.attributes=cm(t.attrs)),e.push(s)}),e}function lm(n){const e=new Ze;return e.body.case="jsonObject",e.body.value=new yl({nodes:sm(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function zl(n){const e=new Ze;return e.body.case="jsonArray",e.body.value=new vl({nodes:im(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function um(n){const e=new Ze;return e.body.case="primitive",e.body.value=new Tl({type:$l(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function fm(n){const e=new Ze;return e.body.case="text",e.body.value=new wl({nodes:om(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hm(n){const e=new Ze;return e.body.case="counter",e.body.value=new bl({type:Ul(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function ql(n){const e=new Ze;return e.body.case="tree",e.body.value=new Al({nodes:ao(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function co(n){if(n instanceof $e)return lm(n);if(n instanceof Ke)return zl(n);if(n instanceof ce)return um(n);if(n instanceof Ye)return fm(n);if(n instanceof je)return hm(n);if(n instanceof Xe)return ql(n);throw new T(p.ErrUnimplemented,"unimplemented element")}function dm(n){return new Wt({documentKey:n.getDocumentKey(),checkpoint:Qg(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:rm(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:F(n.getMinSyncedTicket())})}function $a(n){const e=n.findDetails(Pg);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Kl(n){let e;return n.serverSeq&&(e=q.fromString(n.serverSeq,!0)),en.of(n.clientSeq,q.fromString(n.lamport,!0),ho(n.actorId),e)}function M(n){if(n)return Le.of(q.fromString(n.lamport,!0),n.delimiter,ho(n.actorId))}function lo(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function gm(n){const e=n.type;if(e===xr.PUT){const t=lo(n.presence);return{type:ln.Put,presence:t}}if(e===xr.CLEAR)return{type:ln.Clear};throw new T(p.ErrInvalidType,`unsupported type: ${e}`)}function mm(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,lo(r))}),e}function jl(n){switch(n){case V.NULL:return ve.Null;case V.BOOLEAN:return ve.Boolean;case V.INTEGER:return ve.Integer;case V.LONG:return ve.Long;case V.DOUBLE:return ve.Double;case V.STRING:return ve.String;case V.BYTES:return ve.Bytes;case V.DATE:return ve.Date}throw new T(p.ErrUnimplemented,`unimplemented value type: ${n}`)}function Is(n){switch(n){case V.INTEGER_CNT:return Pt.IntegerCnt;case V.LONG_CNT:return Pt.LongCnt}throw new T(p.ErrUnimplemented,`unimplemented value type: ${n}`)}function si(n){switch(n.type){case V.JSON_OBJECT:return n.value?Zl(n.value):$e.create(M(n.createdAt));case V.JSON_ARRAY:return n.value?xm(n.value):Ke.create(M(n.createdAt));case V.TEXT:return Ye.create(er.create(),M(n.createdAt));case V.TREE:return Cm(n.value);case V.NULL:case V.BOOLEAN:case V.INTEGER:case V.LONG:case V.DOUBLE:case V.STRING:case V.BYTES:case V.DATE:return ce.of(ce.valueFromBytes(jl(n.type),n.value),M(n.createdAt));case V.INTEGER_CNT:case V.LONG_CNT:return je.create(Is(n.type),je.valueFromBytes(Is(n.type),n.value),M(n.createdAt))}}function Qr(n){return ut.of(Ot.of(M(n.createdAt),n.offset),n.relativeOffset)}function Vl(n){return Ot.of(M(n.createdAt),n.offset)}function pm(n){const e=Pr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{e.setAttr(r,s.value,M(s.updatedAt))});const t=on.create(Vl(n.id),e);return t.remove(M(n.removedAt)),t}function _n(n){return at.of(vr(n.parentId),vr(n.leftSiblingId))}function vr(n){return be.of(M(n.createdAt),n.offset)}function ym(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=uo(t.content);e.push(r)}),e}function uo(n){if(n.length===0)return;const e=[];for(const s of n)e.push(Tm(s));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(e[s]),r.set(n[s].depth,e[s]);return t.updateDescendantsSize(),Xe.create(t,lt).getRoot()}function vm(n){const e=jt.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function Tm(n){const e=vr(n.id),t=qe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=vm(n.attributes)),n.insPrevId&&(t.insPrevID=vr(n.insPrevId)),n.insNextId&&(t.insNextID=vr(n.insNextId)),t.removedAt=M(n.removedAt),t}function Wl(n){if(n.body.case==="set"){const e=n.body.value;return Nn.create(e.key,si(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Fr.create(M(e.parentCreatedAt),M(e.prevCreatedAt),si(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return tn.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return un.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const r=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{r.set(s,i)}),Mr.create(M(e.parentCreatedAt),Qr(e.from),Qr(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const r=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{r.set(s,i)}),Br.create(M(e.parentCreatedAt),Qr(e.from),Qr(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return tr.create(M(e.parentCreatedAt),si(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,M(s))}),Lr.create(M(e.parentCreatedAt),_n(e.from),_n(e.to),ym(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,M(o))}),(r==null?void 0:r.length)>0?qt.createTreeRemoveStyleOperation(M(e.parentCreatedAt),_n(e.from),_n(e.to),s,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),qt.create(M(e.parentCreatedAt),_n(e.from),_n(e.to),s,t,M(e.executedAt)))}else throw new T(p.ErrUnimplemented,"unimplemented operation")}}function wm(n){const e=[];for(const t of n){const r=Wl(t);r&&e.push(r)}return e}function Hl(n){const e=[];for(const t of n)e.push(Qn.create({id:Kl(t.id),operations:wm(t.operations),presenceChange:t.presenceChange?gm(t.presenceChange):void 0,message:t.message}));return e}function bm(n){return jn.of(q.fromString(n.serverSeq,!0),n.clientSeq)}function Am(n){return Us.create(n.documentKey,bm(n.checkpoint),n.isRemoved,Hl(n.changes),n.snapshot,M(n.minSyncedTicket))}function Gl(n){const e=new Nr;for(const r of n.nodes){const s=fo(r.element);e.set(r.key,s,s.getPositionedAt())}const t=new $e(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Yl(n){const e=new Or;for(const r of n.nodes)e.insert(fo(r.element));const t=new Ke(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Im(n){const e=ce.of(ce.valueFromBytes(jl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Sm(n){const e=new er;let t=e.getHead();for(const s of n.nodes){const i=e.insertAfter(t,pm(s));s.insPrevId&&i.setInsPrev(e.findNode(Vl(s.insPrevId))),t=i}const r=new Ye(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function km(n){const e=je.create(Is(n.type),je.valueFromBytes(Is(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Xl(n){const e=uo(n.nodes);return Xe.create(e,M(n.createdAt))}function fo(n){if(n.body.case==="jsonObject")return Gl(n.body.value);if(n.body.case==="jsonArray")return Yl(n.body.value);if(n.body.case==="primitive")return Im(n.body.value);if(n.body.case==="text")return Sm(n.body.value);if(n.body.case==="counter")return km(n.body.value);if(n.body.case==="tree")return Xl(n.body.value);throw new T(p.ErrUnimplemented,"unimplemented element")}function Em(n){if(!n)return{root:$e.create(lt),presences:new Map};const e=ag.fromBinary(n);return{root:fo(e.root),presences:mm(e.presences)}}function Zl(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Gl(e.body.value)}function Ql(n){return co(n).toBinary()}function xm(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Yl(e.body.value)}function Nm(n){return zl(n).toBinary()}function Cm(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Xl(e.body.value)}function Om(n){return ql(n).toBinary()}function eu(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ho(n){return eu(n)}function tu(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function go(n){return tu(n)}function Pm(n){const e=Ms.fromBinary(n);return Kl(e)}function Dm(n){const e=Qi.fromBinary(n);return Wl(e)}const Te={fromPresence:lo,toChangePack:dm,fromChangePack:Am,fromChanges:Hl,toTreeNodes:ao,fromTreeNodes:uo,objectToBytes:Ql,bytesToObject:Zl,bytesToSnapshot:Em,bytesToHex:eu,hexToBytes:tu,toHexString:ho,toUint8Array:go,toOperation:Jl,toChangeID:Ll,PbChangeID:Ms,bytesToChangeID:Pm,bytesToOperation:Dm};var De=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(De||{});let pn=3;function nu(n){pn=n}const z={trivial:(...n)=>{pn>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{pn>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{pn>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{pn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{pn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>pn<=n};function ru(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class Rm{constructor(e,t,r,s,i){d(this,"reconnectStreamDelay");d(this,"doc");d(this,"docID");d(this,"syncMode");d(this,"remoteChangeEventReceived");d(this,"watchStream");d(this,"watchLoopTimerID");d(this,"watchAbortController");d(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===ds.RealtimeSyncOff?!1:this.syncMode===ds.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==ds.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const ii=()=>{};class _m{constructor(e){d(this,"finalized",!1);d(this,"observers",[]);d(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let s;if(!e)throw new T(p.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(p.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:r},s.next===void 0&&(s.next=ii),s.error===void 0&&(s.error=ii),s.complete===void 0&&(s.complete=ii);const i=ru(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Ln{constructor(e,t,r,s){d(this,"id");d(this,"delimiter");d(this,"message");d(this,"root");d(this,"operations");d(this,"presenceChange");d(this,"previousPresence");d(this,"reversePresenceKeys");this.id=e,this.delimiter=so,this.root=t,this.operations=[],this.previousPresence=nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,r,s){return new Ln(e,t,r,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Qn.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Dr{constructor(e){d(this,"rootObject");d(this,"elementPairMapByCreatedAt");d(this,"gcElementSetByCreatedAt");d(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Ye||t instanceof Xe)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Dr($e.create(lt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new T(p.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof sn&&e.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(e){let t=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return r(e),e instanceof sn&&e.getDescendants(s=>(r(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof sn&&r.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Dr(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r);s.element.getRemovedAt()&&e.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s!==void 0&&e.compare(s)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function su(n,e){const t=new Rr(n);return new Proxy(e,t.getHandlers())}class Rr{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,r,s)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]=${JSON.stringify(s)}`),Rr.setInternal(e,t,r,s),!0),get:(t,r)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():yn(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]`),Rr.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,s){if(r.includes("."))throw new T(p.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=Ss(e,s,i),a=t.set(r,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nn.create(r,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const r={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new T(p.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Ss(e,i,o);r[s]=a}return r}static deleteInternal(e,t,r){const s=e.issueTimeTicket(),i=t.deleteByKey(r,s);i&&(e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function Mm(n,e){const t=new fe(n,e);return new Proxy(e,t.getHandlers())}function Bm(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Lm(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class fe{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Xt(e,a)}:s==="getElementByIndex"?o=>{const a=r.get(o);return Xt(e,a)}:s==="getLast"?()=>Xt(e,r.getLast()):s==="deleteByID"?o=>{const a=fe.deleteInternalByID(e,r,o);return Xt(e,a)}:s==="insertAfter"?(o,a)=>{const c=fe.insertAfterInternal(e,r,o,a);return Xt(e,c)}:s==="insertBefore"?(o,a)=>{const c=fe.insertBeforeInternal(e,r,o,a);return Xt(e,c)}:s==="moveBefore"?(o,a)=>{fe.moveBeforeInternal(e,r,o,a)}:s==="moveAfter"?(o,a)=>{fe.moveAfterInternal(e,r,o,a)}:s==="moveFront"?o=>{fe.moveFrontInternal(e,r,o)}:s==="moveLast"?o=>{fe.moveLastInternal(e,r,o)}:Bm(s)?yn(e,r.get(Number(s))):s==="push"?o=>fe.pushInternal(e,r,o):s==="splice"?(o,a,...c)=>fe.splice(e,r,o,a,...c):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?fe.iteratorInternal.bind(this,e,r):s==="includes"?(o,a)=>fe.includes(e,r,o,a):s==="indexOf"?(o,a)=>fe.indexOf(e,r,o,a):s==="lastIndexOf"?(o,a)=>fe.lastIndexOf(e,r,o,a):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>fe.toTestString(r):typeof s=="string"&&Lm(s)?(...o)=>{const a=Array.from(r).map(c=>yn(e,c));return Array.prototype[s].apply(a,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(z.isEnabled(De.Trivial)&&z.trivial(`array[${s}]`),fe.deleteInternalByIndex(e,r,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Xt(e,r)}static buildArrayElements(e,t){const r=[];for(const s of t){const i=e.issueTimeTicket(),o=Ss(e,s,i);r.push(o)}return r}static pushInternal(e,t,r){return fe.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,s,i),e.push(tn.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,r,s){const i=e.issueTimeTicket();t.moveAfter(r,s,i),e.push(tn.create(t.getCreatedAt(),r,s,i))}static moveFrontInternal(e,t,r){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,s),e.push(tn.create(t.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(e,t,r){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,s),e.push(tn.create(t.getCreatedAt(),i,r,s))}static insertAfterInternal(e,t,r,s){const i=e.issueTimeTicket(),o=Ss(e,s,i);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Fr.create(t.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,r,s){return fe.insertAfterInternal(e,t,t.getPrevCreatedAt(r),s)}static deleteInternalByIndex(e,t,r){const s=e.issueTimeTicket(),i=t.deleteByIndex(r,s);if(i)return e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){const s=e.issueTimeTicket(),i=t.delete(r,s);return e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,r,s,...i){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),c=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let u=a;u=i)return!1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).includes(r,o);for(let c=o;c=i)return-1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).indexOf(r,o);for(let c=o;c=i?i-1:s<0?s+i:s;if(o<0)return-1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).lastIndexOf(r,o);for(let c=o;c>0;c--)if(((a=t.get(c))==null?void 0:a.getID())===r.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Js{constructor(e,t){d(this,"context");d(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,s){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);z.isEnabled(De.Debug)&&z.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${r}`);const o=s?Zn(s):void 0,a=this.context.issueTimeTicket(),[c,,l,u]=this.text.edit(i,r,a,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Mr(this.text.getCreatedAt(),i[0],i[1],c,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(u)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);z.isEnabled(De.Debug)&&z.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Zn(r),o=this.context.issueTimeTicket(),[a,c]=this.text.setStyle(s,i,o);for(const l of c)this.context.registerGCPair(l);return this.context.push(new Br(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([ut.fromStruct(e[0]),ut.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class zs{constructor(e,t){d(this,"valueType");d(this,"value");d(this,"context");d(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(p.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ce.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(tr.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(p.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function mo(n,e,t){const{type:r}=n,s=t.issueTimeTicket();if(r===zt){iu(n);const{value:i}=n,o=qe.create(be.of(s,0),r,i);e.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Pl(o)){const l=Zn(o);a=new jt;for(const[u,h]of Object.entries(l))a.set(u,h,s)}const c=qe.create(be.of(s,0),r,void 0,a);e.append(c);for(const l of i)mo(l,c,t)}}function $m(n,e){const{type:t}=e,r=n.issueTimeTicket();let s;if(e.type===zt){const{value:i}=e;s=qe.create(be.of(r,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Pl(o)){const c=Zn(o);a=new jt;for(const[l,u]of Object.entries(c))a.set(l,u,r)}s=qe.create(be.of(n.issueTimeTicket(),0),t,void 0,a);for(const c of i)mo(c,s,n)}return s}function iu(n){if(!n.value.length)throw new T(p.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ua(n){if(!n.length)return!0;if(n[0].type===zt)for(const t of n){const{type:r}=t;if(r!==zt)throw new T(p.ErrInvalidArgument,"element node and text node cannot be passed together");iu(t)}else for(const t of n){const{type:r}=t;if(r===zt)throw new T(p.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class qs{constructor(e){d(this,"initialRoot");d(this,"context");d(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return qe.create(be.of(e.issueTimeTicket(),0),Ug);const t=qe.create(be.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)mo(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?Zn(t):void 0,[a]=this.tree.style([r,s],o,i);this.context.push(qt.create(this.tree.getCreatedAt(),r,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?Zn(r):void 0,[c,l]=this.tree.style([s,i],a,o);for(const u of l)this.context.registerGCPair(u);this.context.push(qt.create(this.tree.getCreatedAt(),s,i,c,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,c]=this.tree.removeStyle([s,i],r,o);for(const l of c)this.context.registerGCPair(l);this.context.push(qt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,r,o))}editInternal(e,t,r,s=0){var l;if(r.length!==0&&r[0]&&(Ua(r),r[0].type!==zt))for(const u of r){const{children:h=[]}=u;Ua(h)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=r[0])==null?void 0:l.type)===zt){let u="";for(const h of r){const{value:v}=h;u+=v}o.push(qe.create(be.of(this.context.issueTimeTicket(),0),zt,u))}else o=r.map(u=>u&&$m(this.context,u)).filter(u=>u);const[,a,c]=this.tree.edit([e,t],o.length?o.map(u=>u==null?void 0:u.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const u of a)this.context.registerGCPair(u);return this.context.push(Lr.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,c,i)),!0}editByPath(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new T(p.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new T(p.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,r,s)}edit(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,r?[r]:[],s)}editBulk(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[at.fromStruct(e[0]),at.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[at.fromStruct(e[0]),at.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Ja(n,e){return su(n,e)}function Xt(n,e){if(e){if(e instanceof ce)return e;if(e instanceof $e)return su(n,e);if(e instanceof Ke)return Mm(n,e);if(e instanceof Ye)return new Js(n,e);if(e instanceof je){const t=new zs(Pt.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Xe){const t=new qs;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function yn(n,e){const t=Xt(n,e);return t instanceof ce?t.getValue():t}function Ss(n,e,t){let r;if(ce.isSupport(e))r=ce.of(e,t);else if(Array.isArray(e))r=Ke.create(t,fe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Js?(r=Ye.create(er.create(),t),e.initialize(n,r)):e instanceof zs?(r=je.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof qs?(r=Xe.create(e.buildRoot(n),t),e.initialize(n,r)):r=$e.create(t,Rr.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const za=50;class Um{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=za&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=za&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Jm="yorkie-devtools-panel",zm="yorkie-devtools-sdk";let Mn="disconnected";const qa=new Map,hs=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=hs);function es(n,e){(e!=null&&e.force||Mn!=="disconnected")&&window.postMessage({source:zm,...n},"*")}function qm(n){if(!n.isEnableDevtools()||typeof window>"u"||qa.has(n.getKey()))return;hs.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Me.StatusChanged&&r.type!==Me.Snapshot&&r.type!==Me.LocalChange&&r.type!==Me.RemoteChange&&r.type!==Me.Initialized&&r.type!==Me.Watched&&r.type!==Me.Unwatched&&r.type!==Me.PresenceChanged)||(hs.get(n.getKey()).push(t),Mn==="synced"&&es({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});qa.set(n.getKey(),[e]),es({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==Jm)return;switch(t.data.msg){case"devtools::connect":if(Mn!=="disconnected")break;Mn="connected",es({msg:"doc::available",docKey:n.getKey()}),z.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Mn="disconnected",z.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Mn="synced",es({msg:"doc::sync::full",docKey:n.getKey(),events:hs.get(n.getKey())}),z.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Zt=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Zt||{}),Me=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(Me||{}),xi=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(xi||{}),Ni=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Ni||{});class ou{constructor(e,t){d(this,"key");d(this,"status");d(this,"opts");d(this,"changeID");d(this,"checkpoint");d(this,"localChanges");d(this,"root");d(this,"clone");d(this,"eventStream");d(this,"eventStreamObserver");d(this,"onlineClients");d(this,"presences");d(this,"history");d(this,"internalHistory");d(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Dr.create(),this.changeID=Hg,this.checkpoint=Gg,this.localChanges=[],this.eventStream=Fm(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Um,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},qm(this)}update(e,t){if(this.getStatus()==="removed")throw new T(p.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const i=Ja(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(i,new ni(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){z.isEnabled(De.Trivial)&&z.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,re.Local),c=s.getReversePresence();c&&a.push({type:"presence",value:c}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const l=[];o.length>0&&l.push({type:"local-change",source:re.Local,value:{message:i.getMessage()||"",operations:o,actor:r,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:re.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(l),z.isEnabled(De.Trivial)&&z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,s){if(typeof e=="string"){if(typeof t!="function")throw new T(p.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="initialized"&&l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||a(l)},r,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="initialized"&&l.type!=="presence-changed"||l.type==="presence-changed"&&l.value.clientID!==this.changeID.getActorID()||a(l)},r,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||l.value.clientID!==this.changeID.getActorID()&&a(l)},r,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="connection-changed"&&a(l)},r,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="status-changed"&&a(l)},r,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="sync-status-changed"&&a(l)},r,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="local-broadcast"&&a(l)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="broadcast"&&a(l)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const c of a){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const l=[];for(const u of c.value.operations)this.isSameElementOrChildOf(u.path,i)&&l.push(u);l.length&&o({...c,value:{...c.value,operations:l}})}},r,s)}if(typeof e=="function"){const i=e,o=t,a=r;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new T(p.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((i,o)=>i===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),re.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,re.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),z.isEnabled(De.Trivial)&&z.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:nt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Us.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ja(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:r,presences:s}=Te.bytesToSnapshot(t);this.root=new Dr(r),this.presences=s,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:re.Remote,value:{snapshot:this.isEnableDevtools()?Te.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){z.isEnabled(De.Debug)&&z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),z.isEnabled(De.Trivial)&&z.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` +`:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class _r{constructor(e){d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class sn extends _r{constructor(e){super(e)}}class io{constructor(e,t){d(this,"strKey");d(this,"value");this.strKey=e,this.value=t}static of(e,t){return new io(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class Nr{constructor(){d(this,"nodeMapByKey");d(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new Nr}set(e,t,r){let s;const i=this.nodeMapByKey.get(e);i!=null&&!i.isRemoved()&&i.remove(r)&&(s=i.getValue());const o=io.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(i==null||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(r)),s}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new T(p.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new T(p.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const r=this.nodeMapByKey.get(e);if(r!=null&&r.remove(t))return r.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class $e extends sn{constructor(t,r){super(t);d(this,"memberNodes");this.memberNodes=r}static create(t,r){if(!r)return new $e(t,Nr.create());const s=Nr.create();for(const[i,o]of Object.entries(r))s.set(i,o.deepcopy(),o.getCreatedAt());return new $e(t,s)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,r,s){return this.memberNodes.set(t,r,s)}delete(t,r){return this.memberNodes.delete(t,r)}deleteByKey(t,r){return this.memberNodes.deleteByKey(t,r)}get(t){const r=this.memberNodes.get(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.memberNodes.getByID(t);return r==null?void 0:r.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[r,s]of this)t.push(`"${Nt(r)}":${s.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[r,s]of this){const{createdAt:i,value:o,type:a}=s.toJSForTest();t[r]={key:r,createdAt:i,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[r]of this)t.push(r);return t}toSortedJSON(){var s;const t=Array();for(const[i]of this)t.push(i);const r=[];for(const i of t.sort()){const o=(s=this.memberNodes.get(i))==null?void 0:s.getValue();r.push(`"${Nt(i)}":${o.toSortedJSON()}`)}return`{${r.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=$e.create(this.getCreatedAt());for(const r of this.memberNodes)t.memberNodes.set(r.getStrKey(),r.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const r of this.memberNodes){const s=r.getValue();if(t(s,this))return;s instanceof sn&&s.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const r of this.memberNodes)t.has(r.getStrKey())||(t.add(r.getStrKey()),r.isRemoved()||(yield[r.getStrKey(),r.getValue()]))}}var re=(n=>(n.Local="local",n.Remote="remote",n.UndoRedo="undoredo",n))(re||{});class ft{constructor(e,t){d(this,"parentCreatedAt");d(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new T(p.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Dl{constructor(e){d(this,"value");d(this,"left");d(this,"right");d(this,"parent");d(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class Cr{constructor(e){d(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new T(p.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return this.splayNode(t),[t,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new Cr(e.getLeft());t.root&&t.root.setParent();const r=new Cr(e.getRight());if(r.root&&r.root.setParent(),t.root){const s=t.getRightmost();t.splayNode(s),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const r of t)r.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class ce extends _r{constructor(t,r){super(r);d(this,"valueType");d(this,"value");this.valueType=ce.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ce(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const s=new DataView(r.buffer);return r.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${Nt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ce.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ce.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new T(p.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class As extends Dl{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,r){const s=new As(r),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Or{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=ce.of(0,lt);e.setRemovedAt(lt),this.dummyHead=new As(e),this.last=this.dummyHead,this.nodeMapByIndex=new Cr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Or}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new T(p.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,r),i=As.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new T(p.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new T(p.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new T(p.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),s=r.isRemoved();return r.remove(t)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class Ke extends sn{constructor(t,r){super(t);d(this,"elements");this.elements=r}static create(t,r){if(!r)return new Ke(t,Or.create());const s=Or.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new Ke(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,s){this.elements.moveAfter(t,r,s)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const s=r.getValue();if(t(s,this))return;s instanceof sn&&s.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...g,value:g.value?{attributes:Kn(g.value.getAttributes()),content:g.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,u,[c,c]]}setStyle(t,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),c=[],l=this.rgaTreeSplit.findBetween(a,o),u=new Map,h=[];for(const g of l){const A=g.getCreatedAt().getActorID(),x=i!=null&&i.size?i.has(A)?i.get(A):lt:pr;if(g.canStyle(s,x)){const R=u.get(A),L=g.getCreatedAt();(!R||L.after(R))&&u.set(A,L),h.push(g)}}const v=[];for(const g of h){if(g.isRemoved())continue;const[A,x]=this.rgaTreeSplit.findIndexesFromRange(g.createPosRange());c.push({type:"style",actor:s.getActorID(),from:A,to:x,value:{attributes:Kn(r)}});for(const[R,L]of Object.entries(r)){const[$]=g.getValue().setAttr(R,L,s);$!==void 0&&v.push({parent:g.getValue(),child:$})}}return[u,v,c]}indexRangeToPosRange(t,r){const s=this.rgaTreeSplit.indexToPos(t);return t===r?[s,s]:[s,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();t.push({attributes:Kn(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Ye(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())t.push(s)}return t}}class Mr extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,r,s,i,o,a,c){return new Mr(t,r,s,i,o,a,c)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ye))throw new T(p.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:l})=>({type:"edit",from:a,to:c,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Br extends ft{constructor(t,r,s,i,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,r,s,i,o,a){return new Br(t,r,s,i,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ye))throw new T(p.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:c,value:l})=>({type:"style",from:a,to:c,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const $g=2,Ug="root",zt="text";function cr(n,e){let t=0;const r=n.children;for(let s=0;s0)throw new T(p.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===zt}get paddedSize(){return this.size+(this.isText?0:$g)}isAncestorOf(e){return zg(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=r;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new T(p.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,r._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new T(p.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new T(p.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function zg(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var me=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(me||{});function Rl(n,e,t,r){if(e>t)throw new T(p.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new T(p.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new T(p.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let s=0;for(const i of n.children){if(e-i.paddedSizei.size;(i.isText||c)&&r([i,i.isText?"Text":"Start"],l),Rl(i,Math.max(0,o),Math.min(a,i.size),r),l&&r([i,"End"],l)}s+=i.paddedSize}}function _l(n,e,t=0){for(const r of n.children)_l(r,e,t+1);e(n,t)}function $s(n,e,t=0){for(const r of n._children)$s(r,e,t+1);e(n,t)}function ki(n,e,t=!0){if(e>n.size)throw new T(p.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,s=0;for(const i of n.children){if(t&&i.isText&&i.size>=e-s)return ki(i,e-s,t);if(e===s)return{node:n,offset:r};if(!t&&i.paddedSize===e-s)return{node:n,offset:r+1};if(i.paddedSize>e-s)return ki(i,e-s-1,t);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Fl(n){return n.isText||n.children.length===0?n:Fl(n.children[0])}function qg(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new Vg(e,t,!0);const s=this.comparator(e,r.key);return s<0?r.left=this.putInternal(e,t,r.left):s>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class at{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new at(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,s;return r.isText?(r.parent.children[0]===r&&t===0?s=r.parent:s=r,r=r.parent):t===0?s=r:s=r.children[t-1],at.of(r.id,be.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return at.of(be.of(Le.fromStruct(e.parentID.createdAt),e.parentID.offset),be.of(Le.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(r);if(!s||!i)throw new T(p.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class be{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new be(e,t)}static fromStruct(e){return be.of(Le.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new T(p.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new T(p.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new qe(be.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new qe(be.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new jt);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,r));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Ei(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(Ei)};return n.attrs&&(e.attributes=Kn((t=n.attrs)==null?void 0:t.toObject())),e}function oo(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${Nt(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>oo(t)).join("")}`}function Bl(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(Bl),size:n.size,isRemoved:n.isRemoved}}class Xe extends _r{constructor(t,r){super(r);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new Kg(t),this.nodeMapByID=new Ml(be.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,r){return new Xe(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,c=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const l=c.allChildren,u=a?0:l.indexOf(o)+1;for(let h=u;h{const x=A.getCreatedAt().getActorID(),R=i?i.has(x)?i.get(x):lt:pr;if(A.canStyle(s,R)&&r){const L=v.get(x),$=A.getCreatedAt();(!L||$.after(L))&&v.set(x,$);const Y=A.setAttrs(r,s),P=Y.reduce((oe,[,Ie])=>(Ie&&(oe[Ie.getKey()]=h[Ie.getKey()]),oe),{}),H=A.parent,Q=A.prevSibling||A.parent;Object.keys(P).length>0&&u.push({type:"style",from:this.toIndex(H,Q),to:this.toIndex(A,A),fromPath:this.toPath(H,Q),toPath:this.toPath(A,A),actor:s.getActorID(),value:P});for(const[oe]of Y)oe&&g.push({parent:A,child:oe})}}),[v,g,u]}removeStyle(t,r,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[c,l]=this.findNodesAndSplitText(t[1],s),u=[],h=new Map,v=[];return this.traverseInPosRange(o,a,c,l,([g])=>{const A=g.getCreatedAt().getActorID(),x=i?i.has(A)?i.get(A):lt:pr;if(g.canStyle(s,x)&&r){const R=h.get(A),L=g.getCreatedAt();(!R||L.after(R))&&h.set(A,L),g.attrs||(g.attrs=new jt);for(const P of r){const H=g.attrs.remove(P,s);for(const Q of H)v.push({parent:g,child:Q})}const $=g.parent,Y=g.prevSibling||g.parent;u.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex($,Y),to:this.toIndex(g,g),fromPath:this.toPath($,Y),toPath:this.toPath(g,g),value:r})}}),[h,v,u]}edit(t,r,s,i,o,a){const[c,l]=this.findNodesAndSplitText(t[0],i),[u,h]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(c,l),g=this.toPath(c,l),A=[],x=[],R=[],L=new Map;this.traverseInPosRange(c,l,u,h,([P,H],Q)=>{if(H===me.Start&&!Q)for(const Qe of P.children)R.push(Qe);const oe=P.getCreatedAt().getActorID(),Ie=a?a.has(oe)?a.get(oe):lt:pr;if(P.canDelete(i,Ie)||A.includes(P.parent)){const Qe=L.get(oe),Ve=P.getCreatedAt();(!Qe||Ve.after(Qe))&&L.set(oe,Ve),(H===me.Text||H===me.Start)&&A.push(P),x.push([P,H])}});const $=this.makeDeletionChanges(x,i),Y=[];for(const P of A)P.remove(i),P.isRemoved&&Y.push({parent:this,child:P});for(const P of R)P.removedAt||c.append(P);if(s>0){let P=0,H=c,Q=l;for(;P{c.isRemoved&&(oe.remove(i),Y.push({parent:this,child:oe})),this.nodeMapByID.put(oe.id,oe)}),Q.isRemoved||P.push(Q);if(P.length){const Q=P.map(oe=>Ei(oe));$.length&&$[$.length-1].from===v?$[$.length-1].value=Q:$.push({type:"content",from:v,to:v,fromPath:g,toPath:g,actor:i.getActorID(),value:Q})}}return[$,Y,L]}editT(t,r,s,i,o){const a=this.findPos(t[0]),c=this.findPos(t[1]);this.edit([a,c],r,s,i,o)}move(t,r,s){throw new T(p.ErrUnimplemented,`not implemented: ${t}, ${r}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,s=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const s of r.getGCPairs())t.push(s)}),t}findPos(t,r=!0){const s=this.indexTree.findTreePos(t,r);return at.fromTreePos(s)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return oo(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,a=0)=>{var g,A,x,R;let c,l,u;const h=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;h&&(c=this.indexTree.indexOf(h),l=this.indexTree.treePosToPath(h),u=at.fromTreePos(h).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(g=s.removedAt)==null?void 0:g.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(x=s.insNextID)==null?void 0:x.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?Kn((R=s.attrs)==null?void 0:R.toObject()):void 0,index:c,path:l,pos:u};for(let L=0;L0&&L===s[s.length-1].to?(s[s.length-1].to=$,s[s.length-1].toPath=this.toPath(R,g)):s.push({type:"content",from:L,to:$,fromPath:this.toPath(x,h),toPath:this.toPath(R,g),actor:r.getActorID()}))}return s.reverse()}findRightToken([t,r]){if(r===me.Start){const c=t.allChildren;return c.length>0?[c[0],c[0].isText?me.Text:me.Start]:[t,me.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,me.End];const a=i[o+1];return[a,a.isText?me.Text:me.Start]}findLeftToken([t,r]){if(r===me.End){const c=t.allChildren;if(c.length>0){const l=c[c.length-1];return[l,l.isText?me.Text:me.End]}return[t,me.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,me.Start];const a=i[o-1];return[a,a.isText?me.Text:me.End]}}class Lr extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,s,i,o,a,c){return new Lr(t,r,s,i,o,a,c)}execute(t){var c;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Xe))throw new T(p.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,a]=i.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>Le.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:u,value:h,splitLevel:v,fromPath:g,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:u,value:h,splitLevel:v,fromPath:g,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${r},${s},${i.map(o=>oo(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class en{constructor(e,t,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.actor=r}static of(e,t,r,s){return new en(e,t,r,s)}next(){return new en(this.clientSeq+1,this.lamport.add(1),this.actor)}syncLamport(e){return e.greaterThan(this.lamport)?new en(this.clientSeq,e,this.actor):new en(this.clientSeq,this.lamport.add(1),this.actor)}createTimeTicket(e){return Le.of(this.lamport,e,this.actor)}setActor(e){return new en(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Hg=new en(0,q.fromInt(0,!0),Ls);class Qn{constructor({id:e,operations:t,presenceChange:r,message:s}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=s}static create({id:e,operations:t,presenceChange:r,message:s}){return new Qn({id:e,operations:t,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:c,reverseOp:l}=a;s.push(...c),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===ln.Put?t.set(this.id.getActorID(),nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:Te.bytesToHex(Te.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>Te.bytesToHex(Te.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:s,message:i}=e;return Qn.create({id:Te.bytesToChangeID(Te.hexToBytes(t)),operations:r==null?void 0:r.map(o=>Te.bytesToOperation(Te.hexToBytes(o))),presenceChange:s,message:i})}}class Us{constructor(e,t,r,s,i,o){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(e,t,r,s,i,o){return new Us(e,t,r,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class jn{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new jn(e,t)}increaseClientSeq(e){return e===0?this:new jn(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq.greaterThan(e.serverSeq)?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return jn.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq.equals(e.serverSeq)}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Gg=new jn(q.fromInt(0,!0),0);class Ot{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ot(e,t)}static fromStruct(e){return Ot.of(Le.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Ot(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Yg=Ot.of(lt,0);class ut{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new ut(e,t)}static fromStruct(e){const t=Ot.fromStruct(e.id);return ut.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ot.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class on extends Dl{constructor(t,r,s){super(r);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=s}static create(t,r){return new on(t,r)}static createComparator(){return(t,r)=>{const s=t.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let s=e;for(;s&&s!==t;)r.push(s),s=s.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new T(p.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const s=e.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,r),o=new Map,a=new Map,c=this.makeChanges(i,t);for(const l of s){const u=l.getCreatedAt().getActorID();(!o.has(u)||l.getID().getCreatedAt().after(o.get(u)))&&o.set(u,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[c,o,a]}filterNodes(e,t,r){const s=!!r,i=[],o=[],[a,c]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const u=l.getCreatedAt().getActorID(),h=s?r.has(u)?r.get(u):lt:pr;l.canDelete(t,h)?i.push(l):o.push(l)}return o.push(c),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pt=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pt||{});class je extends _r{constructor(t,r,s){super(s);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=La(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,s){return new je(t,r,s)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new T(p.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=je.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!je.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new T(p.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+La(t.getValue())).toInt(),this}}class tr extends ft{constructor(t,r,s){super(t,s);d(this,"value");this.value=r}static create(t,r,s){return new tr(t,r,s)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof je))throw new T(p.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return tr.create(this.getParentCreatedAt(),ce.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class qt extends ft{constructor(t,r,s,i,o,a,c){super(t,c);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,r,s,i,o,a){return new qt(t,r,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,s,i,o,a){return new qt(t,r,s,i,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new T(p.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Xe))throw new T(p.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([c,l])=>a[c]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:c,value:l,fromPath:u,toPath:h})=>({type:"tree-style",from:a,to:c,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:u,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Xg(n){const e=new no,t=e.data;for(const[r,s]of Object.entries(n))t[r]=JSON.stringify(s);return e}function Zg(n){if(n.type===ln.Put)return new Ii({type:xr.PUT,presence:Xg(n.presence)});if(n.type===ln.Clear)return new Ii({type:xr.CLEAR});throw new T(p.ErrUnimplemented,"unimplemented type")}function Qg(n){return new El({serverSeq:n.getServerSeqAsString(),clientSeq:n.getClientSeq()})}function Ll(n){return new Ms({clientSeq:n.getClientSeq(),lamport:n.getLamportAsString(),actorId:go(n.getActorID())})}function F(n){if(n)return new B({lamport:n.getLamportAsString(),delimiter:n.getDelimiter(),actorId:go(n.getActorID())})}function $l(n){switch(n){case ve.Null:return V.NULL;case ve.Boolean:return V.BOOLEAN;case ve.Integer:return V.INTEGER;case ve.Long:return V.LONG;case ve.Double:return V.DOUBLE;case ve.String:return V.STRING;case ve.Bytes:return V.BYTES;case ve.Date:return V.DATE;default:throw new T(p.ErrInvalidType,`unsupported type: ${n}`)}}function Ul(n){switch(n){case Pt.IntegerCnt:return V.INTEGER_CNT;case Pt.LongCnt:return V.LONG_CNT;default:throw new T(p.ErrInvalidType,`unsupported type: ${n}`)}}function ri(n){if(n instanceof $e)return new Bt({type:V.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ql(n)});if(n instanceof Ke)return new Bt({type:V.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:Nm(n)});if(n instanceof Ye)return new Bt({type:V.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ce)return new Bt({type:$l(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof je)return new Bt({type:Ul(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Xe)return new Bt({type:V.TREE,createdAt:F(n.getCreatedAt()),value:Om(n)});throw new T(p.ErrUnimplemented,"unimplemented element")}function em(n){return new Ai({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Xr(n){return new xn({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function Zr(n){return new Er({parentId:yr(n.getParentID()),leftSiblingId:yr(n.getLeftSiblingID())})}function yr(n){return new qn({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Jl(n){const e=new Qi;if(n instanceof Nn){const t=n,r=new cl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Fr){const t=n,r=new ll;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof tn){const t=n,r=new ul;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof un){const t=n,r=new fl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Mr){const t=n,r=new hl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Xr(t.getFromPos()),r.to=Xr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);r.content=t.getContent();const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Br){const t=n,r=new dl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Xr(t.getFromPos()),r.to=Xr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof tr){const t=n,r=new gl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=ri(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Lr){const t=n,r=new ml,s=r.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zr(t.getFromPos()),r.to=Zr(t.getToPos()),r.contents=am(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof qt){const t=n,r=new pl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zr(t.getFromPos()),r.to=Zr(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=F(a);const i=t.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[a,c]of t.getAttributes())o[a]=c}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new T(p.ErrUnimplemented,"unimplemented operation");return e}function tm(n){const e=[];for(const t of n)e.push(Jl(t));return e}function nm(n){const e=new al({id:Ll(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=tm(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=Zg(n.getPresenceChange())),e}function rm(n){const e=[];for(const t of n)e.push(nm(t));return e}function sm(n){const e=[];for(const t of n)e.push(new Il({key:t.getStrKey(),element:co(t.getValue())}));return e}function im(n){const e=[];for(const t of n)e.push(new eo({element:co(t.getValue())}));return e}function om(n){const e=[];for(const t of n){const r=new Sl;r.id=em(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const s=r.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new Bs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),s[o.getKey()]=a}e.push(r)}return e}function am(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new kl({content:ao(t)}));return e}function cm(n){const e={};for(const t of n)e[t.getKey()]=new Bs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ao(n){if(!n)return[];const e=[];return $s(n,(t,r)=>{const s=new to({id:yr(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=yr(t.insPrevID)),t.insNextID&&(s.insNextId=yr(t.insNextID)),t.attrs&&(s.attributes=cm(t.attrs)),e.push(s)}),e}function lm(n){const e=new Ze;return e.body.case="jsonObject",e.body.value=new yl({nodes:sm(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function zl(n){const e=new Ze;return e.body.case="jsonArray",e.body.value=new vl({nodes:im(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function um(n){const e=new Ze;return e.body.case="primitive",e.body.value=new Tl({type:$l(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function fm(n){const e=new Ze;return e.body.case="text",e.body.value=new wl({nodes:om(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hm(n){const e=new Ze;return e.body.case="counter",e.body.value=new bl({type:Ul(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function ql(n){const e=new Ze;return e.body.case="tree",e.body.value=new Al({nodes:ao(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function co(n){if(n instanceof $e)return lm(n);if(n instanceof Ke)return zl(n);if(n instanceof ce)return um(n);if(n instanceof Ye)return fm(n);if(n instanceof je)return hm(n);if(n instanceof Xe)return ql(n);throw new T(p.ErrUnimplemented,"unimplemented element")}function dm(n){return new Wt({documentKey:n.getDocumentKey(),checkpoint:Qg(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:rm(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:F(n.getMinSyncedTicket())})}function $a(n){const e=n.findDetails(Pg);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Kl(n){let e;return n.serverSeq&&(e=q.fromString(n.serverSeq,!0)),en.of(n.clientSeq,q.fromString(n.lamport,!0),ho(n.actorId),e)}function M(n){if(n)return Le.of(q.fromString(n.lamport,!0),n.delimiter,ho(n.actorId))}function lo(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function gm(n){const e=n.type;if(e===xr.PUT){const t=lo(n.presence);return{type:ln.Put,presence:t}}if(e===xr.CLEAR)return{type:ln.Clear};throw new T(p.ErrInvalidType,`unsupported type: ${e}`)}function mm(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,lo(r))}),e}function jl(n){switch(n){case V.NULL:return ve.Null;case V.BOOLEAN:return ve.Boolean;case V.INTEGER:return ve.Integer;case V.LONG:return ve.Long;case V.DOUBLE:return ve.Double;case V.STRING:return ve.String;case V.BYTES:return ve.Bytes;case V.DATE:return ve.Date}throw new T(p.ErrUnimplemented,`unimplemented value type: ${n}`)}function Is(n){switch(n){case V.INTEGER_CNT:return Pt.IntegerCnt;case V.LONG_CNT:return Pt.LongCnt}throw new T(p.ErrUnimplemented,`unimplemented value type: ${n}`)}function si(n){switch(n.type){case V.JSON_OBJECT:return n.value?Zl(n.value):$e.create(M(n.createdAt));case V.JSON_ARRAY:return n.value?xm(n.value):Ke.create(M(n.createdAt));case V.TEXT:return Ye.create(er.create(),M(n.createdAt));case V.TREE:return Cm(n.value);case V.NULL:case V.BOOLEAN:case V.INTEGER:case V.LONG:case V.DOUBLE:case V.STRING:case V.BYTES:case V.DATE:return ce.of(ce.valueFromBytes(jl(n.type),n.value),M(n.createdAt));case V.INTEGER_CNT:case V.LONG_CNT:return je.create(Is(n.type),je.valueFromBytes(Is(n.type),n.value),M(n.createdAt))}}function Qr(n){return ut.of(Ot.of(M(n.createdAt),n.offset),n.relativeOffset)}function Vl(n){return Ot.of(M(n.createdAt),n.offset)}function pm(n){const e=Pr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{e.setAttr(r,s.value,M(s.updatedAt))});const t=on.create(Vl(n.id),e);return t.remove(M(n.removedAt)),t}function _n(n){return at.of(vr(n.parentId),vr(n.leftSiblingId))}function vr(n){return be.of(M(n.createdAt),n.offset)}function ym(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=uo(t.content);e.push(r)}),e}function uo(n){if(n.length===0)return;const e=[];for(const s of n)e.push(Tm(s));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(e[s]),r.set(n[s].depth,e[s]);return t.updateDescendantsSize(),Xe.create(t,lt).getRoot()}function vm(n){const e=jt.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function Tm(n){const e=vr(n.id),t=qe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=vm(n.attributes)),n.insPrevId&&(t.insPrevID=vr(n.insPrevId)),n.insNextId&&(t.insNextID=vr(n.insNextId)),t.removedAt=M(n.removedAt),t}function Wl(n){if(n.body.case==="set"){const e=n.body.value;return Nn.create(e.key,si(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Fr.create(M(e.parentCreatedAt),M(e.prevCreatedAt),si(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return tn.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return un.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const r=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{r.set(s,i)}),Mr.create(M(e.parentCreatedAt),Qr(e.from),Qr(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const r=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{r.set(s,i)}),Br.create(M(e.parentCreatedAt),Qr(e.from),Qr(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return tr.create(M(e.parentCreatedAt),si(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,M(s))}),Lr.create(M(e.parentCreatedAt),_n(e.from),_n(e.to),ym(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,M(o))}),(r==null?void 0:r.length)>0?qt.createTreeRemoveStyleOperation(M(e.parentCreatedAt),_n(e.from),_n(e.to),s,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),qt.create(M(e.parentCreatedAt),_n(e.from),_n(e.to),s,t,M(e.executedAt)))}else throw new T(p.ErrUnimplemented,"unimplemented operation")}}function wm(n){const e=[];for(const t of n){const r=Wl(t);r&&e.push(r)}return e}function Hl(n){const e=[];for(const t of n)e.push(Qn.create({id:Kl(t.id),operations:wm(t.operations),presenceChange:t.presenceChange?gm(t.presenceChange):void 0,message:t.message}));return e}function bm(n){return jn.of(q.fromString(n.serverSeq,!0),n.clientSeq)}function Am(n){return Us.create(n.documentKey,bm(n.checkpoint),n.isRemoved,Hl(n.changes),n.snapshot,M(n.minSyncedTicket))}function Gl(n){const e=new Nr;for(const r of n.nodes){const s=fo(r.element);e.set(r.key,s,s.getPositionedAt())}const t=new $e(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Yl(n){const e=new Or;for(const r of n.nodes)e.insert(fo(r.element));const t=new Ke(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Im(n){const e=ce.of(ce.valueFromBytes(jl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Sm(n){const e=new er;let t=e.getHead();for(const s of n.nodes){const i=e.insertAfter(t,pm(s));s.insPrevId&&i.setInsPrev(e.findNode(Vl(s.insPrevId))),t=i}const r=new Ye(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function km(n){const e=je.create(Is(n.type),je.valueFromBytes(Is(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Xl(n){const e=uo(n.nodes);return Xe.create(e,M(n.createdAt))}function fo(n){if(n.body.case==="jsonObject")return Gl(n.body.value);if(n.body.case==="jsonArray")return Yl(n.body.value);if(n.body.case==="primitive")return Im(n.body.value);if(n.body.case==="text")return Sm(n.body.value);if(n.body.case==="counter")return km(n.body.value);if(n.body.case==="tree")return Xl(n.body.value);throw new T(p.ErrUnimplemented,"unimplemented element")}function Em(n){if(!n)return{root:$e.create(lt),presences:new Map};const e=ag.fromBinary(n);return{root:fo(e.root),presences:mm(e.presences)}}function Zl(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Gl(e.body.value)}function Ql(n){return co(n).toBinary()}function xm(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Yl(e.body.value)}function Nm(n){return zl(n).toBinary()}function Cm(n){if(!n)throw new T(p.ErrInvalidArgument,"bytes is empty");const e=Ze.fromBinary(n);return Xl(e.body.value)}function Om(n){return ql(n).toBinary()}function eu(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ho(n){return eu(n)}function tu(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function go(n){return tu(n)}function Pm(n){const e=Ms.fromBinary(n);return Kl(e)}function Dm(n){const e=Qi.fromBinary(n);return Wl(e)}const Te={fromPresence:lo,toChangePack:dm,fromChangePack:Am,fromChanges:Hl,toTreeNodes:ao,fromTreeNodes:uo,objectToBytes:Ql,bytesToObject:Zl,bytesToSnapshot:Em,bytesToHex:eu,hexToBytes:tu,toHexString:ho,toUint8Array:go,toOperation:Jl,toChangeID:Ll,PbChangeID:Ms,bytesToChangeID:Pm,bytesToOperation:Dm};var De=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(De||{});let pn=3;function nu(n){pn=n}const z={trivial:(...n)=>{pn>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{pn>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{pn>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{pn>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{pn>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>pn<=n};function ru(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class Rm{constructor(e,t,r,s,i){d(this,"reconnectStreamDelay");d(this,"doc");d(this,"docID");d(this,"syncMode");d(this,"remoteChangeEventReceived");d(this,"watchStream");d(this,"watchLoopTimerID");d(this,"watchAbortController");d(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===ds.RealtimeSyncOff?!1:this.syncMode===ds.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==ds.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const ii=()=>{};class _m{constructor(e){d(this,"finalized",!1);d(this,"observers",[]);d(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let s;if(!e)throw new T(p.ErrInvalidArgument,"missing observer");if(this.finalized)throw new T(p.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:r},s.next===void 0&&(s.next=ii),s.error===void 0&&(s.error=ii),s.complete===void 0&&(s.complete=ii);const i=ru(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Ln{constructor(e,t,r,s){d(this,"id");d(this,"delimiter");d(this,"message");d(this,"root");d(this,"operations");d(this,"presenceChange");d(this,"previousPresence");d(this,"reversePresenceKeys");this.id=e,this.delimiter=so,this.root=t,this.operations=[],this.previousPresence=nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,r,s){return new Ln(e,t,r,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return Qn.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Dr{constructor(e){d(this,"rootObject");d(this,"elementPairMapByCreatedAt");d(this,"gcElementSetByCreatedAt");d(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Ye||t instanceof Xe)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Dr($e.create(lt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new T(p.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof sn&&e.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(e){let t=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return r(e),e instanceof sn&&e.getDescendants(s=>(r(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof sn&&r.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Dr(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r);s.element.getRemovedAt()&&e.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s!==void 0&&e.compare(s)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function su(n,e){const t=new Rr(n);return new Proxy(e,t.getHandlers())}class Rr{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,r,s)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]=${JSON.stringify(s)}`),Rr.setInternal(e,t,r,s),!0),get:(t,r)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():yn(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(z.isEnabled(De.Trivial)&&z.trivial(`obj[${r}]`),Rr.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,s){if(r.includes("."))throw new T(p.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=Ss(e,s,i),a=t.set(r,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nn.create(r,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const r={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new T(p.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=Ss(e,i,o);r[s]=a}return r}static deleteInternal(e,t,r){const s=e.issueTimeTicket(),i=t.deleteByKey(r,s);i&&(e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function Mm(n,e){const t=new fe(n,e);return new Proxy(e,t.getHandlers())}function Bm(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Lm(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class fe{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Xt(e,a)}:s==="getElementByIndex"?o=>{const a=r.get(o);return Xt(e,a)}:s==="getLast"?()=>Xt(e,r.getLast()):s==="deleteByID"?o=>{const a=fe.deleteInternalByID(e,r,o);return Xt(e,a)}:s==="insertAfter"?(o,a)=>{const c=fe.insertAfterInternal(e,r,o,a);return Xt(e,c)}:s==="insertBefore"?(o,a)=>{const c=fe.insertBeforeInternal(e,r,o,a);return Xt(e,c)}:s==="moveBefore"?(o,a)=>{fe.moveBeforeInternal(e,r,o,a)}:s==="moveAfter"?(o,a)=>{fe.moveAfterInternal(e,r,o,a)}:s==="moveFront"?o=>{fe.moveFrontInternal(e,r,o)}:s==="moveLast"?o=>{fe.moveLastInternal(e,r,o)}:Bm(s)?yn(e,r.get(Number(s))):s==="push"?o=>fe.pushInternal(e,r,o):s==="splice"?(o,a,...c)=>fe.splice(e,r,o,a,...c):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?fe.iteratorInternal.bind(this,e,r):s==="includes"?(o,a)=>fe.includes(e,r,o,a):s==="indexOf"?(o,a)=>fe.indexOf(e,r,o,a):s==="lastIndexOf"?(o,a)=>fe.lastIndexOf(e,r,o,a):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>fe.toTestString(r):typeof s=="string"&&Lm(s)?(...o)=>{const a=Array.from(r).map(c=>yn(e,c));return Array.prototype[s].apply(a,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(z.isEnabled(De.Trivial)&&z.trivial(`array[${s}]`),fe.deleteInternalByIndex(e,r,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Xt(e,r)}static buildArrayElements(e,t){const r=[];for(const s of t){const i=e.issueTimeTicket(),o=Ss(e,s,i);r.push(o)}return r}static pushInternal(e,t,r){return fe.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,s,i),e.push(tn.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,r,s){const i=e.issueTimeTicket();t.moveAfter(r,s,i),e.push(tn.create(t.getCreatedAt(),r,s,i))}static moveFrontInternal(e,t,r){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,s),e.push(tn.create(t.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(e,t,r){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,s),e.push(tn.create(t.getCreatedAt(),i,r,s))}static insertAfterInternal(e,t,r,s){const i=e.issueTimeTicket(),o=Ss(e,s,i);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Fr.create(t.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,r,s){return fe.insertAfterInternal(e,t,t.getPrevCreatedAt(r),s)}static deleteInternalByIndex(e,t,r){const s=e.issueTimeTicket(),i=t.deleteByIndex(r,s);if(i)return e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){const s=e.issueTimeTicket(),i=t.delete(r,s);return e.push(un.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,r,s,...i){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),c=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let u=a;u=i)return!1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).includes(r,o);for(let c=o;c=i)return-1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).indexOf(r,o);for(let c=o;c=i?i-1:s<0?s+i:s;if(o<0)return-1;if(ce.isSupport(r))return Array.from(t).map(l=>yn(e,l)).lastIndexOf(r,o);for(let c=o;c>0;c--)if(((a=t.get(c))==null?void 0:a.getID())===r.getID())return c;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Js{constructor(e,t){d(this,"context");d(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,s){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);z.isEnabled(De.Debug)&&z.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${r}`);const o=s?Zn(s):void 0,a=this.context.issueTimeTicket(),[c,,l,u]=this.text.edit(i,r,a,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Mr(this.text.getCreatedAt(),i[0],i[1],c,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(u)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);z.isEnabled(De.Debug)&&z.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Zn(r),o=this.context.issueTimeTicket(),[a,c]=this.text.setStyle(s,i,o);for(const l of c)this.context.registerGCPair(l);return this.context.push(new Br(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([ut.fromStruct(e[0]),ut.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new T(p.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class zs{constructor(e,t){d(this,"valueType");d(this,"value");d(this,"context");d(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new T(p.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ce.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(tr.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new T(p.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function mo(n,e,t){const{type:r}=n,s=t.issueTimeTicket();if(r===zt){iu(n);const{value:i}=n,o=qe.create(be.of(s,0),r,i);e.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Pl(o)){const l=Zn(o);a=new jt;for(const[u,h]of Object.entries(l))a.set(u,h,s)}const c=qe.create(be.of(s,0),r,void 0,a);e.append(c);for(const l of i)mo(l,c,t)}}function $m(n,e){const{type:t}=e,r=n.issueTimeTicket();let s;if(e.type===zt){const{value:i}=e;s=qe.create(be.of(r,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Pl(o)){const c=Zn(o);a=new jt;for(const[l,u]of Object.entries(c))a.set(l,u,r)}s=qe.create(be.of(n.issueTimeTicket(),0),t,void 0,a);for(const c of i)mo(c,s,n)}return s}function iu(n){if(!n.value.length)throw new T(p.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ua(n){if(!n.length)return!0;if(n[0].type===zt)for(const t of n){const{type:r}=t;if(r!==zt)throw new T(p.ErrInvalidArgument,"element node and text node cannot be passed together");iu(t)}else for(const t of n){const{type:r}=t;if(r===zt)throw new T(p.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class qs{constructor(e){d(this,"initialRoot");d(this,"context");d(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return qe.create(be.of(e.issueTimeTicket(),0),Ug);const t=qe.create(be.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)mo(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?Zn(t):void 0,[a]=this.tree.style([r,s],o,i);this.context.push(qt.create(this.tree.getCreatedAt(),r,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?Zn(r):void 0,[c,l]=this.tree.style([s,i],a,o);for(const u of l)this.context.registerGCPair(u);this.context.push(qt.create(this.tree.getCreatedAt(),s,i,c,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,c]=this.tree.removeStyle([s,i],r,o);for(const l of c)this.context.registerGCPair(l);this.context.push(qt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,r,o))}editInternal(e,t,r,s=0){var l;if(r.length!==0&&r[0]&&(Ua(r),r[0].type!==zt))for(const u of r){const{children:h=[]}=u;Ua(h)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=r[0])==null?void 0:l.type)===zt){let u="";for(const h of r){const{value:v}=h;u+=v}o.push(qe.create(be.of(this.context.issueTimeTicket(),0),zt,u))}else o=r.map(u=>u&&$m(this.context,u)).filter(u=>u);const[,a,c]=this.tree.edit([e,t],o.length?o.map(u=>u==null?void 0:u.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const u of a)this.context.registerGCPair(u);return this.context.push(Lr.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,c,i)),!0}editByPath(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new T(p.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new T(p.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new T(p.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,r,s)}edit(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,r?[r]:[],s)}editBulk(e,t,r,s=0){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new T(p.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[at.fromStruct(e[0]),at.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new T(p.ErrNotInitialized,"Tree is not initialized yet");const t=[at.fromStruct(e[0]),at.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Ja(n,e){return su(n,e)}function Xt(n,e){if(e){if(e instanceof ce)return e;if(e instanceof $e)return su(n,e);if(e instanceof Ke)return Mm(n,e);if(e instanceof Ye)return new Js(n,e);if(e instanceof je){const t=new zs(Pt.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Xe){const t=new qs;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function yn(n,e){const t=Xt(n,e);return t instanceof ce?t.getValue():t}function Ss(n,e,t){let r;if(ce.isSupport(e))r=ce.of(e,t);else if(Array.isArray(e))r=Ke.create(t,fe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Js?(r=Ye.create(er.create(),t),e.initialize(n,r)):e instanceof zs?(r=je.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof qs?(r=Xe.create(e.buildRoot(n),t),e.initialize(n,r)):r=$e.create(t,Rr.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const za=50;class Um{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=za&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=za&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Jm="yorkie-devtools-panel",zm="yorkie-devtools-sdk";let Mn="disconnected";const qa=new Map,hs=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=hs);function es(n,e){(e!=null&&e.force||Mn!=="disconnected")&&window.postMessage({source:zm,...n},"*")}function qm(n){if(!n.isEnableDevtools()||typeof window>"u"||qa.has(n.getKey()))return;hs.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Me.StatusChanged&&r.type!==Me.Snapshot&&r.type!==Me.LocalChange&&r.type!==Me.RemoteChange&&r.type!==Me.Initialized&&r.type!==Me.Watched&&r.type!==Me.Unwatched&&r.type!==Me.PresenceChanged)||(hs.get(n.getKey()).push(t),Mn==="synced"&&es({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});qa.set(n.getKey(),[e]),es({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==Jm)return;switch(t.data.msg){case"devtools::connect":if(Mn!=="disconnected")break;Mn="connected",es({msg:"doc::available",docKey:n.getKey()}),z.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Mn="disconnected",z.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Mn="synced",es({msg:"doc::sync::full",docKey:n.getKey(),events:hs.get(n.getKey())}),z.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Zt=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Zt||{}),Me=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(Me||{}),xi=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(xi||{}),Ni=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Ni||{});class ou{constructor(e,t){d(this,"key");d(this,"status");d(this,"opts");d(this,"changeID");d(this,"checkpoint");d(this,"localChanges");d(this,"root");d(this,"clone");d(this,"eventStream");d(this,"eventStreamObserver");d(this,"onlineClients");d(this,"presences");d(this,"history");d(this,"internalHistory");d(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Dr.create(),this.changeID=Hg,this.checkpoint=Gg,this.localChanges=[],this.eventStream=Fm(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Um,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},qm(this)}update(e,t){if(this.getStatus()==="removed")throw new T(p.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const i=Ja(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(i,new ni(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){z.isEnabled(De.Trivial)&&z.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,re.Local),c=s.getReversePresence();c&&a.push({type:"presence",value:c}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const l=[];o.length>0&&l.push({type:"local-change",source:re.Local,value:{message:i.getMessage()||"",operations:o,actor:r,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:re.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(l),z.isEnabled(De.Trivial)&&z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,s){if(typeof e=="string"){if(typeof t!="function")throw new T(p.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="initialized"&&l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||a(l)},r,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="initialized"&&l.type!=="presence-changed"||l.type==="presence-changed"&&l.value.clientID!==this.changeID.getActorID()||a(l)},r,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||l.value.clientID!==this.changeID.getActorID()&&a(l)},r,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="connection-changed"&&a(l)},r,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="status-changed"&&a(l)},r,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="sync-status-changed"&&a(l)},r,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="local-broadcast"&&a(l)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(c=>{for(const l of c)l.type==="broadcast"&&a(l)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const c of a){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const l=[];for(const u of c.value.operations)this.isSameElementOrChildOf(u.path,i)&&l.push(u);l.length&&o({...c,value:{...c.value,operations:l}})}},r,s)}if(typeof e=="function"){const i=e,o=t,a=r;return this.eventStream.subscribe(c=>{for(const l of c)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new T(p.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((i,o)=>i===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),re.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,re.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),z.isEnabled(De.Trivial)&&z.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:nt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Us.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ja(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:r,presences:s}=Te.bytesToSnapshot(t);this.root=new Dr(r),this.presences=s,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:re.Remote,value:{snapshot:this.isEnableDevtools()?Te.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){z.isEnabled(De.Debug)&&z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),z.isEnabled(De.Trivial)&&z.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of e)this.applyChange(r,t);z.isEnabled(De.Debug)&&z.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case ln.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:re.Remote,value:{clientID:s,presence:o.presence}});break;case ln.Clear:r.push({type:"unwatched",source:re.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===re.Remote?{type:"remote-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const s of t)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:re.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,s=[];if(t===mr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:re.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===mr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:re.Remote,value:{clientID:r,presence:i}})}else if(t===mr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:i,payload:o}=e.body.value.body,a=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(a.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Ls),this.publish([{source:e==="removed"?re.Remote:re.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r}=e.value;if(!t)return;this.applySnapshot(q.fromString(r),Te.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=Qn.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:s}of e.value)t.add(r),this.presences.set(r,s);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new T(p.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const s of t)if(r=r[s],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?nt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?nt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?nt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:nt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:nt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new T(p.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new T(p.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof ft)){new ni(t,nt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const u=t.issueTimeTicket();l.setExecutedAt(u),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,re.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,re.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),c=[];s.length>0&&c.push({type:"local-change",source:re.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&c.push({type:"presence-changed",source:re.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(c)}redo(){if(this.isUpdating)throw new T(p.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new T(p.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Ln.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof ft)){new ni(t,nt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const u=t.issueTimeTicket();l.setExecutedAt(u),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,re.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,re.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),c=[];s.length>0&&c.push({type:"local-change",source:re.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&c.push({type:"presence-changed",source:re.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const s={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([s])}}function Km(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const jm="yorkie-js-sdk",Vm="0.5.0",Wm="Yorkie JS SDK",Hm="./src/yorkie.ts",Gm={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Ym=["dist"],Xm={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},Zm={node:">=18.0.0",npm:">=7.1.0"},Qm={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ep={name:"hackerwins",email:"susukang98@gmail.com"},tp="Apache-2.0",np={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},rp="https://github.com/yorkie-team/yorkie-js-sdk#readme",sp={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ip={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ka={name:jm,version:Vm,description:Wm,main:Hm,publishConfig:Gm,files:Ym,scripts:Xm,engines:Zm,repository:Qm,author:ep,license:tp,bugs:np,homepage:rp,devDependencies:sp,dependencies:ip};function op(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Ka.name+"/"+Ka.version),await n(e))}const ap=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var ds=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(ds||{});const ts={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},oi={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class au{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ts,this.key=t.key?t.key:ru(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ts.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ts.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ts.retrySyncLoopDelay,this.rpcClient=Ld(Cg,og({baseUrl:e,interceptors:[Km(t.apiKey,t.token),op()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),z.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw z.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),z.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw z.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Zt.Detached)throw new T(p.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((i,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async i=>{var u;const{topic:o,payload:a}=i.value,c=(u=i.options)==null?void 0:u.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(h){h instanceof Error&&(c==null||c(h))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:Te.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=Te.fromChangePack(i.changePack);return e.applyChangePack(o),e.getStatus()===Zt.Removed||(e.applyStatus(Zt.Attached),this.attachmentMap.set(e.getKey(),new Rm(this.reconnectStreamDelay,e,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(e.getKey()),z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(i=>{throw z.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(p.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:Te.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=Te.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==Zt.Removed&&e.applyStatus(Zt.Detached),this.detachInternal(e.getKey()),z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw z.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new T(p.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const s=r.syncMode;return s===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new T(p.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new T(p.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=Te.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=Te.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw z.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,s){if(!this.isActive())throw new T(p.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new T(p.ErrDocumentNotAttached,`${e} is not attached`);if(!ap(r))throw new T(p.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??oi.maxRetries,a=oi.maxBackoff;let c=0;const l=h=>Math.min(oi.initialRetryInterval*2**h,a),u=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(z.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(cu(),l(c-1)),z.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${o}`);else throw z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return u()}runSyncLoop(){const e=()=>{if(!this.isActive()){z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{z.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};z.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new T(p.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new T(p.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:s.signal});return t.doc.publish([{type:Me.ConnectionChanged,value:xi.Connected}]),z.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const l of i)this.handleWatchDocumentsResponse(t,l),l.body.case==="initialization"&&o([i,s])}catch(l){t.doc.resetOnlineClients(),t.doc.publish([{type:Me.Initialized,source:re.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Me.ConnectionChanged,value:xi.Disconnected}]),z.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?r():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===mr.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Zt.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:s}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:Te.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=Te.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Me.SyncStatusChanged,value:Ni.Synced}]),r.getStatus()===Zt.Removed&&this.detachInternal(r.getKey());const c=r.getKey(),l=a.getChangeSize();return z.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:Me.SyncStatusChanged,value:Ni.SyncFailed}]),z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===ee.Canceled||e.code===ee.Unknown||e.code===ee.ResourceExhausted||e.code===ee.Unavailable?!0:(($a(e)===p.ErrClientNotActivated||$a(e)===p.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{z.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const cu={Client:au,Document:ou,Primitive:ce,Text:Js,Counter:zs,Tree:qs,LogLevel:De,setLogLevel:nu,IntType:Pt.IntegerCnt,LongType:Pt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:au,Document:ou,Primitive:ce,Text:Js,Counter:zs,Tree:qs,LogLevel:De,setLogLevel:nu,IntType:Pt.IntegerCnt,LongType:Pt.LongCnt});const cp=(n,e)=>{const t=n.__vccOpts||n;for(const[r,s]of e)t[r]=s;return t},lp=[{title:"Todo",cards:[{title:"Pruning document"},{title:"Clean up codes"}]},{title:"Doing",cards:[{title:"Array operations"}]},{title:"Done",cards:[{title:"Create a sample page"},{title:"Launch demo site"}]}],Yt=new cu.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Ft=new cu.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),up={data(){return{lists:[],title:"",opened:null}},created(){this.fetchDoc()},beforeUnmount(){this.disconnect()},watch:{opened(n){this.$nextTick(function(){n===0?this.$refs.addListForm.querySelector("input").focus():n&&this.$refs.addCardForm[n-1].querySelector("input").focus(),this.title=""})}},methods:{async fetchDoc(){await Yt.activate(),await Yt.attach(Ft),Ft.update(n=>{n.lists||(n.lists=lp)},"create default list if not exists"),Ft.subscribe(n=>{this.lists=Ft.getRoot().lists}),await Yt.sync(),this.lists=Ft.getRoot().lists},async disconnect(){await Yt.deactivate()},isOpened(n){return this.opened===n},openForm(n){this.opened=n},closeForm(){this.opened=null},addCard(n){this.title!==""&&Ft.update(e=>{e.lists.getElementByID(n.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${Yt.getID()}`)},deleteCard(n,e){Ft.update(t=>{t.lists.getElementByID(n.getID()).cards.deleteByID(e.getID())},`delete a card by ${Yt.getID()}`)},addList(){this.title!==""&&Ft.update(n=>{n.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${Yt.getID()}`)},deleteList(n){Ft.update(e=>{e.lists.deleteByID(n.getID())},`delete a list by ${Yt.getID()}`)}}},fp={class:"list"},hp=["onClick"],dp={class:"title"},gp={class:"card"},mp=["onClick"],pp={key:0,class:"add-form"},yp=["onKeyup"],vp={class:"buttons"},Tp=["onClick"],wp=["onClick"],bp={class:"add-list",ref:"addListForm"},Ap={key:0,class:"add-form"},Ip={class:"buttons"};function Sp(n,e,t,r,s,i){return Rt(),_t(We,null,[(Rt(!0),_t(We,null,Mo(s.lists,(o,a)=>(Rt(),_t("div",fp,[Oe("span",{class:"delete",onClick:c=>i.deleteList(o)},"❌",8,hp),Oe("div",dp,ko(o.title),1),(Rt(!0),_t(We,null,Mo(o.cards,c=>(Rt(),_t("div",gp,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,c)},"❌",8,mp),Dc(" "+ko(c.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Rt(),_t("div",pp,[Fo(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=c=>s.title=c),onKeyup:[Gr(c=>i.addCard(o),["enter"]),e[1]||(e[1]=Gr(c=>i.closeForm(),["esc"]))]},null,40,yp),[[ra,s.title]]),Oe("div",vp,[Oe("input",{type:"button",value:"Add",onClick:c=>i.addCard(o)},null,8,Tp),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=c=>i.closeForm())})])])):(Rt(),_t("div",{key:1,class:"add-card-opener",onClick:c=>i.openForm(a+1)}," Add another card ",8,wp))],512)]))),256)),Oe("div",bp,[i.isOpened(0)?(Rt(),_t("div",Ap,[Fo(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=Gr(o=>i.addList(),["enter"])),e[5]||(e[5]=Gr(o=>i.closeForm(),["esc"]))]},null,544),[[ra,s.title]]),Oe("div",Ip,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Rt(),_t("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const kp=cp(up,[["render",Sp]]);Lh(kp).mount("#app"); diff --git a/examples/vuejs-kanban/index.html b/examples/vuejs-kanban/index.html index b5f5f5c56..dd0907b3c 100644 --- a/examples/vuejs-kanban/index.html +++ b/examples/vuejs-kanban/index.html @@ -6,7 +6,7 @@ Vite App - +