diff --git a/api-reference/classes/Change.html b/api-reference/classes/Change.html index 78ed1c5b4..ceacae42c 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 1370b47e6..1058633a9 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>>
authTokenInjector?: ((reason?) => Promise<string>)

Type declaration

    • (reason?): Promise<string>
    • Parameters

      • Optional reason: string

      Returns Promise<string>

conditions: Record<ClientCondition, boolean>
id?: string
keepalive: boolean = false
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>>
authTokenInjector?: ((reason?) => Promise<string>)

Type declaration

    • (reason?): Promise<string>
    • Parameters

      • Optional reason: string

      Returns Promise<string>

conditions: Record<ClientCondition, boolean>
id?: string
keepalive: boolean = false
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

      @@ -49,39 +49,39 @@
      • 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"
setAuthToken: ((token) => void)

Type declaration

    • (token): void
    • Parameters

      • token: string

      Returns void

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"
  • setAuthToken: ((token) => void)

    Type declaration

      • (token): void
      • Parameters

        • token: string

        Returns void

    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;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • 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.

      +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • 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.

      Parameters

      • options: {
            keepalive: boolean;
        } = ...

        If keepalive is true, the client will request deactivation immediately using fetch with the keepalive option enabled. This is useful for ensuring the deactivation request completes even if the page is being unloaded, such as in beforeunload or unload event listeners.

        -
        • keepalive: boolean

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the +

      • keepalive: boolean

    Returns Promise<void>

    \ 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 ce11f65a4..b6f128c4a 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 253574cda..1bf5b2e51 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
    status: DocStatus

    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
    status: DocStatus

    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: bigint
      • snapshotVector: VersionVector
      • Optional snapshot: Uint8Array
      • clientSeq: number = -1

      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

    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 63263f1e5..4f06d300d 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 3b86cc5d9..4ff652844 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 f74a9cbb2..aa7f7807e 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: bigint

    Methods

    • compare returns an integer comparing two Ticket. +

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: bigint

    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 82730af31..26614ddbc 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/classes/VersionVector.html b/api-reference/classes/VersionVector.html index 0f828f911..8914f3abc 100644 --- a/api-reference/classes/VersionVector.html +++ b/api-reference/classes/VersionVector.html @@ -2,7 +2,7 @@ between changes whether they are causally related or concurrent. It is similar to vector clocks, but it is synced with lamport timestamp of the change.

    -

    Constructors

    Constructors

    Properties

    Methods

    [iterator] afterOrEqual @@ -14,13 +14,13 @@ set size unset -

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    • get gets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string

      Returns undefined | bigint

    • set sets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string
      • lamport: bigint

      Returns void

    • unset removes the version for the given actor from the VersionVector.

      -

      Parameters

      • actorID: string

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    \ No newline at end of file diff --git a/api-reference/enums/ClientCondition.html b/api-reference/enums/ClientCondition.html index 208b7ccaa..4a8c56134 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 1c08be1cd..e2fb483db 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 d5e03ac99..be87641a3 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

    AuthError: "auth-error"

    AuthError indicates an authorization failure in syncLoop or watchLoop.

    -
    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, +

    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, enabling real-time synchronization.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocStatus.html b/api-reference/enums/DocStatus.html index 44c61094d..9310146c2 100644 --- a/api-reference/enums/DocStatus.html +++ b/api-reference/enums/DocStatus.html @@ -1,11 +1,11 @@ DocStatus | yorkie-js-sdk

    Enumeration DocStatus

    DocStatus 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/DocSyncStatus.html b/api-reference/enums/DocSyncStatus.html index 86b0f02bc..e841ebcab 100644 --- a/api-reference/enums/DocSyncStatus.html +++ b/api-reference/enums/DocSyncStatus.html @@ -1,6 +1,6 @@ DocSyncStatus | yorkie-js-sdk

    Enumeration DocSyncStatus

    DocSyncStatus 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 10d4408d2..6484c8fad 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 385faf1b1..283f65b0c 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 a94dd4b51..dcb1b3ff6 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 4843f73f9..38dbe5b5d 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 f2f1670a5..b2351d58d 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 5b24aad3e..c21a8ed37 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 7ba2bf38c..ef349fa66 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;
        authTokenInjector?: ((reason?) => Promise<string>);
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
    }

    Properties

    interface ClientOptions {
        apiKey?: string;
        authTokenInjector?: ((reason?) => Promise<string>);
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
    }

    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.

    -
    authTokenInjector?: ((reason?) => Promise<string>)

    authTokenInjector is a function that provides a token for the auth webhook. +

    authTokenInjector?: ((reason?) => Promise<string>)

    authTokenInjector is a function that provides a token for the auth webhook. When the webhook response status code is 401, this function is called to refresh the token. The reason parameter is the reason from the webhook response.

    -

    Type declaration

      • (reason?): Promise<string>
      • Parameters

        • Optional reason: string

        Returns Promise<string>

    key?: string

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

    Type declaration

      • (reason?): Promise<string>
      • Parameters

        • Optional reason: string

        Returns Promise<string>

    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).

    -
    \ 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 f1f80f96a..fdaf2c614 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 47831ec64..3b5b5ec47 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 d6c2d5932..b29a5d327 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 078117c5b..34943a90d 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 e958f889f..a2a2ed011 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 4e7ce7901..977e12529 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 9a58b7976..8820a0f70 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 57a6b5461..d6397fecd 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: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    -
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file +

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    +
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file diff --git a/api-reference/interfaces/SyncStatusChangedEvent.html b/api-reference/interfaces/SyncStatusChangedEvent.html index 2f029da68..d65833bce 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: DocSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

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

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    Properties

    enum DocEventType.SyncStatusChanged

    -
    \ No newline at end of file +
    value: DocSyncStatus
    \ No newline at end of file diff --git a/api-reference/interfaces/UnwatchedEvent.html b/api-reference/interfaces/UnwatchedEvent.html index e6131a671..872492506 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 fe9d57df8..021b26509 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 5ac65982b..1622a1245 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 633cece4f..e731fbdef 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 358b81859..f389a750f 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 070e98ee1..f9c3b8f93 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 9c4a3350f..36a579fa6 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 043e73125..1bd9cea9f 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 40ac2f0b4..059c4869c 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 fca1e65e7..9b5c2c21b 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 9bbd85df4..f2a93dd48 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 1cef3f5f5..4560f0399 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 2e4e9f616..552d60fcb 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 0ec6c6d76..89499991e 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 d6b9e8df3..70aa73b18 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 | AuthErrorEvent

    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 892378609..297e213e5 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 73b042cd4..e7510897a 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 f6dd1d791..f73238c56 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 6704ec825..86646516e 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 bb04e785c..b28a9d77c 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 5a7c88b49..446c8e4b7 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 d1fdb683d..c096c154f 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 a02f78367..53fd935e0 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 89e1e522a..4dc6a14e4 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 69f1cd208..befb1d912 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 8f4bdf7ab..7a053e666 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 184a34918..2bb25be57 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 bcded46da..ab689e9b0 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 037d87168..ec56888fb 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 e37150eb7..e25661eb1 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 efd3fa60a..5c0be67a2 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 134d3d009..f90f214d6 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 01b7dcfb7..9ee73c3b7 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 d834627ed..c897c2eae 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 37ac2cccf..21988b7c8 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 75f85f407..8a602a178 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 4a3d644c6..4725a369d 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 22f471c25..c99c264d7 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 448fa94b4..e3634f38d 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 20356897c..2492ae71a 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 dd9fa33ad..6646d00be 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 15d9321c9..dd98594f3 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 258290442..9a9940493 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 95fa4dc89..b19866c00 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 8f70aad79..196e9fd7e 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 133399195..9b6a3bceb 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 5d56611b2..36af2618f 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 3e3ecd5be..f5843f25b 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 241e6c685..17cc914a4 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 32baf3d06..f2d4dedcf 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 0790a7459..f3af4af45 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 dbe9fb30d..b249d0f42 100644 --- a/api-reference/variables/converter.html +++ b/api-reference/variables/converter.html @@ -19,4 +19,4 @@

    Parameters

    Returns PbOperation

  • toTreeNodes: ((node) => PbTreeNode[])
  • toUint8Array: ((hex) => Uint8Array)
  • versionVectorToHex: ((vector) => string)
  • \ No newline at end of file +

    Parameters

    Returns string

    \ No newline at end of file diff --git a/api-reference/variables/default.html b/api-reference/variables/default.html index f1815be78..fa3354789 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 0f3d967da..453591eae 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/chunks/app/page-4229c045ecb9909b.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-d47c72bd3c8b5064.js similarity index 99% rename from examples/nextjs-scheduler/_next/static/chunks/app/page-4229c045ecb9909b.js rename to examples/nextjs-scheduler/_next/static/chunks/app/page-d47c72bd3c8b5064.js index d3fc6dc29..32e752873 100644 --- a/examples/nextjs-scheduler/_next/static/chunks/app/page-4229c045ecb9909b.js +++ b/examples/nextjs-scheduler/_next/static/chunks/app/page-d47c72bd3c8b5064.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,B,O,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(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 G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[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[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eB,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{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:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eO},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eO},{no:6,name:"ins_next_id",kind:"message",T:eO},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodes",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodeID",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eO},{no:2,name:"left_sibling_id",kind:"message",T:eO}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{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:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{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:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{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:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{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:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{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:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{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}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided",o.ErrPermissionDenied="ErrPermissionDenied",o.ErrUnauthenticated="ErrUnauthenticated";class ti 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 ts(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 to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(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 th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),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 td(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>e.lamport)return 1;if(e.lamport>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 tu=new td(0n,0,th);function tg(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}})}new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");class tf{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 tm extends tf{constructor(e){super(e)}}class tp{static of(e,t){return new tp(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 ty{static create(){return new ty}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=tp.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 ti(x.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 ti(x.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 tv extends tm{static create(e,t){if(!t)return new tv(e,ty.create());let r=ty.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tv(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(tg(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(tg(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tv.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 tm&&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}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tw{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.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 tA{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 tT{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 ti(x.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 tT(e.getLeft());t.root&&t.root.setParent();let r=new tT(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}}var tS=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tI extends tf{static of(e,t){return new tI(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 tS.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tS.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tg(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tI.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 tS.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tI.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=tS.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tI.getPrimitiveType(e),this.value=void 0===e?null:e}}class tC extends tA{static createAfter(e,t){let r=new tC(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 tx{static create(){return new tx}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.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=tC.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 ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.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 ti(x.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=tI.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tC(e),this.last=this.dummyHead,this.nodeMapByIndex=new tT,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tP extends tm{static create(e,t){if(!t)return new tP(e,tx.create());let r=tx.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tP(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 tm&&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:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),l,[a,a]]}setStyle(e,t,r,n,i){let[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,o]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),a=[],c=this.rgaTreeSplit.findBetween(o,s),l=new Map,h=[];for(let e of c){let t;let s=e.getCreatedAt().getActorID(),o=0n;if(void 0===i&&void 0===n?o=0x7fffffffffffffffn:i.size()>0?o=i.get(s)?i.get(s):0n:t=n.has(s)?n.get(s):tu,e.canStyle(r,t,o)){let t=l.get(s),r=e.getCreatedAt();(!t||r.after(t))&&l.set(s,r),h.push(e)}}let d=[];for(let e of h){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:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,o,r);void 0!==t&&d.push({parent:e.getValue(),child:t})}}return[l,d,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:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tO(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 tJ extends tw{static create(e,t,r,n,i,s,o){return new tJ(e,t,r,n,i,s,o)}execute(e,t,r){let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tO))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,i,s]=n.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,r);for(let t of s)e.registerGCPair(t);return{opInfos:i.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,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class tL extends tw{static create(e,t,r,n,i,s){return new tL(e,t,r,n,i,s)}execute(e,t,r){let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tO))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,i,s]=n.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,r);for(let t of i)e.registerGCPair(t);return{opInfos:s.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 t_="text";function tM(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 ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.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 ti(x.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 ti(x.ErrRefused,"Text node cannot have children")}}function tz(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tz(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tK{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.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){tz(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 ti(x.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 o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.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 ti(x.ErrInvalidArgument,"invalid treePos");let i=tM(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tM(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 ti(x.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 ti(x.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 tV(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:tF,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tW{static of(e,t){return new tW(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],tW.of(n.id,tG.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tW.of(tG.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tG.of(td.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 ti(x.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 tG{static of(e,t){return new tG(e,t)}static fromStruct(e){return tG.of(td.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 ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.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 tH(tG.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tH(tG.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,r){return(t?!this.getCreatedAt().after(t):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t,r){return!this.isText&&(t?!this.getCreatedAt().after(t):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tN);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 tY(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tY)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tZ(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(tg(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tZ(e)).join(""),"")}class tX extends tf{static create(e,t){return new tX(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,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let s,[o]=e,a=o.getCreatedAt().getActorID(),c=0n;if(void 0===i&&void 0===n?c=0x7fffffffffffffffn:i.size()>0?c=i.get(a)?i.get(a):0n:s=n.has(a)?n.get(a):tu,o.canStyle(r,s,c)&&t){let e=d.get(a),n=o.getCreatedAt();(!e||n.after(e))&&d.set(a,n);let i=o.setAttrs(t,r),s=i.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=h[r.getKey()]),e},{}),c=o.parent,g=o.prevSibling||o.parent;for(let[e]of(Object.keys(s).length>0&&l.push({type:"style",from:this.toIndex(c,g),to:this.toIndex(o,o),fromPath:this.toPath(c,g),toPath:this.toPath(o,o),actor:r.getActorID(),value:s}),i))e&&u.push({parent:o,child:e})}}),[d,u,l]}removeStyle(e,t,r,n,i){let[s,o]=this.findNodesAndSplitText(e[0],r),[a,c]=this.findNodesAndSplitText(e[1],r),l=[],h=new Map,d=[];return this.traverseInPosRange(s,o,a,c,e=>{let s,[o]=e,a=o.getCreatedAt().getActorID(),c=0n;if(void 0===i&&void 0===n?c=0x7fffffffffffffffn:i.size()>0?c=i.get(a)?i.get(a):0n:s=n.has(a)?n.get(a):tu,o.canStyle(r,s,c)&&t){let e=h.get(a),n=o.getCreatedAt();for(let i of((!e||n.after(e))&&h.set(a,n),o.attrs||(o.attrs=new tN),t))for(let e of o.attrs.remove(i,r))d.push({parent:o,child:e});let i=o.parent,s=o.prevSibling||o.parent;l.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(i,s),to:this.toIndex(o,o),fromPath:this.toPath(i,s),toPath:this.toPath(o,o),value:t})}}),[h,d,l]}edit(e,t,r,n,i,s,o){let[a,c]=this.findNodesAndSplitText(e[0],n),[l,h]=this.findNodesAndSplitText(e[1],n),d=this.toIndex(a,c),u=this.toPath(a,c),g=[],f=[],m=[],p=new Map;this.traverseInPosRange(a,c,l,h,(e,t)=>{let r,[i,a]=e;if(a===D.Start&&!t)for(let e of i.children)m.push(e);let c=i.getCreatedAt().getActorID(),l=0n;if(void 0===o&&void 0===s?l=0x7fffffffffffffffn:o.size()>0?l=o.get(c)?o.get(c):0n:r=s.has(c)?s.get(c):tu,i.canDelete(n,r,l)||g.includes(i.parent)){let e=p.get(c),t=i.getCreatedAt();(!e||t.after(e))&&p.set(c,t),(a===D.Text||a===D.Start)&&g.push(i),f.push([i,a])}});let y=this.makeDeletionChanges(f,n),v=[];for(let e of g)e.remove(n),e.isRemoved&&v.push({parent:this,child:e});for(let e of m)e.removedAt||a.append(e);if(r>0){let e=0,t=a,s=c;for(;e{a.isRemoved&&(e.remove(n),v.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tY(e));y.length&&y[y.length-1].from===d?y[y.length-1].value=t:y.push({type:"content",from:d,to:d,fromPath:u,toPath:u,actor:n.getActorID(),value:t})}}return[y,v,p]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.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 tW.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 tZ(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,o;let a,c,l,h=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}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tW.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.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?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tK(e),this.nodeMapByID=new tj(tG.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class tQ extends tw{static create(e,t,r,n,i,s,o){return new tQ(e,t,r,n,i,s,o)}execute(e,t,r){var n;let i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(i instanceof tX))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let s=this.getExecutedAt(),[o,a]=i.edit([this.fromPos,this.toPos],null===(n=this.contents)||void 0===n?void 0:n.map(e=>e.deepcopy()),this.splitLevel,s,(()=>{let e=s.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(s.getLamport(),++e,s.getActorID())})(),this.maxCreatedAtMapByActor,r);for(let t of a)e.registerGCPair(t);return{opInfos:o.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}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=>tZ(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,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t${set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t$(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t$(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t$(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t0=new t$(new Map);class t1{static of(e,t,r,n,i){return new t1(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t1(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=e.versionVector;0===r.size()&&(r=r.deepcopy()).set(e.actor,e.lamport);let n=this.versionVector.max(r),i=new t1(this.clientSeq,t,this.actor,n);return i.versionVector.set(this.actor,t),i}setClocks(e,t){let r=e>this.lamport?e+1n:this.lamport+1n;t.unset(th);let n=this.versionVector.max(t);return n.set(this.actor,r),t1.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t1(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t1(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t2=new t1(0,0n,th,t0);class t3{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t3({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,this.id.getVersionVector());if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(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:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t3.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.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 t9{static create(e,t,r,n,i,s,o){return new t9(e,t,r,n,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}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t4{static of(e,t){return new t4(e,t)}increaseClientSeq(e){return 0===e?this:new t4(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t4.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==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t8=new t4(0n,0);class t5{static of(e,t){return new t5(e,t)}static fromStruct(e){return t5.of(td.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 t5(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 t6=t5.of(tu,0);class t7{static of(e,t){return new t7(e,t)}static fromStruct(e){let t=t5.fromStruct(e.id);return t7.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t5.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 re extends tA{static create(e,t){return new re(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 ti(x.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,n){if(!e.length)return[[],new Map,new Map];let[i,s]=this.filterNodes(e,t,r,n),o=new Map,a=new Map,c=this.makeChanges(s,t);for(let e of i){let r=e.getCreatedAt().getActorID();(!o.has(r)||e.getID().getCreatedAt().after(o.get(r)))&&o.set(r,e.getID().getCreatedAt()),a.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(s),[c,o,a]}filterNodes(e,t,r,n){let i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e;let o=a.getCreatedAt().getActorID(),c=0n;void 0===n&&void 0===r?c=0x7fffffffffffffffn:n.size()>0?c=n.get(o)?n.get(o):0n:e=r.has(o)?r.get(o):tu,a.canDelete(t,e,c)?i.push(a):s.push(a)}return s.push(a),[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);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class rn extends tf{static create(e,t,r){return new rn(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 tS.Z.fromBytesLE(Array.from(t));default:throw new ti(x.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=rn.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 tS.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!rn.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 ti(x.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()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tS.Z.fromNumber(this.value+rr(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=tS.Z.fromNumber(t).toInt():this.value=rr(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tS.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class ri extends tw{static create(e,t,r){return new ri(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof rn))throw new ti(x.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()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return ri.create(this.getParentCreatedAt(),tI.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 rs extends tw{static create(e,t,r,n,i,s){return new rs(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new rs(e,t,r,n,new Map,i,s)}execute(e,t,r){let n,i;let s=e.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(s instanceof tX))throw new ti(x.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}),[,i,n]=s.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}else{let e=this.attributesToRemove;[,i,n]=s.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}for(let t of i)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,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,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ro(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rc(e.getVersionVector())})}function ra(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rc(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rl(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rh(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){if(e instanceof tv)return new ew({type:S.JSON_OBJECT,createdAt:ra(e.getCreatedAt()),value:rK(e)});if(e instanceof tP)return new ew({type:S.JSON_ARRAY,createdAt:ra(e.getCreatedAt()),value:ry(e).toBinary()});if(e instanceof tO)return new ew({type:S.TEXT,createdAt:ra(e.getCreatedAt())});if(e instanceof tI)return new ew({type:rl(e.getType()),createdAt:ra(e.getCreatedAt()),value:e.toBytes()});if(e instanceof rn)return new ew({type:rh(e.getType()),createdAt:ra(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tX)return new ew({type:S.TREE,createdAt:ra(e.getCreatedAt()),value:rv(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function ru(e){return new eU({createdAt:ra(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rg(e){return new eJ({parentId:rf(e.getParentID()),leftSiblingId:rf(e.getLeftSiblingID())})}function rf(e){return new eO({createdAt:ra(e.getCreatedAt()),offset:e.getOffset()})}function rm(e){let t=new ea;if(e instanceof tb){let r=new ec;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.key=e.getKey(),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tk){let r=new el;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.prevCreatedAt=ra(e.getPrevCreatedAt()),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tD){let r=new eh;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.prevCreatedAt=ra(e.getPrevCreatedAt()),r.createdAt=ra(e.getCreatedAt()),r.executedAt=ra(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tE){let r=new ed;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.createdAt=ra(e.getCreatedAt()),r.executedAt=ra(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tJ){let r=new eu;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=ru(e.getFromPos()),r.to=ru(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=ra(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tL){let r=new ef;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=ru(e.getFromPos()),r.to=ru(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=ra(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof ri){let r=new em;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tQ){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eB({content:rp(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=ra(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof rs){let r=new ey;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(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=ra(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function rp(e){if(!e)return[];let t=[];return tz(e,(e,r)=>{let n=new eN({id:rf(e.id),type:e.type,removedAt:ra(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rf(e.insPrevID)),e.insNextID&&(n.insNextId=rf(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:ra(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function ry(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rw(r.getValue())}));return t}(e.getElements()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}function rv(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:rp(e.getRoot()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}function rw(e){if(e instanceof tv)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rw(r.getValue())}));return t}(e.getRHT()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tP)return ry(e);if(e instanceof tI)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rl(e.getType()),value:e.toBytes(),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tO)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:ra((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=ra(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=ra(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof rn)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rh(e.getType()),value:e.toBytes(),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tX)return rv(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rA(e){if(!(e instanceof G.K))return{};for(let t of e.findDetails(tn.Qf))return t.metadata;return{}}function rT(e){var t;return null!==(t=rA(e).code)&&void 0!==t?t:""}function rS(e){return t1.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t$;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tv.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tP.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tO.create(rt.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tI.of(tI.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return rn.create(rE(e.type),rn.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return t7.of(t5.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t5.of(rC(e.createdAt),e.offset)}function rR(e){return tW.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tG.of(rC(e.createdAt),e.offset)}function rB(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tH.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tN.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(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(),tX.create(r,tu).getRoot()}function rO(e){if("set"===e.body.case){let t=e.body.value;return tb.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tk.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tE.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(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,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tJ.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(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,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return ri.create(rC(t.parentCreatedAt),rb(t.value),rC(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,rC(n))}),tQ.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rB(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(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,rC(r))}),(null==n?void 0:n.length)>0)?rs.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),rs.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t3.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rO(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new ty;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tv(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tx;for(let r of e.nodes)t.insert(rq(r.element));let r=new tP(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rB(e.nodes);return tX.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tI.of(tI.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rt,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=re.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tO(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=rn.create(rE(e.type),rn.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rw(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ro(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rm(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rc(e.getVersionVector()),minSyncedTicket:ra(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t9.create(e.documentKey,(t=e.checkpoint,t4.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:rp,fromTreeNodes:rB,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tv.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rm,toChangeID:ro,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rO(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rc(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=B||(B={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={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;rrj<=e};function rH(){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 rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.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 rZ=()=>{};class rX{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 ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),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){rG.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=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tv.create(tu))}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 ti(x.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 tm&&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 tm&&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 tm&&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 r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}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 tO||e instanceof tX)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tb.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 ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(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(tE.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.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(tD.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tD.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(tD.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(tD.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tk.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.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(tE.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(tE.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),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.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 r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.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;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{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 ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(B.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tJ(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}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 ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(B.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.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 ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([t7.fromStruct(e[0]),t7.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.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 ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{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 ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tI.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(ri.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===t_){r8(e);let{value:r}=e,s=tH.create(tG.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tN,Object.entries(e)))s.set(t,r,i)}let c=tH.create(tG.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===t_)for(let t of e){let{type:e}=t;if(e!==t_)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===t_)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tH.create(tG.of(e.issueTimeTicket(),0),"root");let t=tH.create(tG.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(rs.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(rs.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(rs.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,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]&&(r5(r),r[0].type!==t_))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===t_){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tH.create(tG.of(this.context.issueTimeTicket(),0),t_,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===t_){let{value:e}=t;r=tH.create(tG.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tN,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tH.create(tG.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(tQ.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tW.fromStruct(e[0]),tW.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tW.fromStruct(e[0]),tW.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tI)return t;if(t instanceof tv)return r0(e,t);if(t instanceof tP)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tO)return new r3(e,t);else if(t instanceof rn){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tX){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tI?r.getValue():r}function nt(e,t,r){let n;if(tI.isSupport(t))n=tI.of(t,r);else if(Array.isArray(t))n=tP.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tO.create(rt.create(),r),t.initialize(e,n)):t instanceof r9?(n=rn.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tX.create(t.buildRoot(e),r),t.initialize(e,n)):n=tv.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{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 nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=O||(O={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",p.AuthError="auth-error",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(B.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.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 o=[];t.length>0&&o.push({type:"local-change",source:E.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()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(B.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.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):"auth-error"===e?this.eventStream.subscribe(e=>{for(let r of e)"auth-error"===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 ti(x.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])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){let t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),E.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(B.Trivial)&&rG.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:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t9.create(this.key,t,!1,e,this.getVersionVector())}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(),r0(rQ.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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1,{root:i,presences:s}=rU.bytesToSnapshot(r);this.root=new r$(i),this.presences=s,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(n),this.applyChanges(this.localChanges,E.Local),this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(B.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(B.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(B.Debug)&&rG.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 P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.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.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.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:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.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(th),this.publish([{source:"removed"===e?E.Remote:E.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,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t3.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 ti(x.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?ts(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?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(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}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tl(t,ts(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,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.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 o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tl(t,ts(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,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.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 o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}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}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t2,this.checkpoint=t8,this.localChanges=[],this.eventStream=function(e){let t=new rX(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 nr,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()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({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"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.6"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){let e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(async e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}))}deactivate(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{keepalive:!1};if("deactivated"===this.status)return Promise.resolve();let t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}catch(e){throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}};if(e.keepalive){this.keepalive=!0;let e=t();return this.keepalive=!1,e}return this.enqueueTask(t)}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==O.Detached)throw new ti(x.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,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}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:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===O.Removed)return e;e.applyStatus(O.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(async e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.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:rU.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=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==O.Removed&&e.applyStatus(O.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(async e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.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 ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),await 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(async e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.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=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(async e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),await 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 ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=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(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(async e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),await this.handleConnectError(e)){if(e instanceof G.K&&rT(e)===x.ErrUnauthenticated&&s.doc.publish([{type:J.AuthError,value:{reason:rA(e).reason,method:"Broadcast"}}]),ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.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).catch(async t=>{throw t instanceof G.K&&rT(t)===x.ErrUnauthenticated&&e.doc.publish([{type:J.AuthError,value:{reason:rA(t).reason,method:"PushPull"}}]),t})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),await this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.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 ti(x.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 ti(x.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:J.ConnectionChanged,value:L.Connected}]),rG.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:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),await this.handleConnectError(e)?(e instanceof G.K&&rT(e)===x.ErrUnauthenticated&&t.doc.publish([{type:J.AuthError,value:{reason:rA(e).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.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(O.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:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===O.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(async e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}async handleConnectError(e){if(!(e instanceof G.K))return!1;if(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable)return!0;if(rT(e)===x.ErrUnauthenticated){if(this.authTokenInjector){let t=await this.authTokenInjector(rA(e).reason);this.setAuthToken(t)}return!0}return(rT(e)===x.ErrClientNotActivated||rT(e)===x.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){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n,i,s;let o;this.processing=!1,this.keepalive=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=null!==(r=t.syncLoopDuration)&&void 0!==r?r:nh.syncLoopDuration,this.reconnectStreamDelay=null!==(n=t.reconnectStreamDelay)&&void 0!==n?n:nh.reconnectStreamDelay,this.retrySyncLoopDelay=null!==(i=t.retrySyncLoopDelay)&&void 0!==i?i:nh.retrySyncLoopDelay;let{authInterceptor:a,setToken:c}=(s=this.apiKey,o=void 0,{authInterceptor:e=>async t=>(s&&t.header.set("x-api-key",s),o&&t.header.set("authorization",o),await e(t)),setToken:e=>{o=e}});this.setAuthToken=c,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[a,e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))],fetch:(e,t)=>{let r={...t,keepalive:this.keepalive};return fetch(e,r)}})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tI,Text:r3,Counter:r9,Tree:r6,LogLevel:B,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tI,Text:r3,Counter:r9,Tree:r6,LogLevel:B,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.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===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.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()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{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 +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,B,O,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(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 G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[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[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eB,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{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:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eO},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eO},{no:6,name:"ins_next_id",kind:"message",T:eO},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodes",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodeID",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eO},{no:2,name:"left_sibling_id",kind:"message",T:eO}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{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:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{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:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{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:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{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:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{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:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{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}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided",o.ErrPermissionDenied="ErrPermissionDenied",o.ErrUnauthenticated="ErrUnauthenticated";class ti 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 ts(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 to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(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 th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),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 td(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>e.lamport)return 1;if(e.lamport>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 tu=new td(0n,0,th);function tg(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}})}new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");class tf{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 tm extends tf{constructor(e){super(e)}}class tp{static of(e,t){return new tp(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 ty{static create(){return new ty}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=tp.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 ti(x.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 ti(x.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 tv extends tm{static create(e,t){if(!t)return new tv(e,ty.create());let r=ty.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tv(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(tg(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(tg(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tv.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 tm&&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}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tw{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.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 tA{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 tT{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 ti(x.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 tT(e.getLeft());t.root&&t.root.setParent();let r=new tT(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}}var tS=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tI extends tf{static of(e,t){return new tI(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 tS.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tS.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tg(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tI.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 tS.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tI.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=tS.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tI.getPrimitiveType(e),this.value=void 0===e?null:e}}class tC extends tA{static createAfter(e,t){let r=new tC(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 tx{static create(){return new tx}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.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=tC.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 ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.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 ti(x.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=tI.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tC(e),this.last=this.dummyHead,this.nodeMapByIndex=new tT,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tP extends tm{static create(e,t){if(!t)return new tP(e,tx.create());let r=tx.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tP(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 tm&&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:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),l,[a,a]]}setStyle(e,t,r,n,i){let[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,o]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),a=[],c=this.rgaTreeSplit.findBetween(o,s),l=new Map,h=[];for(let e of c){let t;let s=e.getCreatedAt().getActorID(),o=0n;if(void 0===i&&void 0===n?o=0x7fffffffffffffffn:i.size()>0?o=i.get(s)?i.get(s):0n:t=n.has(s)?n.get(s):tu,e.canStyle(r,t,o)){let t=l.get(s),r=e.getCreatedAt();(!t||r.after(t))&&l.set(s,r),h.push(e)}}let d=[];for(let e of h){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:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,o,r);void 0!==t&&d.push({parent:e.getValue(),child:t})}}return[l,d,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:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tO(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 tJ extends tw{static create(e,t,r,n,i,s,o){return new tJ(e,t,r,n,i,s,o)}execute(e,t,r){let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tO))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,i,s]=n.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,r);for(let t of s)e.registerGCPair(t);return{opInfos:i.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,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class tL extends tw{static create(e,t,r,n,i,s){return new tL(e,t,r,n,i,s)}execute(e,t,r){let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tO))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,i,s]=n.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,r);for(let t of i)e.registerGCPair(t);return{opInfos:s.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 t_="text";function tM(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 ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.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 ti(x.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 ti(x.ErrRefused,"Text node cannot have children")}}function tz(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tz(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tK{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.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){tz(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 ti(x.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 o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.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 ti(x.ErrInvalidArgument,"invalid treePos");let i=tM(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tM(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 ti(x.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 ti(x.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 tV(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:tF,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tW{static of(e,t){return new tW(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],tW.of(n.id,tG.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tW.of(tG.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tG.of(td.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 ti(x.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 tG{static of(e,t){return new tG(e,t)}static fromStruct(e){return tG.of(td.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 ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.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 tH(tG.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tH(tG.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,r){return(t?!this.getCreatedAt().after(t):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t,r){return!this.isText&&(t?!this.getCreatedAt().after(t):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tN);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 tY(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tY)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tZ(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(tg(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tZ(e)).join(""),"")}class tX extends tf{static create(e,t){return new tX(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,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let s,[o]=e,a=o.getCreatedAt().getActorID(),c=0n;if(void 0===i&&void 0===n?c=0x7fffffffffffffffn:i.size()>0?c=i.get(a)?i.get(a):0n:s=n.has(a)?n.get(a):tu,o.canStyle(r,s,c)&&t){let e=d.get(a),n=o.getCreatedAt();(!e||n.after(e))&&d.set(a,n);let i=o.setAttrs(t,r),s=i.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=h[r.getKey()]),e},{}),c=o.parent,g=o.prevSibling||o.parent;for(let[e]of(Object.keys(s).length>0&&l.push({type:"style",from:this.toIndex(c,g),to:this.toIndex(o,o),fromPath:this.toPath(c,g),toPath:this.toPath(o,o),actor:r.getActorID(),value:s}),i))e&&u.push({parent:o,child:e})}}),[d,u,l]}removeStyle(e,t,r,n,i){let[s,o]=this.findNodesAndSplitText(e[0],r),[a,c]=this.findNodesAndSplitText(e[1],r),l=[],h=new Map,d=[];return this.traverseInPosRange(s,o,a,c,e=>{let s,[o]=e,a=o.getCreatedAt().getActorID(),c=0n;if(void 0===i&&void 0===n?c=0x7fffffffffffffffn:i.size()>0?c=i.get(a)?i.get(a):0n:s=n.has(a)?n.get(a):tu,o.canStyle(r,s,c)&&t){let e=h.get(a),n=o.getCreatedAt();for(let i of((!e||n.after(e))&&h.set(a,n),o.attrs||(o.attrs=new tN),t))for(let e of o.attrs.remove(i,r))d.push({parent:o,child:e});let i=o.parent,s=o.prevSibling||o.parent;l.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(i,s),to:this.toIndex(o,o),fromPath:this.toPath(i,s),toPath:this.toPath(o,o),value:t})}}),[h,d,l]}edit(e,t,r,n,i,s,o){let[a,c]=this.findNodesAndSplitText(e[0],n),[l,h]=this.findNodesAndSplitText(e[1],n),d=this.toIndex(a,c),u=this.toPath(a,c),g=[],f=[],m=[],p=new Map;this.traverseInPosRange(a,c,l,h,(e,t)=>{let r,[i,a]=e;if(a===D.Start&&!t)for(let e of i.children)m.push(e);let c=i.getCreatedAt().getActorID(),l=0n;if(void 0===o&&void 0===s?l=0x7fffffffffffffffn:o.size()>0?l=o.get(c)?o.get(c):0n:r=s.has(c)?s.get(c):tu,i.canDelete(n,r,l)||g.includes(i.parent)){let e=p.get(c),t=i.getCreatedAt();(!e||t.after(e))&&p.set(c,t),(a===D.Text||a===D.Start)&&g.push(i),f.push([i,a])}});let y=this.makeDeletionChanges(f,n),v=[];for(let e of g)e.remove(n),e.isRemoved&&v.push({parent:this,child:e});for(let e of m)e.removedAt||a.append(e);if(r>0){let e=0,t=a,s=c;for(;e{a.isRemoved&&(e.remove(n),v.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tY(e));y.length&&y[y.length-1].from===d?y[y.length-1].value=t:y.push({type:"content",from:d,to:d,fromPath:u,toPath:u,actor:n.getActorID(),value:t})}}return[y,v,p]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.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 tW.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 tZ(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,o;let a,c,l,h=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}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tW.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.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?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tK(e),this.nodeMapByID=new tj(tG.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class tQ extends tw{static create(e,t,r,n,i,s,o){return new tQ(e,t,r,n,i,s,o)}execute(e,t,r){var n;let i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(i instanceof tX))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let s=this.getExecutedAt(),[o,a]=i.edit([this.fromPos,this.toPos],null===(n=this.contents)||void 0===n?void 0:n.map(e=>e.deepcopy()),this.splitLevel,s,(()=>{let e=s.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(s.getLamport(),++e,s.getActorID())})(),this.maxCreatedAtMapByActor,r);for(let t of a)e.registerGCPair(t);return{opInfos:o.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}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=>tZ(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,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t${set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t$(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t$(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t$(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t0=new t$(new Map);class t1{static of(e,t,r,n,i){return new t1(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t1(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=e.versionVector;0===r.size()&&(r=r.deepcopy()).set(e.actor,e.lamport);let n=this.versionVector.max(r),i=new t1(this.clientSeq,t,this.actor,n);return i.versionVector.set(this.actor,t),i}setClocks(e,t){let r=e>this.lamport?e+1n:this.lamport+1n;t.unset(th);let n=this.versionVector.max(t);return n.set(this.actor,r),t1.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t1(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t1(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t2=new t1(0,0n,th,t0);class t3{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t3({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,this.id.getVersionVector());if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(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:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t3.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.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 t9{static create(e,t,r,n,i,s,o){return new t9(e,t,r,n,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}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t4{static of(e,t){return new t4(e,t)}increaseClientSeq(e){return 0===e?this:new t4(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t4.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==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t8=new t4(0n,0);class t5{static of(e,t){return new t5(e,t)}static fromStruct(e){return t5.of(td.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 t5(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 t6=t5.of(tu,0);class t7{static of(e,t){return new t7(e,t)}static fromStruct(e){let t=t5.fromStruct(e.id);return t7.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t5.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 re extends tA{static create(e,t){return new re(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 ti(x.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,n){if(!e.length)return[[],new Map,new Map];let[i,s]=this.filterNodes(e,t,r,n),o=new Map,a=new Map,c=this.makeChanges(s,t);for(let e of i){let r=e.getCreatedAt().getActorID();(!o.has(r)||e.getID().getCreatedAt().after(o.get(r)))&&o.set(r,e.getID().getCreatedAt()),a.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(s),[c,o,a]}filterNodes(e,t,r,n){let i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e;let o=a.getCreatedAt().getActorID(),c=0n;void 0===n&&void 0===r?c=0x7fffffffffffffffn:n.size()>0?c=n.get(o)?n.get(o):0n:e=r.has(o)?r.get(o):tu,a.canDelete(t,e,c)?i.push(a):s.push(a)}return s.push(a),[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);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class rn extends tf{static create(e,t,r){return new rn(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 tS.Z.fromBytesLE(Array.from(t));default:throw new ti(x.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=rn.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 tS.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!rn.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 ti(x.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()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tS.Z.fromNumber(this.value+rr(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=tS.Z.fromNumber(t).toInt():this.value=rr(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tS.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class ri extends tw{static create(e,t,r){return new ri(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof rn))throw new ti(x.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()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return ri.create(this.getParentCreatedAt(),tI.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 rs extends tw{static create(e,t,r,n,i,s){return new rs(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new rs(e,t,r,n,new Map,i,s)}execute(e,t,r){let n,i;let s=e.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(s instanceof tX))throw new ti(x.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}),[,i,n]=s.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}else{let e=this.attributesToRemove;[,i,n]=s.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}for(let t of i)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,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,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ro(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rc(e.getVersionVector())})}function ra(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rc(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rl(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rh(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){if(e instanceof tv)return new ew({type:S.JSON_OBJECT,createdAt:ra(e.getCreatedAt()),value:rK(e)});if(e instanceof tP)return new ew({type:S.JSON_ARRAY,createdAt:ra(e.getCreatedAt()),value:ry(e).toBinary()});if(e instanceof tO)return new ew({type:S.TEXT,createdAt:ra(e.getCreatedAt())});if(e instanceof tI)return new ew({type:rl(e.getType()),createdAt:ra(e.getCreatedAt()),value:e.toBytes()});if(e instanceof rn)return new ew({type:rh(e.getType()),createdAt:ra(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tX)return new ew({type:S.TREE,createdAt:ra(e.getCreatedAt()),value:rv(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function ru(e){return new eU({createdAt:ra(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rg(e){return new eJ({parentId:rf(e.getParentID()),leftSiblingId:rf(e.getLeftSiblingID())})}function rf(e){return new eO({createdAt:ra(e.getCreatedAt()),offset:e.getOffset()})}function rm(e){let t=new ea;if(e instanceof tb){let r=new ec;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.key=e.getKey(),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tk){let r=new el;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.prevCreatedAt=ra(e.getPrevCreatedAt()),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tD){let r=new eh;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.prevCreatedAt=ra(e.getPrevCreatedAt()),r.createdAt=ra(e.getCreatedAt()),r.executedAt=ra(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tE){let r=new ed;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.createdAt=ra(e.getCreatedAt()),r.executedAt=ra(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tJ){let r=new eu;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=ru(e.getFromPos()),r.to=ru(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=ra(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tL){let r=new ef;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=ru(e.getFromPos()),r.to=ru(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=ra(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof ri){let r=new em;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.value=rd(e.getValue()),r.executedAt=ra(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tQ){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(r);r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eB({content:rp(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=ra(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof rs){let r=new ey;r.parentCreatedAt=ra(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=ra(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=ra(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function rp(e){if(!e)return[];let t=[];return tz(e,(e,r)=>{let n=new eN({id:rf(e.id),type:e.type,removedAt:ra(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rf(e.insPrevID)),e.insNextID&&(n.insNextId=rf(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:ra(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function ry(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rw(r.getValue())}));return t}(e.getElements()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}function rv(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:rp(e.getRoot()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}function rw(e){if(e instanceof tv)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rw(r.getValue())}));return t}(e.getRHT()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tP)return ry(e);if(e instanceof tI)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rl(e.getType()),value:e.toBytes(),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tO)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:ra((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=ra(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=ra(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof rn)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rh(e.getType()),value:e.toBytes(),createdAt:ra(e.getCreatedAt()),movedAt:ra(e.getMovedAt()),removedAt:ra(e.getRemovedAt())}),t}(e);if(e instanceof tX)return rv(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rA(e){if(!(e instanceof G.K))return{};for(let t of e.findDetails(tn.Qf))return t.metadata;return{}}function rT(e){var t;return null!==(t=rA(e).code)&&void 0!==t?t:""}function rS(e){return t1.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t$;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tv.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tP.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tO.create(rt.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tI.of(tI.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return rn.create(rE(e.type),rn.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return t7.of(t5.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t5.of(rC(e.createdAt),e.offset)}function rR(e){return tW.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tG.of(rC(e.createdAt),e.offset)}function rB(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tH.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tN.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(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(),tX.create(r,tu).getRoot()}function rO(e){if("set"===e.body.case){let t=e.body.value;return tb.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tk.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tE.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(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,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tJ.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(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,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return ri.create(rC(t.parentCreatedAt),rb(t.value),rC(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,rC(n))}),tQ.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rB(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(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,rC(r))}),(null==n?void 0:n.length)>0)?rs.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),rs.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t3.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rO(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new ty;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tv(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tx;for(let r of e.nodes)t.insert(rq(r.element));let r=new tP(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rB(e.nodes);return tX.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tI.of(tI.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rt,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=re.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tO(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=rn.create(rE(e.type),rn.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rw(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ro(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rm(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rc(e.getVersionVector()),minSyncedTicket:ra(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t9.create(e.documentKey,(t=e.checkpoint,t4.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:rp,fromTreeNodes:rB,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tv.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rm,toChangeID:ro,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rO(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rc(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=B||(B={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={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;rrj<=e};function rH(){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 rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.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 rZ=()=>{};class rX{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 ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),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){rG.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=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tv.create(tu))}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 ti(x.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 tm&&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 tm&&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 tm&&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 r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}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 tO||e instanceof tX)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tb.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 ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(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(tE.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.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(tD.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tD.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(tD.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(tD.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tk.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.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(tE.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(tE.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),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.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 r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.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;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(B.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{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 ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(B.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tJ(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}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 ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(B.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.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 ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([t7.fromStruct(e[0]),t7.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.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 ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{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 ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tI.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(ri.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===t_){r8(e);let{value:r}=e,s=tH.create(tG.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tN,Object.entries(e)))s.set(t,r,i)}let c=tH.create(tG.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===t_)for(let t of e){let{type:e}=t;if(e!==t_)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===t_)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tH.create(tG.of(e.issueTimeTicket(),0),"root");let t=tH.create(tG.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(rs.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(rs.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(rs.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,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]&&(r5(r),r[0].type!==t_))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===t_){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tH.create(tG.of(this.context.issueTimeTicket(),0),t_,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===t_){let{value:e}=t;r=tH.create(tG.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tN,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tH.create(tG.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(tQ.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.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 ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tW.fromStruct(e[0]),tW.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tW.fromStruct(e[0]),tW.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tI)return t;if(t instanceof tv)return r0(e,t);if(t instanceof tP)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tO)return new r3(e,t);else if(t instanceof rn){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tX){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tI?r.getValue():r}function nt(e,t,r){let n;if(tI.isSupport(t))n=tI.of(t,r);else if(Array.isArray(t))n=tP.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tO.create(rt.create(),r),t.initialize(e,n)):t instanceof r9?(n=rn.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tX.create(t.buildRoot(e),r),t.initialize(e,n)):n=tv.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{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 nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=O||(O={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",p.AuthError="auth-error",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(B.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.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 o=[];t.length>0&&o.push({type:"local-change",source:E.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()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(B.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.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):"auth-error"===e?this.eventStream.subscribe(e=>{for(let r of e)"auth-error"===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 ti(x.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])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){let t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),E.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(B.Trivial)&&rG.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:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t9.create(this.key,t,!1,e,this.getVersionVector())}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(),r0(rQ.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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1,{root:i,presences:s}=rU.bytesToSnapshot(r);this.root=new r$(i),this.presences=s,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(n),this.applyChanges(this.localChanges,E.Local),this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(B.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(B.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(B.Debug)&&rG.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 P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.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.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.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:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.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(th),this.publish([{source:"removed"===e?E.Remote:E.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,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t3.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 ti(x.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?ts(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?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(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}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tl(t,ts(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,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.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 o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tl(t,ts(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,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.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 o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}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}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t2,this.checkpoint=t8,this.localChanges=[],this.eventStream=function(e){let t=new rX(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 nr,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()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({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"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.7"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){let e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(async e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}))}deactivate(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{keepalive:!1};if("deactivated"===this.status)return Promise.resolve();let t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}catch(e){throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}};if(e.keepalive){this.keepalive=!0;let e=t();return this.keepalive=!1,e}return this.enqueueTask(t)}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==O.Detached)throw new ti(x.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,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}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:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===O.Removed)return e;e.applyStatus(O.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(async e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.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:rU.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=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==O.Removed&&e.applyStatus(O.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(async e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.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 ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),await 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(async e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),await this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.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=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(async e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),await 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 ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=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(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(async e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),await this.handleConnectError(e)){if(e instanceof G.K&&rT(e)===x.ErrUnauthenticated&&s.doc.publish([{type:J.AuthError,value:{reason:rA(e).reason,method:"Broadcast"}}]),ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.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).catch(async t=>{throw t instanceof G.K&&rT(t)===x.ErrUnauthenticated&&e.doc.publish([{type:J.AuthError,value:{reason:rA(t).reason,method:"PushPull"}}]),t})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),await this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.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 ti(x.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 ti(x.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:J.ConnectionChanged,value:L.Connected}]),rG.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:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),await this.handleConnectError(e)?(e instanceof G.K&&rT(e)===x.ErrUnauthenticated&&t.doc.publish([{type:J.AuthError,value:{reason:rA(e).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.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(O.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:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===O.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(async e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}async handleConnectError(e){if(!(e instanceof G.K))return!1;if(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable)return!0;if(rT(e)===x.ErrUnauthenticated){if(this.authTokenInjector){let t=await this.authTokenInjector(rA(e).reason);this.setAuthToken(t)}return!0}return(rT(e)===x.ErrClientNotActivated||rT(e)===x.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){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n,i,s;let o;this.processing=!1,this.keepalive=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=null!==(r=t.syncLoopDuration)&&void 0!==r?r:nh.syncLoopDuration,this.reconnectStreamDelay=null!==(n=t.reconnectStreamDelay)&&void 0!==n?n:nh.reconnectStreamDelay,this.retrySyncLoopDelay=null!==(i=t.retrySyncLoopDelay)&&void 0!==i?i:nh.retrySyncLoopDelay;let{authInterceptor:a,setToken:c}=(s=this.apiKey,o=void 0,{authInterceptor:e=>async t=>(s&&t.header.set("x-api-key",s),o&&t.header.set("authorization",o),await e(t)),setToken:e=>{o=e}});this.setAuthToken=c,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[a,e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))],fetch:(e,t)=>{let r={...t,keepalive:this.keepalive};return fetch(e,r)}})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tI,Text:r3,Counter:r9,Tree:r6,LogLevel:B,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tI,Text:r3,Counter:r9,Tree:r6,LogLevel:B,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.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===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.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()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{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/wLeZu3DP96EZimuMGR2Il/_buildManifest.js b/examples/nextjs-scheduler/_next/static/u3uXYOUHYQOqUxL-X8yoB/_buildManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/wLeZu3DP96EZimuMGR2Il/_buildManifest.js rename to examples/nextjs-scheduler/_next/static/u3uXYOUHYQOqUxL-X8yoB/_buildManifest.js diff --git a/examples/nextjs-scheduler/_next/static/wLeZu3DP96EZimuMGR2Il/_ssgManifest.js b/examples/nextjs-scheduler/_next/static/u3uXYOUHYQOqUxL-X8yoB/_ssgManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/wLeZu3DP96EZimuMGR2Il/_ssgManifest.js rename to examples/nextjs-scheduler/_next/static/u3uXYOUHYQOqUxL-X8yoB/_ssgManifest.js diff --git a/examples/nextjs-scheduler/index.html b/examples/nextjs-scheduler/index.html index 7935e36ee..f4e855183 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 : 10-12-24

    input form

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

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 11-12-24

    input form

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.txt b/examples/nextjs-scheduler/index.txt index 90be09bf8..540f7fe02 100644 --- a/examples/nextjs-scheduler/index.txt +++ b/examples/nextjs-scheduler/index.txt @@ -1,7 +1,7 @@ 2:I[9974,[],""] -3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-4229c045ecb9909b.js"],""] +3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-d47c72bd3c8b5064.js"],""] 4:I[4926,[],""] 5:I[4582,[],""] -0:["wLeZu3DP96EZimuMGR2Il",[[["",{"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:["u3uXYOUHYQOqUxL-X8yoB",[[["",{"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-BZcMnYBH.js b/examples/profile-stack/assets/index-D58-Rye2.js similarity index 99% rename from examples/profile-stack/assets/index-BZcMnYBH.js rename to examples/profile-stack/assets/index-D58-Rye2.js index e02cd710b..3610c3a0e 100644 --- a/examples/profile-stack/assets/index-BZcMnYBH.js +++ b/examples/profile-stack/assets/index-D58-Rye2.js @@ -20,7 +20,7 @@ var la=Object.defineProperty;var ha=(n,t,e)=>t in n?la(n,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Te=null;try{Te=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 O(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}O.prototype.__isLong__;Object.defineProperty(O.prototype,"__isLong__",{value:!0});function _(n){return(n&&n.__isLong__)===!0}function $i(n){var t=Math.clz32(n&-n);return n?31-t:t}O.isLong=_;var Ui={},qi={};function Ar(n,t){var e,r,s;return t?(n>>>=0,(s=0<=n&&n<256)&&(r=qi[n],r)?r:(e=B(n,0,!0),s&&(qi[n]=e),e)):(n|=0,(s=-128<=n&&n<128)&&(r=Ui[n],r)?r:(e=B(n,n<0?-1:0,!1),s&&(Ui[n]=e),e))}O.fromInt=Ar;function Ae(n,t){if(isNaN(n))return t?Xt:xe;if(t){if(n<0)return Xt;if(n>=Bo)return Jo}else{if(n<=-Vi)return re;if(n+1>=Vi)return Lo}return n<0?Ae(-n,t).neg():B(n%Jr|0,n/Jr|0,t)}O.fromNumber=Ae;function B(n,t,e){return new O(n,t,e)}O.fromBits=B;var Vn=Math.pow;function Ws(n,t,e){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Xt:xe;if(e=e||10,e<2||360)throw Error("interior hyphen");if(r===0)return Ws(n.substring(1),t,e).neg();for(var s=Ae(Vn(e,8)),i=xe,o=0;o>>0:this.low};T.toNumber=function(){return this.unsigned?(this.high>>>0)*Jr+(this.low>>>0):this.high*Jr+(this.low>>>0)};T.toString=function(t){if(t=t||10,t<2||36>>0,f=h.toString(t);if(o=l,o.isZero())return f+c;for(;f.length<6;)f="0"+f;c=""+f+c}};T.getHighBits=function(){return this.high};T.getHighBitsUnsigned=function(){return this.high>>>0};T.getLowBits=function(){return this.low};T.getLowBitsUnsigned=function(){return this.low>>>0};T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(re)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};T.isOdd=function(){return(this.low&1)===1};T.isEven=function(){return(this.low&1)===0};T.equals=function(t){return _(t)||(t=De(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};T.eq=T.equals;T.notEquals=function(t){return!this.eq(t)};T.neq=T.notEquals;T.ne=T.notEquals;T.lessThan=function(t){return this.comp(t)<0};T.lt=T.lessThan;T.lessThanOrEqual=function(t){return this.comp(t)<=0};T.lte=T.lessThanOrEqual;T.le=T.lessThanOrEqual;T.greaterThan=function(t){return this.comp(t)>0};T.gt=T.greaterThan;T.greaterThanOrEqual=function(t){return this.comp(t)>=0};T.gte=T.greaterThanOrEqual;T.ge=T.greaterThanOrEqual;T.compare=function(t){if(_(t)||(t=De(t)),this.eq(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&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};T.comp=T.compare;T.negate=function(){return!this.unsigned&&this.eq(re)?re:this.not().add(Er)};T.neg=T.negate;T.add=function(t){_(t)||(t=De(t));var e=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,c=t.high&65535,l=t.low>>>16,h=t.low&65535,f=0,g=0,v=0,p=0;return p+=i+h,v+=p>>>16,p&=65535,v+=s+l,g+=v>>>16,v&=65535,g+=r+c,f+=g>>>16,g&=65535,f+=e+o,f&=65535,B(v<<16|p,f<<16|g,this.unsigned)};T.subtract=function(t){return _(t)||(t=De(t)),this.add(t.neg())};T.sub=T.subtract;T.multiply=function(t){if(this.isZero())return this;if(_(t)||(t=De(t)),Te){var e=Te.mul(this.low,this.high,t.low,t.high);return B(e,Te.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Xt:xe;if(this.eq(re))return t.isOdd()?re:xe;if(t.eq(re))return this.isOdd()?re:xe;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(Ki)&&t.lt(Ki))return Ae(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,c=t.high>>>16,l=t.high&65535,h=t.low>>>16,f=t.low&65535,g=0,v=0,p=0,w=0;return w+=o*f,p+=w>>>16,w&=65535,p+=i*f,v+=p>>>16,p&=65535,p+=o*h,v+=p>>>16,p&=65535,v+=s*f,g+=v>>>16,v&=65535,v+=i*h,g+=v>>>16,v&=65535,v+=o*l,g+=v>>>16,v&=65535,g+=r*f+s*h+i*l+o*c,g&=65535,B(p<<16|w,g<<16|v,this.unsigned)};T.mul=T.multiply;T.divide=function(t){if(_(t)||(t=De(t)),t.isZero())throw Error("division by zero");if(Te){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Te.div_u:Te.div_s)(this.low,this.high,t.low,t.high);return B(e,Te.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Xt:xe;var r,s,i;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Xt;if(t.gt(this.shru(1)))return Ro;i=Xt}else{if(this.eq(re)){if(t.eq(Er)||t.eq(Fs))return re;if(t.eq(re))return Er;var o=this.shr(1);return r=o.div(t).shl(1),r.eq(xe)?t.isNegative()?Er:Fs:(s=this.sub(t.mul(r)),i=r.add(s.div(t)),i)}else if(t.eq(re))return this.unsigned?Xt:xe;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();i=xe}for(s=this;s.gte(t);){r=Math.max(1,Math.floor(s.toNumber()/t.toNumber()));for(var c=Math.ceil(Math.log(r)/Math.LN2),l=c<=48?1:Vn(2,c-48),h=Ae(r),f=h.mul(t);f.isNegative()||f.gt(s);)r-=l,h=Ae(r,this.unsigned),f=h.mul(t);h.isZero()&&(h=Er),i=i.add(h),s=s.sub(f)}return i};T.div=T.divide;T.modulo=function(t){if(_(t)||(t=De(t)),Te){var e=(this.unsigned?Te.rem_u:Te.rem_s)(this.low,this.high,t.low,t.high);return B(e,Te.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};T.mod=T.modulo;T.rem=T.modulo;T.not=function(){return B(~this.low,~this.high,this.unsigned)};T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};T.clz=T.countLeadingZeros;T.countTrailingZeros=function(){return this.low?$i(this.low):$i(this.high)+32};T.ctz=T.countTrailingZeros;T.and=function(t){return _(t)||(t=De(t)),B(this.low&t.low,this.high&t.high,this.unsigned)};T.or=function(t){return _(t)||(t=De(t)),B(this.low|t.low,this.high|t.high,this.unsigned)};T.xor=function(t){return _(t)||(t=De(t)),B(this.low^t.low,this.high^t.high,this.unsigned)};T.shiftLeft=function(t){return _(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low<>>32-t,this.unsigned):B(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):B(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};T.shr=T.shiftRight;T.shiftRightUnsigned=function(t){return _(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?B(this.high,0,this.unsigned):B(this.high>>>t-32,0,this.unsigned)};T.shru=T.shiftRightUnsigned;T.shr_u=T.shiftRightUnsigned;T.rotateLeft=function(t){var e;return _(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,B(this.high<>>e,this.low<>>e,this.unsigned))};T.rotl=T.rotateLeft;T.rotateRight=function(t){var e;return _(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,B(this.low<>>t,this.high<>>t,this.unsigned))};T.rotr=T.rotateRight;T.toSigned=function(){return this.unsigned?B(this.low,this.high,!1):this};T.toUnsigned=function(){return this.unsigned?this:B(this.low,this.high,!0)};T.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};T.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};T.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};O.fromBytes=function(t,e,r){return r?O.fromBytesLE(t,e):O.fromBytesBE(t,e)};O.fromBytesLE=function(t,e){return new O(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};O.fromBytesBE=function(t,e){return new O(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var H=(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))(H||{});class U extends sn{constructor(e,r){super(r);a(this,"valueType");a(this,"value");this.valueType=U.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,r){return new U(e,r)}static valueFromBytes(e,r){switch(e){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 O.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(O.fromBytesLE(Array.from(r),!0).toNumber());default:throw new m(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Ve(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=U.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":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof O)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return U.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===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 e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!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 e=this.value,r=O.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new m(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Kn extends Oo{constructor(e){super(e);a(this,"prev");a(this,"next");this.value=e}static createAfter(e,r){const s=new Kn(r),i=e.next;return e.next=s,s.prev=e,s.next=i,i&&(i.prev=s),s}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()}}class en{constructor(){a(this,"dummyHead");a(this,"last");a(this,"nodeMapByIndex");a(this,"nodeMapByCreatedAt");const t=U.of(0,Ne);t.setRemovedAt(Ne),this.dummyHead=new Kn(t),this.last=this.dummyHead,this.nodeMapByIndex=new _r,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new en}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new m(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(e);)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,e,r=e.getCreatedAt()){const s=this.findNextBeforeExecutedAt(t,r),i=Kn.createAfter(s,e);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(t,e,r){const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new m(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new m(d.ErrInvalidArgument,`cant find the given node: ${e.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(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new m(d.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,r]=this.nodeMapByIndex.find(t);let s=e;if(t===0&&e===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const r=this.nodeMapByCreatedAt.get(t.toIDString()),s=r.isRemoved();return r.remove(e)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,e){const r=this.getByIndex(t);if(r)return r.remove(e)&&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 e of this){const r=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.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 ae extends ar{constructor(e,r){super(e);a(this,"elements");this.elements=r}static create(e,r){if(!r)return new ae(e,en.create());const s=en.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new ae(e,s)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,r){this.elements.insertAfter(e,r)}moveAfter(e,r,s){this.elements.moveAfter(e,r,s)}get(e){const r=this.elements.getByIndex(e);return r==null?void 0:r.getValue()}getByID(e){const r=this.elements.getByID(e);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,r){return this.elements.delete(e,r)}deleteByIndex(e,r){return this.elements.deleteByIndex(e,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const r of this.elements){const s=r.getValue();if(e(s,this))return;s instanceof ar&&s.getDescendants(e)}}toJSON(){const e=[];for(const r of this)e.push(r.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let r=0;r({...w,value:w.value?{attributes:Cr(w.value.getAttributes()),content:w.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[f,p,g,[h,h]]}setStyle(e,r,s,i,o){const[,c]=this.rgaTreeSplit.findNodeWithSplit(e[1],s),[,l]=this.rgaTreeSplit.findNodeWithSplit(e[0],s),h=[],f=this.rgaTreeSplit.findBetween(l,c),g=new Map,v=[];for(const w of f){const b=w.getCreatedAt().getActorID();let x,C=0n;if(o===void 0&&i===void 0?C=jr:o.size()>0?C=o.get(b)?o.get(b):0n:x=i.has(b)?i.get(b):Ne,w.canStyle(s,x,C)){const P=g.get(b),L=w.getCreatedAt();(!P||L.after(P))&&g.set(b,L),v.push(w)}}const p=[];for(const w of v){if(w.isRemoved())continue;const[b,x]=this.rgaTreeSplit.findIndexesFromRange(w.createPosRange());h.push({type:"style",actor:s.getActorID(),from:b,to:x,value:{attributes:Cr(r)}});for(const[C,P]of Object.entries(r)){const[L]=w.getValue().setAttr(C,P,s);L!==void 0&&p.push({parent:w.getValue(),child:L})}}return[g,p,h]}indexRangeToPosRange(e,r){const s=this.rgaTreeSplit.indexToPos(e);return e===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 e=[];for(const r of this.rgaTreeSplit)r.isRemoved()||e.push(r.getValue().toJSON());return`[${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(){const e=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();e.push({attributes:Cr(s.getAttributes()),content:s.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Ie(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())e.push(s)}return e}}class an extends Pe{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"content");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=c}static create(e,r,s,i,o,c,l){return new an(e,r,s,i,o,c,l)}execute(e,r,s){const i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new m(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Ie))throw new m(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=i,[,c,l]=o.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,s);for(const h of l)e.registerGCPair(h);return{opInfos:c.map(({from:h,to:f,value:g})=>({type:"edit",from:h,to:f,value:g,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${e}.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 cn extends Pe{constructor(e,r,s,i,o,c){super(e,c);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(e,r,s,i,o,c){return new cn(e,r,s,i,o,c)}execute(e,r,s){const i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new m(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Ie))throw new m(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=i,[,c,l]=o.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,s);for(const h of c)e.registerGCPair(h);return{opInfos:l.map(({from:h,to:f,value:g})=>({type:"style",from:h,to:f,value:g,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${e}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Uc=2,qc="root",Zt="text";function qr(n,t){let e=0;const r=n.children;for(let s=0;s0)throw new m(d.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const r=e.updateDescendantsSize();e.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===Zt}get paddedSize(){return this.size+(this.isText?0:Uc)}isAncestorOf(t){return Vc(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const r=this.value.slice(0,t),s=this.value.slice(t);if(!s.length)return;this.value=r;const i=this.cloneText(t+e);return i.value=s,this.parent.insertAfterInternal(i,this),i}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 m(d.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new m(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new m(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new m(d.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const r=this.cloneElement(e);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,t),i=this.children.slice(t);this._children=s,r._children=i,this.size=this._children.reduce((o,c)=>o+c.paddedSize,0),r.size=r._children.reduce((o,c)=>o+c.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(t,e){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new m(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,e){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(s=>!s.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new m(d.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const r=this._children.indexOf(e);if(r!==-1)return r;e=e.parent}return-1}}function Vc(n,t){if(n===t)return!1;for(;t.parent;){if(t.parent===n)return!0;t=t.parent}return!1}var W=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(W||{});function Fo(n,t,e,r){if(t>e)throw new m(d.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>n.size)throw new m(d.ErrInvalidArgument,`from is out of range: ${t} > ${n.size}`);if(e>n.size)throw new m(d.ErrInvalidArgument,`to is out of range: ${e} > ${n.size}`);if(t===e)return;let s=0;for(const i of n.children){if(t-i.paddedSizei.size;(i.isText||l)&&r([i,i.isText?"Text":"Start"],h),Fo(i,Math.max(0,o),Math.min(c,i.size),r),h&&r([i,"End"],h)}s+=i.paddedSize}}function Mo(n,t,e=0){for(const r of n.children)Mo(r,t,e+1);t(n,e)}function Zn(n,t,e=0){for(const r of n._children)Zn(r,t,e+1);t(n,e)}function Ms(n,t,e=!0){if(t>n.size)throw new m(d.ErrInvalidArgument,`index is out of range: ${t} > ${n.size}`);if(n.isText)return{node:n,offset:t};let r=0,s=0;for(const i of n.children){if(e&&i.isText&&i.size>=t-s)return Ms(i,t-s,e);if(t===s)return{node:n,offset:r};if(!e&&i.paddedSize===t-s)return{node:n,offset:r+1};if(i.paddedSize>t-s)return Ms(i,t-s-1,e);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function $o(n){return n.isText||n.children.length===0?n:$o(n.children[0])}function Kc(n,t){if(n.sizen===t?0:n0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(r<0)if(e.left)e.left.parent=e,e=e.left;else{let s=e.parent,i=e;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return e}}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,e){for(;e;){const r=this.comparator(t,e.key);if(r===0)return e;r<0?e=e.left:r>0&&(e=e.right)}}putInternal(t,e,r){if(!r)return this.counter+=1,new Wc(t,e,!0);const s=this.comparator(t,r.key);return s<0?r.left=this.putInternal(t,e,r.left):s>0?r.right=this.putInternal(t,e,r.right):r.value=e,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,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,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(e,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,e)}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 e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Ee{constructor(t,e){a(this,"parentID");a(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new Ee(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:r}=t,s;return r.isText?(r.parent.children[0]===r&&e===0?s=r.parent:s=r,r=r.parent):e===0?s=r:s=r.children[e-1],Ee.of(r.id,Z.of(s.getCreatedAt(),s.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return Ee.of(Z.of(be.fromStruct(t.parentID.createdAt),t.parentID.offset),Z.of(be.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 e=this.getParentID(),r=this.getLeftSiblingID(),s=t.findFloorNode(e);let i=t.findFloorNode(r);if(!s||!i)throw new m(d.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${r.toTestString()})`);return!r.equals(e)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=t.findFloorNode(i.insPrevID)),[s,i]}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 Z{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Z(t,e)}static fromStruct(t){return Z.of(be.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const r=t.getCreatedAt().compare(e.getCreatedAt());return r!==0?r:t.getOffset()>e.getOffset()?1:t.getOffset(){const i=s.deepcopy();return i.parent=e,i}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new m(d.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new m(d.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),r&&this.updateAncestorsSize()}cloneText(e){return new oe(Z.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new oe(Z.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,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=e.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,e.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,r,s){return(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=s)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,r,s){return this.isText?!1:(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=s)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,r){this.attrs||(this.attrs=new er);const s=[];for(const[i,o]of Object.entries(e))s.push(this.attrs.set(i,o,r));return s}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const r of this.attrs)r.getRemovedAt()&&e.push({parent:this,child:r});return e}}function $s(n){var e;if(n.isText){const r=n;return{type:r.type,value:r.value}}const t={type:n.type,children:n.children.map($s)};return n.attrs&&(t.attributes=Cr((e=n.attrs)==null?void 0:e.toObject())),t}function Hs(n){if(n.isText)return n.value;let t="";return n.attrs&&n.attrs.size()&&(t=" "+Array.from(n.attrs).filter(e=>!e.isRemoved()).sort((e,r)=>e.getKey().localeCompare(r.getKey())).map(e=>{const r=JSON.parse(e.getValue());return typeof r=="string"?`${e.getKey()}="${r}"`:`${e.getKey()}="${Ve(e.getValue())}"`}).join(" ")),`<${n.type}${t}>${n.children.map(e=>Hs(e)).join("")}`}function qo(n){if(n.isText){const t=n;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:n.type,children:n.children.map(qo),size:n.size,isRemoved:n.isRemoved}}class Se extends sn{constructor(e,r){super(r);a(this,"indexTree");a(this,"nodeMapByID");this.indexTree=new jc(e),this.nodeMapByID=new Uo(Z.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(e,r){return new Se(e,r)}findFloorNode(e){const r=this.nodeMapByID.floorEntry(e);if(!(!r||!r.key.getCreatedAt().equals(e.getCreatedAt())))return r.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,r){const[s,i]=e.toTreeNodePair(this);let o=i;const c=s===o,l=o.parent&&!c?o.parent:s;if(o.isText&&o.split(this,e.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const h=l.allChildren,f=c?0:h.indexOf(o)+1;for(let g=f;g{const x=b.getCreatedAt().getActorID();let C,P=0n;if(o===void 0&&i===void 0?P=jr:o.size()>0?P=o.get(x)?o.get(x):0n:C=i.has(x)?i.get(x):Ne,b.canStyle(s,C,P)&&r){const L=p.get(x),Y=b.getCreatedAt();(!L||Y.after(L))&&p.set(x,Y);const D=b.setAttrs(r,s),F=D.reduce((ue,[,Ge])=>(Ge&&(ue[Ge.getKey()]=v[Ge.getKey()]),ue),{}),V=b.parent,K=b.prevSibling||b.parent;Object.keys(F).length>0&&g.push({type:"style",from:this.toIndex(V,K),to:this.toIndex(b,b),fromPath:this.toPath(V,K),toPath:this.toPath(b,b),actor:s.getActorID(),value:F});for(const[ue]of D)ue&&w.push({parent:b,child:ue})}}),[p,w,g]}removeStyle(e,r,s,i,o){const[c,l]=this.findNodesAndSplitText(e[0],s),[h,f]=this.findNodesAndSplitText(e[1],s),g=[],v=new Map,p=[];return this.traverseInPosRange(c,l,h,f,([w])=>{const b=w.getCreatedAt().getActorID();let x,C=0n;if(o===void 0&&i===void 0?C=jr:o.size()>0?C=o.get(b)?o.get(b):0n:x=i.has(b)?i.get(b):Ne,w.canStyle(s,x,C)&&r){const P=v.get(b),L=w.getCreatedAt();(!P||L.after(P))&&v.set(b,L),w.attrs||(w.attrs=new er);for(const F of r){const V=w.attrs.remove(F,s);for(const K of V)p.push({parent:w,child:K})}const Y=w.parent,D=w.prevSibling||w.parent;g.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(Y,D),to:this.toIndex(w,w),fromPath:this.toPath(Y,D),toPath:this.toPath(w,w),value:r})}}),[v,p,g]}edit(e,r,s,i,o,c,l){const[h,f]=this.findNodesAndSplitText(e[0],i),[g,v]=this.findNodesAndSplitText(e[1],i),p=this.toIndex(h,f),w=this.toPath(h,f),b=[],x=[],C=[],P=new Map;this.traverseInPosRange(h,f,g,v,([D,F],V)=>{if(F===W.Start&&!V)for(const br of D.children)C.push(br);const K=D.getCreatedAt().getActorID();let ue,Ge=0n;if(l===void 0&&c===void 0?Ge=jr:l.size()>0?Ge=l.get(K)?l.get(K):0n:ue=c.has(K)?c.get(K):Ne,D.canDelete(i,ue,Ge)||b.includes(D.parent)){const br=P.get(K),ai=D.getCreatedAt();(!br||ai.after(br))&&P.set(K,ai),(F===W.Text||F===W.Start)&&b.push(D),x.push([D,F])}});const L=this.makeDeletionChanges(x,i),Y=[];for(const D of b)D.remove(i),D.isRemoved&&Y.push({parent:this,child:D});for(const D of C)D.removedAt||h.append(D);if(s>0){let D=0,F=h,V=f;for(;D{h.isRemoved&&(K.remove(i),Y.push({parent:this,child:K})),this.nodeMapByID.put(K.id,K)}),V.isRemoved||D.push(V);if(D.length){const V=D.map(K=>$s(K));L.length&&L[L.length-1].from===p?L[L.length-1].value=V:L.push({type:"content",from:p,to:p,fromPath:w,toPath:w,actor:i.getActorID(),value:V})}}return[L,Y,P]}editT(e,r,s,i,o){const c=this.findPos(e[0]),l=this.findPos(e[1]);this.edit([c,l],r,s,i,o)}move(e,r,s){throw new m(d.ErrUnimplemented,`not implemented: ${e}, ${r}, ${s}`)}purge(e){var i;(i=e.parent)==null||i.removeChild(e),this.nodeMapByID.remove(e.id);const r=e.insPrevID,s=e.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&e.push({parent:this,child:r});for(const s of r.getGCPairs())e.push(s)}),e}findPos(e,r=!0){const s=this.indexTree.findTreePos(e,r);return Ee.fromTreePos(s)}pathToPosRange(e){const r=this.pathToIndex(e);return[this.findPos(r),this.findPos(r+1)]}pathToPos(e){const r=this.indexTree.pathToIndex(e);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 Hs(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 e=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,c=0)=>{var p,w,b,x;let l,h,f;const g=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;g&&(l=this.indexTree.indexOf(g),h=this.indexTree.treePosToPath(g),f=Ee.fromTreePos(g).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(p=s.removedAt)==null?void 0:p.toTestString(),insPrev:(w=s.insPrevID)==null?void 0:w.toTestString(),insNext:(b=s.insNextID)==null?void 0:b.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:c,attributes:s.attrs?Cr((x=s.attrs)==null?void 0:x.toObject()):void 0,index:l,path:h,pos:f};for(let C=0;C0&&C===s[s.length-1].to?(s[s.length-1].to=P,s[s.length-1].toPath=this.toPath(x,p)):s.push({type:"content",from:C,to:P,fromPath:this.toPath(b,g),toPath:this.toPath(x,p),actor:r.getActorID()}))}return s.reverse()}findRightToken([e,r]){if(r===W.Start){const l=e.allChildren;return l.length>0?[l[0],l[0].isText?W.Text:W.Start]:[e,W.End]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===i.length-1)return[s,W.End];const c=i[o+1];return[c,c.isText?W.Text:W.Start]}findLeftToken([e,r]){if(r===W.End){const l=e.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?W.Text:W.End]}return[e,W.Start]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===0)return[s,W.Start];const c=i[o-1];return[c,c.isText?W.Text:W.End]}}class un extends Pe{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"contents");a(this,"splitLevel");a(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=c}static create(e,r,s,i,o,c,l){return new un(e,r,s,i,o,c,l)}execute(e,r,s){var f;const i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new m(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Se))throw new m(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=this.getExecutedAt(),c=i,[l,h]=c.edit([this.fromPos,this.toPos],(f=this.contents)==null?void 0:f.map(g=>g.deepcopy()),this.splitLevel,o,(()=>{let g=o.getDelimiter();return this.contents!==void 0&&(g+=this.contents.length),()=>be.of(o.getLamport(),++g,o.getActorID())})(),this.maxCreatedAtMapByActor,s);for(const g of h)e.registerGCPair(g);return{opInfos:l.map(({from:g,to:v,value:p,splitLevel:w,fromPath:b,toPath:x})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:g,to:v,value:p,splitLevel:w,fromPath:b,toPath:x}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=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`${e}.EDIT(${r},${s},${i.map(o=>Hs(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Pr{constructor(t){a(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}unset(t){this.vector.delete(t)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[r,s]of t){const i=this.vector.get(r),o=i&&i>s?i:s;e.set(r,o)}for(const[r,s]of this){const i=t.get(r),o=i&&i>s?i:s;e.set(r,o)}return new Pr(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,r]of this.vector)t.set(e,r);return new Pr(t)}filter(t){const e=new Map;for(const[r]of t){const s=this.vector.get(r);s!==void 0&&e.set(r,s)}return new Pr(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Yc=new Pr(new Map);class Gt{constructor(t,e,r,s,i){a(this,"clientSeq");a(this,"serverSeq");a(this,"lamport");a(this,"actor");a(this,"versionVector");this.clientSeq=t,this.serverSeq=i,this.lamport=e,this.versionVector=s,this.actor=r}static of(t,e,r,s,i){return new Gt(t,e,r,s,i)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new Gt(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n;let r=t.versionVector;r.size()===0&&(r=r.deepcopy(),r.set(t.actor,t.lamport));const s=this.versionVector.max(r),i=new Gt(this.clientSeq,e,this.actor,s);return i.versionVector.set(this.actor,e),i}setClocks(t,e){const r=t>this.lamport?t+1n:this.lamport+1n;e.unset(Xn);const s=this.versionVector.max(e);return s.set(this.actor,r),Gt.of(this.clientSeq,r,this.actor,s)}createTimeTicket(t){return be.of(this.lamport,t,this.actor)}setActor(t){return new Gt(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new Gt(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Xc=new Gt(0,0n,Xn,Yc);class Fr{constructor({id:t,operations:e,presenceChange:r,message:s}){a(this,"id");a(this,"operations");a(this,"presenceChange");a(this,"message");this.id=t,this.operations=e||[],this.presenceChange=r,this.message=s}static create({id:t,operations:e,presenceChange:r,message:s}){return new Fr({id:t,operations:e,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,r){const s=[],i=[];for(const o of this.operations){const c=o.execute(t,r,this.id.getVersionVector());if(!c)continue;const{opInfos:l,reverseOp:h}=c;s.push(...l),h&&i.unshift(h)}return this.presenceChange&&(this.presenceChange.type===lr.Put?e.set(this.id.getActorID(),ke(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:j.bytesToHex(j.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>j.bytesToHex(j.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:r,presenceChange:s,message:i}=t;return Fr.create({id:j.bytesToChangeID(j.hexToBytes(e)),operations:r==null?void 0:r.map(o=>j.bytesToOperation(j.hexToBytes(o))),presenceChange:s,message:i})}}class Qn{constructor(t,e,r,s,i,o,c){a(this,"documentKey");a(this,"checkpoint");a(this,"isRemoved");a(this,"changes");a(this,"snapshot");a(this,"minSyncedTicket");a(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=r,this.changes=s,this.snapshot=o,this.minSyncedTicket=c,this.versionVector=i}static create(t,e,r,s,i,o,c){return new Qn(t,e,r,s,i,o,c)}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}getVersionVector(){return this.versionVector}}class Dr{constructor(t,e){a(this,"serverSeq");a(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Dr(t,e)}increaseClientSeq(t){return t===0?this:new Dr(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Dr.of(e,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Zc=new Dr(0n,0);class Ke{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Ke(t,e)}static fromStruct(t){return Ke.of(be.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 Ke(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 Qc=Ke.of(Ne,0);class Ce{constructor(t,e){a(this,"id");a(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new Ce(t,e)}static fromStruct(t){const e=Ke.fromStruct(t.id);return Ce.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ke.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 cr extends Oo{constructor(e,r,s){super(r);a(this,"id");a(this,"removedAt");a(this,"prev");a(this,"next");a(this,"insPrev");a(this,"insNext");this.id=e,this.removedAt=s}static create(e,r){return new cr(e,r)}static createComparator(){return(e,r)=>{const s=e.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:e.getOffset()>r.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const r=[];let s=t;for(;s&&s!==e;)r.push(s),s=s.getNext();return r}splitNode(t,e){if(e>t.getContentLength())throw new m(d.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const r=t.split(e);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const s=t.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,e,r,s){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,e,r,s),c=new Map,l=new Map,h=this.makeChanges(o,e);for(const f of i){const g=f.getCreatedAt().getActorID();(!c.has(g)||f.getID().getCreatedAt().after(c.get(g)))&&c.set(g,f.getID().getCreatedAt()),l.set(f.getID().toIDString(),f),f.remove(e)}return this.deleteIndexNodes(o),[h,c,l]}filterNodes(t,e,r,s){const i=[],o=[],[c,l]=this.findEdgesOfCandidates(t);o.push(c);for(const h of t){const f=h.getCreatedAt().getActorID();let g,v=0n;s===void 0&&r===void 0?v=jr:s.size()>0?v=s.get(f)?s.get(f):0n:g=r.has(f)?r.get(f):Ne,h.canDelete(e,g,v)?i.push(h):o.push(h)}return o.push(l),[i,o]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var je=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(je||{});class ce extends sn{constructor(e,r,s){super(s);a(this,"valueType");a(this,"value");switch(this.valueType=e,e){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=O.fromNumber(r).toInt():this.value=ji(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=O.fromNumber(r):this.value=r;break;default:throw new m(d.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,r,s){return new ce(e,r,s)}static valueFromBytes(e,r){switch(e){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return O.fromBytesLE(Array.from(r));default:throw new m(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=ce.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":return e instanceof O?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!ce.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new m(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===H.Long?this.value=this.value+e.getValue().toInt():this.value=O.fromNumber(this.value+ji(e.getValue())).toInt(),this}}class $r extends Pe{constructor(e,r,s){super(e,s);a(this,"value");this.value=r}static create(e,r,s){return new $r(e,r,s)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new m(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ce))throw new m(d.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),s=e.getType()===H.Long?e.getValue().multiply(-1):e.getValue()*-1;return $r.create(this.getParentCreatedAt(),U.of(s,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Qt extends Pe{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");a(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=c}static create(e,r,s,i,o,c){return new Qt(e,r,s,i,o,[],c)}static createTreeRemoveStyleOperation(e,r,s,i,o,c){return new Qt(e,r,s,i,new Map,o,c)}execute(e,r,s){const i=e.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new m(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Se))throw new m(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=i;let c,l;if(this.attributes.size){const h={};[...this.attributes].forEach(([f,g])=>h[f]=g),[,l,c]=o.style([this.fromPos,this.toPos],h,this.getExecutedAt(),this.maxCreatedAtMapByActor,s)}else{const h=this.attributesToRemove;[,l,c]=o.removeStyle([this.fromPos,this.toPos],h,this.getExecutedAt(),this.maxCreatedAtMapByActor,s)}for(const h of l)e.registerGCPair(h);return{opInfos:c.map(({from:h,to:f,value:g,fromPath:v,toPath:p})=>({type:"tree-style",from:h,to:f,value:this.attributes.size?{attributes:g}:{attributesToRemove:g},fromPath:v,toPath:p,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.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 _c(n){const t=new js,e=t.data;for(const[r,s]of Object.entries(n))e[r]=JSON.stringify(s);return t}function eu(n){if(n.type===lr.Put)return new Zr({type:wr.PUT,presence:_c(n.presence)});if(n.type===lr.Clear)return new Zr({type:wr.CLEAR});throw new m(d.ErrUnimplemented,"unimplemented type")}function tu(n){return new Co({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function zo(n){return new Hn({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ii(n.getActorID()),versionVector:Ys(n.getVersionVector())})}function S(n){if(n)return new I({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ii(n.getActorID())})}function Ys(n){if(!n)return;const t=new Yn;for(const[e,r]of n)t.vector[e]=BigInt(r.toString());return t}function Vo(n){switch(n){case H.Null:return N.NULL;case H.Boolean:return N.BOOLEAN;case H.Integer:return N.INTEGER;case H.Long:return N.LONG;case H.Double:return N.DOUBLE;case H.String:return N.STRING;case H.Bytes:return N.BYTES;case H.Date:return N.DATE;default:throw new m(d.ErrInvalidType,`unsupported type: ${n}`)}}function Ko(n){switch(n){case je.IntegerCnt:return N.INTEGER_CNT;case je.LongCnt:return N.LONG_CNT;default:throw new m(d.ErrInvalidType,`unsupported type: ${n}`)}}function as(n){if(n instanceof ne)return new le({type:N.JSON_OBJECT,createdAt:S(n.getCreatedAt()),value:na(n)});if(n instanceof ae)return new le({type:N.JSON_ARRAY,createdAt:S(n.getCreatedAt()),value:Ou(n)});if(n instanceof Ie)return new le({type:N.TEXT,createdAt:S(n.getCreatedAt())});if(n instanceof U)return new le({type:Vo(n.getType()),createdAt:S(n.getCreatedAt()),value:n.toBytes()});if(n instanceof ce)return new le({type:Ko(n.getType()),createdAt:S(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Se)return new le({type:N.TREE,createdAt:S(n.getCreatedAt()),value:Ru(n)});throw new m(d.ErrUnimplemented,"unimplemented element")}function ru(n){return new Yr({createdAt:S(n.getCreatedAt()),offset:n.getOffset()})}function hn(n){return new _t({createdAt:S(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function fn(n){return new vr({parentId:Gr(n.getParentID()),leftSiblingId:Gr(n.getLeftSiblingID())})}function Gr(n){return new or({createdAt:S(n.getCreatedAt()),offset:n.getOffset()})}function jo(n){const t=new Ks;if(n instanceof Tr){const e=n,r=new kn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.key=e.getKey(),r.value=as(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(n instanceof on){const e=n,r=new xn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.prevCreatedAt=S(e.getPrevCreatedAt()),r.value=as(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(n instanceof ir){const e=n,r=new En;r.parentCreatedAt=S(e.getParentCreatedAt()),r.prevCreatedAt=S(e.getPrevCreatedAt()),r.createdAt=S(e.getCreatedAt()),r.executedAt=S(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(n instanceof hr){const e=n,r=new Nn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.createdAt=S(e.getCreatedAt()),r.executedAt=S(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(n instanceof an){const e=n,r=new Cn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=hn(e.getFromPos()),r.to=hn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=S(c);r.content=e.getContent();const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=S(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(n instanceof cn){const e=n,r=new Pn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=hn(e.getFromPos()),r.to=hn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=S(c);const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=S(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(n instanceof $r){const e=n,r=new Dn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.value=as(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(n instanceof un){const e=n,r=new On,s=r.createdAtMapByActor;for(const[i,o]of e.getMaxCreatedAtMapByActor())s[i]=S(o);r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=fn(e.getFromPos()),r.to=fn(e.getToPos()),r.contents=uu(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=S(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(n instanceof Qt){const e=n,r=new Bn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=fn(e.getFromPos()),r.to=fn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=S(c);const i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[c,l]of e.getAttributes())o[c]=l}r.executedAt=S(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new m(d.ErrUnimplemented,"unimplemented operation");return t}function nu(n){const t=[];for(const e of n)t.push(jo(e));return t}function su(n){const t=new Eo({id:zo(n.getID()),message:n.getMessage()});return n.hasOperations()&&(t.operations=nu(n.getOperations())),n.hasPresenceChange()&&(t.presenceChange=eu(n.getPresenceChange())),t}function iu(n){const t=[];for(const e of n)t.push(su(e));return t}function ou(n){const t=[];for(const e of n)t.push(new No({key:e.getStrKey(),element:Zs(e.getValue())}));return t}function au(n){const t=[];for(const e of n)t.push(new Un({element:Zs(e.getValue())}));return t}function cu(n){const t=[];for(const e of n){const r=new qn;r.id=ru(e.getID()),r.value=e.getValue().getContent(),r.removedAt=S(e.getRemovedAt());const s=r.attributes,i=e.getValue().getAttrs();for(const o of i){const c=new Rr;c.value=o.getValue(),c.updatedAt=S(o.getUpdatedAt()),s[o.getKey()]=c}t.push(r)}return t}function uu(n){const t=[];if(!n||!n.length)return t;for(const e of n)t.push(new zn({content:Xs(e)}));return t}function lu(n){const t={};for(const e of n)t[e.getKey()]=new Rr({value:e.getValue(),updatedAt:S(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Xs(n){if(!n)return[];const t=[];return Zn(n,(e,r)=>{const s=new Xr({id:Gr(e.id),type:e.type,removedAt:S(e.removedAt),depth:r});e.isText&&(s.value=e.value),e.insPrevID&&(s.insPrevId=Gr(e.insPrevID)),e.insNextID&&(s.insNextId=Gr(e.insNextID)),e.attrs&&(s.attributes=lu(e.attrs)),t.push(s)}),t}function hu(n){const t=new se;return t.body.case="jsonObject",t.body.value=new Rn({nodes:ou(n.getRHT()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Go(n){const t=new se;return t.body.case="jsonArray",t.body.value=new Ln({nodes:au(n.getElements()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function fu(n){const t=new se;return t.body.case="primitive",t.body.value=new Jn({type:Vo(n.getType()),value:n.toBytes(),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function du(n){const t=new se;return t.body.case="text",t.body.value=new Fn({nodes:cu(n.getRGATreeSplit()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function gu(n){const t=new se;return t.body.case="counter",t.body.value=new Mn({type:Ko(n.getType()),value:n.toBytes(),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Wo(n){const t=new se;return t.body.case="tree",t.body.value=new $n({nodes:Xs(n.getRoot()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Zs(n){if(n instanceof ne)return hu(n);if(n instanceof ae)return Go(n);if(n instanceof U)return fu(n);if(n instanceof Ie)return du(n);if(n instanceof ce)return gu(n);if(n instanceof Se)return Wo(n);throw new m(d.ErrUnimplemented,"unimplemented element")}function mu(n){return new tr({documentKey:n.getDocumentKey(),checkpoint:tu(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:iu(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Ys(n.getVersionVector()),minSyncedTicket:S(n.getMinSyncedTicket())})}function zr(n){if(!(n instanceof M))return{};const t=n.findDetails(Rc);for(const e of t)return e.metadata;return{}}function Sr(n){return zr(n).code??""}function Ho(n){return Gt.of(n.clientSeq,BigInt(n.lamport),ni(n.actorId),Qs(n.versionVector),BigInt(n.serverSeq))}function Qs(n){if(!n)return;const t=new Pr;return Object.entries(n.vector).forEach(([e,r])=>{t.set(e,BigInt(r.toString()))}),t}function k(n){if(n)return be.of(BigInt(n.lamport),n.delimiter,ni(n.actorId))}function _s(n){const t={};return Object.entries(n.data).forEach(([e,r])=>{t[e]=JSON.parse(r)}),t}function pu(n){const t=n.type;if(t===wr.PUT){const e=_s(n.presence);return{type:lr.Put,presence:e}}if(t===wr.CLEAR)return{type:lr.Clear};throw new m(d.ErrInvalidType,`unsupported type: ${t}`)}function yu(n){const t=new Map;return Object.entries(n).forEach(([e,r])=>{t.set(e,_s(r))}),t}function Yo(n){switch(n){case N.NULL:return H.Null;case N.BOOLEAN:return H.Boolean;case N.INTEGER:return H.Integer;case N.LONG:return H.Long;case N.DOUBLE:return H.Double;case N.STRING:return H.String;case N.BYTES:return H.Bytes;case N.DATE:return H.Date}throw new m(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function jn(n){switch(n){case N.INTEGER_CNT:return je.IntegerCnt;case N.LONG_CNT:return je.LongCnt}throw new m(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function cs(n){switch(n.type){case N.JSON_OBJECT:return n.value?ra(n.value):ne.create(k(n.createdAt));case N.JSON_ARRAY:return n.value?Du(n.value):ae.create(k(n.createdAt));case N.TEXT:return Ie.create(Mr.create(),k(n.createdAt));case N.TREE:return Bu(n.value);case N.NULL:case N.BOOLEAN:case N.INTEGER:case N.LONG:case N.DOUBLE:case N.STRING:case N.BYTES:case N.DATE:return U.of(U.valueFromBytes(Yo(n.type),n.value),k(n.createdAt));case N.INTEGER_CNT:case N.LONG_CNT:return ce.create(jn(n.type),ce.valueFromBytes(jn(n.type),n.value),k(n.createdAt))}}function dn(n){return Ce.of(Ke.of(k(n.createdAt),n.offset),n.relativeOffset)}function Xo(n){return Ke.of(k(n.createdAt),n.offset)}function vu(n){const t=tn.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{t.setAttr(r,s.value,k(s.updatedAt))});const e=cr.create(Xo(n.id),t);return e.remove(k(n.removedAt)),e}function kr(n){return Ee.of(Wr(n.parentId),Wr(n.leftSiblingId))}function Wr(n){return Z.of(k(n.createdAt),n.offset)}function wu(n){if(!n.length)return;const t=[];return n.forEach(e=>{const r=ei(e.content);t.push(r)}),t}function ei(n){if(n.length===0)return;const t=[];for(const s of n)t.push(Au(s));const e=t[t.length-1],r=new Map;r.set(n[t.length-1].depth,t[t.length-1]);for(let s=t.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(t[s]),r.set(n[s].depth,t[s]);return e.updateDescendantsSize(),Se.create(e,Ne).getRoot()}function Tu(n){const t=er.create();for(const[e,r]of Object.entries(n))t.setInternal(e,r.value,k(r.updatedAt),r.isRemoved);return t}function Au(n){const t=Wr(n.id),e=oe.create(t,n.type),r=Object.entries(n.attributes);return e.isText?e.value=n.value:r.length&&(e.attrs=Tu(n.attributes)),n.insPrevId&&(e.insPrevID=Wr(n.insPrevId)),n.insNextId&&(e.insNextID=Wr(n.insNextId)),e.removedAt=k(n.removedAt),e}function Zo(n){if(n.body.case==="set"){const t=n.body.value;return Tr.create(t.key,cs(t.value),k(t.parentCreatedAt),k(t.executedAt))}else if(n.body.case==="add"){const t=n.body.value;return on.create(k(t.parentCreatedAt),k(t.prevCreatedAt),cs(t.value),k(t.executedAt))}else if(n.body.case==="move"){const t=n.body.value;return ir.create(k(t.parentCreatedAt),k(t.prevCreatedAt),k(t.createdAt),k(t.executedAt))}else if(n.body.case==="remove"){const t=n.body.value;return hr.create(k(t.parentCreatedAt),k(t.createdAt),k(t.executedAt))}else if(n.body.case==="edit"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,k(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),an.create(k(t.parentCreatedAt),dn(t.from),dn(t.to),e,t.content,r,k(t.executedAt))}else if(n.body.case==="style"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,k(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),cn.create(k(t.parentCreatedAt),dn(t.from),dn(t.to),e,r,k(t.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const t=n.body.value;return $r.create(k(t.parentCreatedAt),cs(t.value),k(t.executedAt))}else if(n.body.case==="treeEdit"){const t=n.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,s])=>{e.set(r,k(s))}),un.create(k(t.parentCreatedAt),kr(t.from),kr(t.to),wu(t.contents),t.splitLevel,e,k(t.executedAt))}else if(n.body.case==="treeStyle"){const t=n.body.value,e=new Map,r=t.attributesToRemove,s=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{s.set(i,k(o))}),(r==null?void 0:r.length)>0?Qt.createTreeRemoveStyleOperation(k(t.parentCreatedAt),kr(t.from),kr(t.to),s,r,k(t.executedAt)):(Object.entries(t.attributes).forEach(([i,o])=>{e.set(i,o)}),Qt.create(k(t.parentCreatedAt),kr(t.from),kr(t.to),s,e,k(t.executedAt)))}else throw new m(d.ErrUnimplemented,"unimplemented operation")}}function bu(n){const t=[];for(const e of n){const r=Zo(e);r&&t.push(r)}return t}function Qo(n){const t=[];for(const e of n)t.push(Fr.create({id:Ho(e.id),operations:bu(e.operations),presenceChange:e.presenceChange?pu(e.presenceChange):void 0,message:e.message}));return t}function Iu(n){return Dr.of(BigInt(n.serverSeq),n.clientSeq)}function Su(n){return Qn.create(n.documentKey,Iu(n.checkpoint),n.isRemoved,Qo(n.changes),Qs(n.versionVector),n.snapshot,k(n.minSyncedTicket))}function _o(n){const t=new Qr;for(const r of n.nodes){const s=ti(r.element);t.set(r.key,s,s.getPositionedAt())}const e=new ne(k(n.createdAt),t);return e.setMovedAt(k(n.movedAt)),e.setRemovedAt(k(n.removedAt)),e}function ea(n){const t=new en;for(const r of n.nodes)t.insert(ti(r.element));const e=new ae(k(n.createdAt),t);return e.setMovedAt(k(n.movedAt)),e.setRemovedAt(k(n.removedAt)),e}function ku(n){const t=U.of(U.valueFromBytes(Yo(n.type),n.value),k(n.createdAt));return t.setMovedAt(k(n.movedAt)),t.setRemovedAt(k(n.removedAt)),t}function xu(n){const t=new Mr;let e=t.getHead();for(const s of n.nodes){const i=t.insertAfter(e,vu(s));s.insPrevId&&i.setInsPrev(t.findNode(Xo(s.insPrevId))),e=i}const r=new Ie(t,k(n.createdAt));return r.setMovedAt(k(n.movedAt)),r.setRemovedAt(k(n.removedAt)),r}function Eu(n){const t=ce.create(jn(n.type),ce.valueFromBytes(jn(n.type),n.value),k(n.createdAt));return t.setMovedAt(k(n.movedAt)),t.setRemovedAt(k(n.removedAt)),t}function ta(n){const t=ei(n.nodes);return Se.create(t,k(n.createdAt))}function ti(n){if(n.body.case==="jsonObject")return _o(n.body.value);if(n.body.case==="jsonArray")return ea(n.body.value);if(n.body.case==="primitive")return ku(n.body.value);if(n.body.case==="text")return xu(n.body.value);if(n.body.case==="counter")return Eu(n.body.value);if(n.body.case==="tree")return ta(n.body.value);throw new m(d.ErrUnimplemented,"unimplemented element")}function Nu(n){if(!n)return{root:ne.create(Ne),presences:new Map};const t=gs.fromBinary(n);return{root:ti(t.root),presences:yu(t.presences)}}function Cu(n){const t=Ys(n);return ri(t.toBinary())}function Pu(n){const t=si(n),e=Yn.fromBinary(t);return Qs(e)}function ra(n){if(!n)throw new m(d.ErrInvalidArgument,"bytes is empty");const t=se.fromBinary(n);return _o(t.body.value)}function na(n){return Zs(n).toBinary()}function Du(n){if(!n)throw new m(d.ErrInvalidArgument,"bytes is empty");const t=se.fromBinary(n);return ea(t.body.value)}function Ou(n){return Go(n).toBinary()}function Bu(n){if(!n)throw new m(d.ErrInvalidArgument,"bytes is empty");const t=se.fromBinary(n);return ta(t.body.value)}function Ru(n){return Wo(n).toBinary()}function ri(n){return n?Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function ni(n){return ri(n)}function si(n){return new Uint8Array(n.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function ii(n){return si(n)}function Lu(n){const t=Hn.fromBinary(n);return Ho(t)}function Ju(n){const t=Ks.fromBinary(n);return Zo(t)}const j={fromPresence:_s,toChangePack:mu,fromChangePack:Su,fromChanges:Qo,toTreeNodes:Xs,fromTreeNodes:ei,objectToBytes:na,bytesToObject:ra,bytesToSnapshot:Nu,bytesToHex:ri,hexToBytes:si,toHexString:ni,toUint8Array:ii,toOperation:jo,toChangeID:zo,PbChangeID:Hn,bytesToChangeID:Lu,bytesToOperation:Ju,versionVectorToHex:Cu,hexToVersionVector:Pu};var te=(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))(te||{});let fr=3;function sa(n){fr=n}const E={trivial:(...n)=>{fr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{fr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{fr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{fr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{fr>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=>fr<=n};function ia(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}class Fu{constructor(t,e,r,s,i){a(this,"reconnectStreamDelay");a(this,"doc");a(this,"docID");a(this,"syncMode");a(this,"remoteChangeEventReceived");a(this,"watchStream");a(this,"watchLoopTimerID");a(this,"watchAbortController");a(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===bn.RealtimeSyncOff?!1:this.syncMode===bn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==bn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=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(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const us=()=>{};class Mu{constructor(t){a(this,"finalized",!1);a(this,"observers",[]);a(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let s;if(!t)throw new m(d.ErrInvalidArgument,"missing observer");if(this.finalized)throw new m(d.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?s=t:s={next:t,error:e,complete:r},s.next===void 0&&(s.next=us),s.error===void 0&&(s.error=us),s.complete===void 0&&(s.complete=us);const i=ia(),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(c){E.warn(c)}return o}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class Nr{constructor(t,e,r,s){a(this,"id");a(this,"delimiter");a(this,"message");a(this,"root");a(this,"operations");a(this,"presenceChange");a(this,"previousPresence");a(this,"reversePresenceKeys");this.id=t,this.delimiter=Do,this.root=e,this.operations=[],this.previousPresence=ke(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(t,e,r,s){return new Nr(t,e,r,s)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Fr.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,e){for(const r of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class rn{constructor(t){a(this,"rootObject");a(this,"elementPairMapByCreatedAt");a(this,"gcElementSetByCreatedAt");a(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Ie||e instanceof Se)for(const r of e.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new rn(ne.create(Ne))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const r=[];for(;e.parent;){const s=e.element.getCreatedAt(),i=e.parent.subPathOf(s);if(i===void 0)throw new m(d.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof ar&&t.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(t){let e=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),e++};return r(t),t instanceof ar&&t.getDescendants(s=>(r(s),!1)),e}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 e of this.gcElementSetByCreatedAt){t.add(e);const r=this.elementPairMapByCreatedAt.get(e);r.element instanceof ar&&r.element.getDescendants(s=>(t.add(s.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new rn(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r),i=s.element.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(s.parent.purge(s.element),e+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s&&(t!=null&&t.afterOrEqual(s))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function oa(n,t){const e=new nn(n);return new Proxy(t,e.getHandlers())}class nn{constructor(t){a(this,"context");a(this,"handlers");this.context=t,this.handlers={set:(e,r,s)=>(E.isEnabled(te.Trivial)&&E.trivial(`obj[${r}]=${JSON.stringify(s)}`),nn.setInternal(t,e,r,s),!0),get:(e,r)=>(E.isEnabled(te.Trivial)&&E.trivial(`obj[${r}]`),r==="getID"?()=>e.getCreatedAt():r==="toJSON"||r==="toString"?()=>e.toJSON():r==="toJS"?()=>e.toJS():r==="toJSForTest"?()=>e.toJSForTest():dr(t,e.get(r))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,r)=>(E.isEnabled(te.Trivial)&&E.trivial(`obj[${r}]`),nn.deleteInternal(t,e,r),!0)}}static setInternal(t,e,r,s){if(r.includes("."))throw new m(d.ErrInvalidObjectKey,"key must not contain the '.'.");const i=t.issueTimeTicket(),o=Gn(t,s,i),c=e.set(r,o,i);t.registerElement(o,e),c&&t.registerRemovedElement(c),t.push(Tr.create(r,o.deepcopy(),e.getCreatedAt(),i))}static buildObjectMembers(t,e){const r={};for(const[s,i]of Object.entries(e)){if(s.includes("."))throw new m(d.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),c=Gn(t,i,o);r[s]=c}return r}static deleteInternal(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByKey(r,s);i&&(t.push(hr.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i))}getHandlers(){return this.handlers}}function Uu(n,t){const e=new q(n,t);return new Proxy(t,e.getHandlers())}function qu(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zu(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class q{constructor(t,e){a(this,"context");a(this,"handlers");a(this,"array");this.context=t,this.array=e,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const c=r.getByID(o);if(!(!c||c.isRemoved()))return nr(t,c)}:s==="getElementByIndex"?o=>{const c=r.get(o);return nr(t,c)}:s==="getLast"?()=>nr(t,r.getLast()):s==="deleteByID"?o=>{const c=q.deleteInternalByID(t,r,o);return nr(t,c)}:s==="insertAfter"?(o,c)=>{const l=q.insertAfterInternal(t,r,o,c);return nr(t,l)}:s==="insertBefore"?(o,c)=>{const l=q.insertBeforeInternal(t,r,o,c);return nr(t,l)}:s==="moveBefore"?(o,c)=>{q.moveBeforeInternal(t,r,o,c)}:s==="moveAfter"?(o,c)=>{q.moveAfterInternal(t,r,o,c)}:s==="moveFront"?o=>{q.moveFrontInternal(t,r,o)}:s==="moveLast"?o=>{q.moveLastInternal(t,r,o)}:qu(s)?dr(t,r.get(Number(s))):s==="push"?o=>q.pushInternal(t,r,o):s==="splice"?(o,c,...l)=>q.splice(t,r,o,c,...l):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?q.iteratorInternal.bind(this,t,r):s==="includes"?(o,c)=>q.includes(t,r,o,c):s==="indexOf"?(o,c)=>q.indexOf(t,r,o,c):s==="lastIndexOf"?(o,c)=>q.lastIndexOf(t,r,o,c):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>q.toTestString(r):typeof s=="string"&&zu(s)?(...o)=>{const c=Array.from(r).map(l=>dr(t,l));return Array.prototype[s].apply(c,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(E.isEnabled(te.Trivial)&&E.trivial(`array[${s}]`),q.deleteInternalByIndex(t,r,Number.parseInt(s)),!0)}}static*iteratorInternal(t,e){for(const r of e)yield nr(t,r)}static buildArrayElements(t,e){const r=[];for(const s of e){const i=t.issueTimeTicket(),o=Gn(t,s,i);r.push(o)}return r}static pushInternal(t,e,r){return q.insertAfterInternal(t,e,e.getLastCreatedAt(),r),e.length}static moveBeforeInternal(t,e,r,s){const i=t.issueTimeTicket(),o=e.getPrevCreatedAt(r);e.moveAfter(o,s,i),t.push(ir.create(e.getCreatedAt(),o,s,i))}static moveAfterInternal(t,e,r,s){const i=t.issueTimeTicket();e.moveAfter(r,s,i),t.push(ir.create(e.getCreatedAt(),r,s,i))}static moveFrontInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getHead();e.moveAfter(i.getCreatedAt(),r,s),t.push(ir.create(e.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getLastCreatedAt();e.moveAfter(i,r,s),t.push(ir.create(e.getCreatedAt(),i,r,s))}static insertAfterInternal(t,e,r,s){const i=t.issueTimeTicket(),o=Gn(t,s,i);return e.insertAfter(r,o),t.registerElement(o,e),t.push(on.create(e.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(t,e,r,s){return q.insertAfterInternal(t,e,e.getPrevCreatedAt(r),s)}static deleteInternalByIndex(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByIndex(r,s);if(i)return t.push(hr.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static deleteInternalByID(t,e,r){const s=t.issueTimeTicket(),i=e.delete(r,s);return t.push(hr.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static splice(t,e,r,s,...i){const o=e.length,c=r>=0?Math.min(r,o):Math.max(o+r,0),l=s===void 0?o:s<0?c:Math.min(c+s,o),h=[];for(let f=c;f=i)return!1;if(U.isSupport(r))return Array.from(e).map(h=>dr(t,h)).includes(r,o);for(let l=o;l=i)return-1;if(U.isSupport(r))return Array.from(e).map(h=>dr(t,h)).indexOf(r,o);for(let l=o;l=i?i-1:s<0?s+i:s;if(o<0)return-1;if(U.isSupport(r))return Array.from(e).map(h=>dr(t,h)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((c=e.get(l))==null?void 0:c.getID())===r.getID())return l;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class _n{constructor(t,e){a(this,"context");a(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,r,s){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,e);E.isEnabled(te.Debug)&&E.debug(`EDIT: f:${t}->${i[0].toTestString()}, t:${e}->${i[1].toTestString()} c:${r}`);const o=s?Lr(s):void 0,c=this.context.issueTimeTicket(),[l,,h,f]=this.text.edit(i,r,c,o);for(const g of h)this.context.registerGCPair(g);return this.context.push(new an(this.text.getCreatedAt(),i[0],i[1],l,r,o?new Map(Object.entries(o)):new Map,c)),this.text.findIndexesFromRange(f)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,r){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(t,e);E.isEnabled(te.Debug)&&E.debug(`STYL: f:${t}->${s[0].toTestString()}, t:${e}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Lr(r),o=this.context.issueTimeTicket(),[c,l]=this.text.setStyle(s,i,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new cn(this.text.getCreatedAt(),s[0],s[1],c,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([Ce.fromStruct(t[0]),Ce.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new m(d.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 m(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new m(d.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}}class es{constructor(t,e){a(this,"valueType");a(this,"value");a(this,"context");a(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new m(d.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),r=U.of(t,e);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push($r.create(this.counter.getCreatedAt(),r,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new m(d.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function oi(n,t,e){const{type:r}=n,s=e.issueTimeTicket();if(r===Zt){aa(n);const{value:i}=n,o=oe.create(Z.of(s,0),r,i);t.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let c;if(typeof o=="object"&&!Po(o)){const h=Lr(o);c=new er;for(const[f,g]of Object.entries(h))c.set(f,g,s)}const l=oe.create(Z.of(s,0),r,void 0,c);t.append(l);for(const h of i)oi(h,l,e)}}function Vu(n,t){const{type:e}=t,r=n.issueTimeTicket();let s;if(t.type===Zt){const{value:i}=t;s=oe.create(Z.of(r,0),e,i)}else if(t){const{children:i=[]}=t,{attributes:o}=t;let c;if(typeof o=="object"&&!Po(o)){const l=Lr(o);c=new er;for(const[h,f]of Object.entries(l))c.set(h,f,r)}s=oe.create(Z.of(n.issueTimeTicket(),0),e,void 0,c);for(const l of i)oi(l,s,n)}return s}function aa(n){if(!n.value.length)throw new m(d.ErrInvalidArgument,"text node cannot have empty value");return!0}function Gi(n){if(!n.length)return!0;if(n[0].type===Zt)for(const e of n){const{type:r}=e;if(r!==Zt)throw new m(d.ErrInvalidArgument,"element node and text node cannot be passed together");aa(e)}else for(const e of n){const{type:r}=e;if(r===Zt)throw new m(d.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ts{constructor(t){a(this,"initialRoot");a(this,"context");a(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return oe.create(Z.of(t.issueTimeTicket(),0),qc);const e=oe.create(Z.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)oi(r,e,t);return e}getSize(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new m(d.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(t),i=this.context.issueTimeTicket(),o=e?Lr(e):void 0,[c]=this.tree.style([r,s],o,i);this.context.push(Qt.create(this.tree.getCreatedAt(),r,s,c,o?new Map(Object.entries(o)):new Map,i))}style(t,e,r){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),c=r?Lr(r):void 0,[l,h]=this.tree.style([s,i],c,o);for(const f of h)this.context.registerGCPair(f);this.context.push(Qt.create(this.tree.getCreatedAt(),s,i,l,c?new Map(Object.entries(c)):new Map,o))}removeStyle(t,e,r){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),[c,l]=this.tree.removeStyle([s,i],r,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Qt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,c,r,o))}editInternal(t,e,r,s=0){var h;if(r.length!==0&&r[0]&&(Gi(r),r[0].type!==Zt))for(const f of r){const{children:g=[]}=f;Gi(g)}const i=this.context.getLastTimeTicket();let o=new Array;if(((h=r[0])==null?void 0:h.type)===Zt){let f="";for(const g of r){const{value:v}=g;f+=v}o.push(oe.create(Z.of(this.context.issueTimeTicket(),0),Zt,f))}else o=r.map(f=>f&&Vu(this.context,f)).filter(f=>f);const[,c,l]=this.tree.edit([t,e],o.length?o.map(f=>f==null?void 0:f.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const f of c)this.context.registerGCPair(f);return this.context.push(un.create(this.tree.getCreatedAt(),t,e,o.length?o:void 0,s,l,i)),!0}editByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new m(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new m(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new m(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new m(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r,s)}edit(t,e,r,s=0){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulk(t,e,r,s=0){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new m(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(e);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");const e=[Ee.fromStruct(t[0]),Ee.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new m(d.ErrNotInitialized,"Tree is not initialized yet");const e=[Ee.fromStruct(t[0]),Ee.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function Wi(n,t){return oa(n,t)}function nr(n,t){if(t){if(t instanceof U)return t;if(t instanceof ne)return oa(n,t);if(t instanceof ae)return Uu(n,t);if(t instanceof Ie)return new _n(n,t);if(t instanceof ce){const e=new es(je.IntegerCnt,0);return e.initialize(n,t),e}else if(t instanceof Se){const e=new ts;return e.initialize(n,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function dr(n,t){const e=nr(n,t);return e instanceof U?e.getValue():e}function Gn(n,t,e){let r;if(U.isSupport(t))r=U.of(t,e);else if(Array.isArray(t))r=ae.create(e,q.buildArrayElements(n,t));else if(typeof t=="object")t instanceof _n?(r=Ie.create(Mr.create(),e),t.initialize(n,r)):t instanceof es?(r=ce.create(t.getValueType(),t.getValue(),e),t.initialize(n,r)):t instanceof ts?(r=Se.create(t.buildRoot(n),e),t.initialize(n,r)):r=ne.create(e,nn.buildObjectMembers(n,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const Hi=50;class Ku{constructor(){a(this,"undoStack",[]);a(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Hi&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Hi&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const ju="yorkie-devtools-panel",Gu="yorkie-devtools-sdk";let xr="disconnected";const Yi=new Map,An=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=An);function gn(n,t){(t!=null&&t.force||xr!=="disconnected")&&window.postMessage({source:Gu,...n},"*")}function Wu(n){if(!n.isEnableDevtools()||typeof window>"u"||Yi.has(n.getKey()))return;An.set(n.getKey(),[]);const t=n.subscribe("all",e=>{e.some(r=>r.type!==X.StatusChanged&&r.type!==X.Snapshot&&r.type!==X.LocalChange&&r.type!==X.RemoteChange&&r.type!==X.Initialized&&r.type!==X.Watched&&r.type!==X.Unwatched&&r.type!==X.PresenceChanged)||(An.get(n.getKey()).push(e),xr==="synced"&&gn({msg:"doc::sync::partial",docKey:n.getKey(),event:e}))});Yi.set(n.getKey(),[t]),gn({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var s;if(((s=e.data)==null?void 0:s.source)!==ju)return;switch(e.data.msg){case"devtools::connect":if(xr!=="disconnected")break;xr="connected",gn({msg:"doc::available",docKey:n.getKey()}),E.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":xr="disconnected",E.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":xr="synced",gn({msg:"doc::sync::full",docKey:n.getKey(),events:An.get(n.getKey())}),E.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var sr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(sr||{}),X=(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.AuthError="auth-error",n))(X||{}),Us=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Us||{}),qs=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(qs||{});class ca{constructor(t,e){a(this,"key");a(this,"status");a(this,"opts");a(this,"changeID");a(this,"checkpoint");a(this,"localChanges");a(this,"root");a(this,"clone");a(this,"eventStream");a(this,"eventStreamObserver");a(this,"onlineClients");a(this,"presences");a(this,"history");a(this,"internalHistory");a(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=rn.create(),this.changeID=Xc,this.checkpoint=Zc,this.localChanges=[],this.eventStream=$u(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Ku,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Wu(this)}update(t,e){if(this.getStatus()==="removed")throw new m(d.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},e);try{const i=Wi(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(i,new os(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){E.isEnabled(te.Trivial)&&E.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:c}=i.execute(this.root,this.presences,J.Local),l=s.getReversePresence();l&&c.push({type:"presence",value:l}),this.localChanges.push(i),c.length>0&&this.internalHistory.pushUndo(c),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const h=[];o.length>0&&h.push({type:"local-change",source:J.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()&&h.push({type:"presence-changed",source:J.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(h),E.isEnabled(te.Trivial)&&E.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,r,s){if(typeof t=="string"){if(typeof e!="function")throw new m(d.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||c(h)},r,s)}if(t==="my-presence"){const c=e;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()||c(h)},r,s)}if(t==="others"){const c=e;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()&&c(h)},r,s)}if(t==="connection"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&c(h)},r,s)}if(t==="status"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&c(h)},r,s)}if(t==="sync"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&c(h)},r,s)}if(t==="local-broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&c(h)},r)}if(t==="broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&c(h)},r)}if(t==="auth-error"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="auth-error"&&c(h)},r)}if(t==="all"){const c=e;return this.eventStream.subscribe(c,r,s)}const i=t,o=e;return this.eventStream.subscribe(c=>{for(const l of c){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const f of l.value.operations)this.isSameElementOrChildOf(f.path,i)&&h.push(f);h.length&&o({...l,value:{...l.value,operations:h}})}},r,s)}if(typeof t=="function"){const i=t,o=e,c=r;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||i(h)},o,c)}throw new m(d.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const r=t.split(".");return e.split(".").every((i,o)=>i===r[o])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const e=t.hasSnapshot();e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),J.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),E.isEnabled(te.Trivial)&&E.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:ke(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Qn.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.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=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Wi(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,r,s=-1){const{root:i,presences:o}=j.bytesToSnapshot(r);this.root=new rn(i),this.presences=o,this.changeID=this.changeID.setClocks(e.maxLamport(),e),this.clone=void 0,this.removePushedLocalChanges(s),this.applyChanges(this.localChanges,J.Local),this.publish([{type:"snapshot",source:J.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?j.bytesToHex(r):void 0,snapshotVector:j.versionVectorToHex(e)}}])}applyChanges(t,e){E.isEnabled(te.Debug)&&E.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),E.isEnabled(te.Trivial)&&E.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of t)this.applyChange(r,e);E.isEnabled(te.Debug)&&E.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const r=[],s=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(s)){const o=t.getPresenceChange();switch(o.type){case lr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:e,value:{clientID:s,presence:o.presence}}:{type:"watched",source:J.Remote,value:{clientID:s,presence:o.presence}});break;case lr.Clear:r.push({type:"unwatched",source:J.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),i.length>0){const o=this.isEnableDevtools()?t.toStruct():void 0;r.push(e===J.Remote?{type:"remote-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,r=new Set;for(const s of e)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:J.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:r}=t.body.value,s=[];if(e===yr.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(e===yr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:J.Remote,value:{clientID:r,presence:i}})}else if(e===yr.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:i,payload:o}=t.body.value.body,c=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(c.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Xn),this.publish([{source:t==="removed"?J.Remote:J.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:e,serverSeq:r,snapshotVector:s}=t.value;if(!e)return;this.applySnapshot(BigInt(r),j.hexToVersionVector(s),j.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Fr.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:r,presence:s}of t.value)e.add(r),this.presences.set(r,s);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:r}=t.value;this.addOnlineClient(e),this.presences.set(e,r);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:r}=t.value;this.presences.set(e,r)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new m(d.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let r=this.getRoot();for(const s of e)if(r=r[s],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?ke(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?ke(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?ke(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:ke(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:ke(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,r)=>e.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new m(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new m(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Pe)){new os(e,ke(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.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 c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}redo(){if(this.isUpdating)throw new m(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new m(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Pe)){new os(e,ke(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.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 c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,r){const s={type:"local-broadcast",value:{topic:t,payload:e},options:r};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function Hu(n,t){let e=t;return{authInterceptor:i=>async o=>(n&&o.header.set("x-api-key",n),e&&o.header.set("authorization",e),await i(o)),setToken:i=>{e=i}}}const Yu="yorkie-js-sdk",Xu="0.5.6",Zu="Yorkie JS SDK",Qu="./src/yorkie.ts",_u={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},el=["dist"],tl={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"},rl={node:">=18.0.0",npm:">=7.1.0"},nl={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},sl={name:"hackerwins",email:"susukang98@gmail.com"},il="Apache-2.0",ol={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},al="https://github.com/yorkie-team/yorkie-js-sdk#readme",cl={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ul={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Xi={name:Yu,version:Xu,description:Zu,main:Qu,publishConfig:_u,files:el,scripts:tl,engines:rl,repository:nl,author:sl,license:il,bugs:ol,homepage:al,devDependencies:cl,dependencies:ul};function ll(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Xi.name+"/"+Xi.version),await n(t))}const hl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var bn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(bn||{});const mn={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ls={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ua{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"authTokenInjector");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"setAuthToken");a(this,"taskQueue");a(this,"processing",!1);a(this,"keepalive",!1);e=e||mn,this.key=e.key?e.key:ia(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.authTokenInjector=e.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration??mn.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay??mn.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay??mn.retrySyncLoopDelay;const{authInterceptor:r,setToken:s}=Hu(this.apiKey);this.setAuthToken=s,this.rpcClient=lc(Bc,Oc({baseUrl:t,interceptors:[r,ll()],fetch:(i,o)=>{const c={...o,keepalive:this.keepalive};return fetch(i,c)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),E.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw E.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const e=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),E.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw E.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(t.keepalive){this.keepalive=!0;const r=e();return this.keepalive=!1,r}return this.enqueueTask(e)}attach(t,e={}){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==sr.Detached)throw new m(d.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((i,o)=>o.set(e.initialPresence||{}));const r=t.subscribe("local-broadcast",async i=>{var f;const{topic:o,payload:c}=i.value,l=(f=i.options)==null?void 0:f.error,h=i.options;try{await this.broadcast(t.getKey(),o,c,h)}catch(g){g instanceof Error&&(l==null||l(g))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:j.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=j.fromChangePack(i.changePack);if(t.applyChangePack(o),t.getStatus()===sr.Removed)return t;t.applyStatus(sr.Attached),this.attachmentMap.set(t.getKey(),new Fu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),E.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const c=t.getRootObject();if(e.initialRoot){const l=e.initialRoot;t.update(h=>{for(const[f,g]of Object.entries(l))if(!c.has(f)){const v=f;h[v]=g}})}return t}).catch(async i=>{throw E.error(`[AD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:j.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==sr.Removed&&t.applyStatus(sr.Detached),this.detachInternal(t.getKey()),E.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async s=>{throw E.error(`[DD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const s=r.syncMode;return s===e?t:(r.changeSyncMode(e),e==="manual"?(r.cancelWatchStream(),t):(e==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(async r=>{throw E.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const e=[];for(const[,r]of this.attachmentMap)e.push(this.syncInternal(r,r.syncMode));return Promise.all(e).catch(async r=>{throw E.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=j.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),E.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async s=>{throw E.error(`[RD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}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,e,r,s){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new m(d.ErrDocumentNotAttached,`${t} is not attached`);if(!hl(r))throw new m(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??ls.maxRetries,c=ls.maxBackoff;let l=0;const h=g=>Math.min(ls.initialRetryInterval*2**g,c),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{E.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(async g=>{if(E.error(`[BC] c:"${this.getKey()}" err:`,g),await this.handleConnectError(g))if(g instanceof M&&Sr(g)===d.ErrUnauthenticated&&i.doc.publish([{type:X.AuthError,value:{reason:zr(g).reason,method:"Broadcast"}}]),lf(),h(l-1)),E.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw E.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),g;else throw g}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){E.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,e.push(this.syncInternal(r,r.syncMode).catch(async s=>{throw s instanceof M&&Sr(s)===d.ErrUnauthenticated&&r.doc.publish([{type:X.AuthError,value:{reason:zr(s).reason,method:"PushPull"}}]),s})));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async r=>{E.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};E.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new m(d.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new m(d.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:s.signal});return e.doc.publish([{type:X.ConnectionChanged,value:Us.Connected}]),E.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((o,c)=>{(async()=>{try{for await(const h of i)this.handleWatchDocumentsResponse(e,h),h.body.case==="initialization"&&o([i,s])}catch(h){e.doc.resetOnlineClients(),e.doc.publish([{type:X.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:X.ConnectionChanged,value:Us.Disconnected}]),E.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(h)?(h instanceof M&&Sr(h)===d.ErrUnauthenticated&&e.doc.publish([{type:X.AuthError,value:{reason:zr(h).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===yr.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(sr.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:r,docID:s}=t,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:j.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=j.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:X.SyncStatusChanged,value:qs.Synced}]),r.getStatus()===sr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return E.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:X.SyncStatusChanged,value:qs.SyncFailed}]),E.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(t){if(!(t instanceof M))return!1;if(t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable)return!0;if(Sr(t)===d.ErrUnauthenticated){if(this.authTokenInjector){const e=await this.authTokenInjector(zr(t).reason);this.setAuthToken(e)}return!0}return(Sr(t)===d.ErrClientNotActivated||Sr(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(t){return new Promise((e,r)=>{this.taskQueue.push(()=>t().then(e).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{E.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Zi={Client:ua,Document:ca,Primitive:U,Text:_n,Counter:es,Tree:ts,LogLevel:te,setLogLevel:sa,IntType:je.IntegerCnt,LongType:je.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:ua,Document:ca,Primitive:U,Text:_n,Counter:es,Tree:ts,LogLevel:te,setLogLevel:sa,IntType:je.IntegerCnt,LongType:je.LongCnt});const Qi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],fl=()=>{const n=Math.floor(Math.random()*Qi.length);return Qi[n]},_i=["red","yellow","orange","green","blue","purple"],dl=()=>{const n=Math.floor(Math.random()*_i.length);return _i[n]};async function gl(){const n=new Zi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new Zi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==X.PresenceChanged&&ml(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:fl(),color:dl()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const hs=4,fs=(n,t,e)=>{const r=document.createElement("div");return r.className="peer",e==="main"?r.innerHTML=` +`));for(const r of t)this.applyChange(r,e);E.isEnabled(te.Debug)&&E.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const r=[],s=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(s)){const o=t.getPresenceChange();switch(o.type){case lr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:e,value:{clientID:s,presence:o.presence}}:{type:"watched",source:J.Remote,value:{clientID:s,presence:o.presence}});break;case lr.Clear:r.push({type:"unwatched",source:J.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),i.length>0){const o=this.isEnableDevtools()?t.toStruct():void 0;r.push(e===J.Remote?{type:"remote-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,r=new Set;for(const s of e)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:J.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:r}=t.body.value,s=[];if(e===yr.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(e===yr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:J.Remote,value:{clientID:r,presence:i}})}else if(e===yr.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:i,payload:o}=t.body.value.body,c=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(c.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Xn),this.publish([{source:t==="removed"?J.Remote:J.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:e,serverSeq:r,snapshotVector:s}=t.value;if(!e)return;this.applySnapshot(BigInt(r),j.hexToVersionVector(s),j.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Fr.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:r,presence:s}of t.value)e.add(r),this.presences.set(r,s);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:r}=t.value;this.addOnlineClient(e),this.presences.set(e,r);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:r}=t.value;this.presences.set(e,r)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new m(d.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let r=this.getRoot();for(const s of e)if(r=r[s],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?ke(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?ke(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?ke(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:ke(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:ke(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,r)=>e.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new m(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new m(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Pe)){new os(e,ke(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.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 c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}redo(){if(this.isUpdating)throw new m(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new m(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Nr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Pe)){new os(e,ke(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.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 c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,r){const s={type:"local-broadcast",value:{topic:t,payload:e},options:r};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function Hu(n,t){let e=t;return{authInterceptor:i=>async o=>(n&&o.header.set("x-api-key",n),e&&o.header.set("authorization",e),await i(o)),setToken:i=>{e=i}}}const Yu="yorkie-js-sdk",Xu="0.5.7",Zu="Yorkie JS SDK",Qu="./src/yorkie.ts",_u={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},el=["dist"],tl={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"},rl={node:">=18.0.0",npm:">=7.1.0"},nl={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},sl={name:"hackerwins",email:"susukang98@gmail.com"},il="Apache-2.0",ol={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},al="https://github.com/yorkie-team/yorkie-js-sdk#readme",cl={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ul={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Xi={name:Yu,version:Xu,description:Zu,main:Qu,publishConfig:_u,files:el,scripts:tl,engines:rl,repository:nl,author:sl,license:il,bugs:ol,homepage:al,devDependencies:cl,dependencies:ul};function ll(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Xi.name+"/"+Xi.version),await n(t))}const hl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var bn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(bn||{});const mn={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ls={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ua{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"authTokenInjector");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"setAuthToken");a(this,"taskQueue");a(this,"processing",!1);a(this,"keepalive",!1);e=e||mn,this.key=e.key?e.key:ia(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.authTokenInjector=e.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration??mn.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay??mn.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay??mn.retrySyncLoopDelay;const{authInterceptor:r,setToken:s}=Hu(this.apiKey);this.setAuthToken=s,this.rpcClient=lc(Bc,Oc({baseUrl:t,interceptors:[r,ll()],fetch:(i,o)=>{const c={...o,keepalive:this.keepalive};return fetch(i,c)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),E.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw E.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const e=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),E.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw E.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(t.keepalive){this.keepalive=!0;const r=e();return this.keepalive=!1,r}return this.enqueueTask(e)}attach(t,e={}){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==sr.Detached)throw new m(d.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((i,o)=>o.set(e.initialPresence||{}));const r=t.subscribe("local-broadcast",async i=>{var f;const{topic:o,payload:c}=i.value,l=(f=i.options)==null?void 0:f.error,h=i.options;try{await this.broadcast(t.getKey(),o,c,h)}catch(g){g instanceof Error&&(l==null||l(g))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:j.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=j.fromChangePack(i.changePack);if(t.applyChangePack(o),t.getStatus()===sr.Removed)return t;t.applyStatus(sr.Attached),this.attachmentMap.set(t.getKey(),new Fu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),E.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const c=t.getRootObject();if(e.initialRoot){const l=e.initialRoot;t.update(h=>{for(const[f,g]of Object.entries(l))if(!c.has(f)){const v=f;h[v]=g}})}return t}).catch(async i=>{throw E.error(`[AD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:j.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==sr.Removed&&t.applyStatus(sr.Detached),this.detachInternal(t.getKey()),E.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async s=>{throw E.error(`[DD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const s=r.syncMode;return s===e?t:(r.changeSyncMode(e),e==="manual"?(r.cancelWatchStream(),t):(e==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(async r=>{throw E.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const e=[];for(const[,r]of this.attachmentMap)e.push(this.syncInternal(r,r.syncMode));return Promise.all(e).catch(async r=>{throw E.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new m(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=j.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=j.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),E.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async s=>{throw E.error(`[RD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}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,e,r,s){if(!this.isActive())throw new m(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new m(d.ErrDocumentNotAttached,`${t} is not attached`);if(!hl(r))throw new m(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??ls.maxRetries,c=ls.maxBackoff;let l=0;const h=g=>Math.min(ls.initialRetryInterval*2**g,c),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{E.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(async g=>{if(E.error(`[BC] c:"${this.getKey()}" err:`,g),await this.handleConnectError(g))if(g instanceof M&&Sr(g)===d.ErrUnauthenticated&&i.doc.publish([{type:X.AuthError,value:{reason:zr(g).reason,method:"Broadcast"}}]),lf(),h(l-1)),E.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw E.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),g;else throw g}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){E.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,e.push(this.syncInternal(r,r.syncMode).catch(async s=>{throw s instanceof M&&Sr(s)===d.ErrUnauthenticated&&r.doc.publish([{type:X.AuthError,value:{reason:zr(s).reason,method:"PushPull"}}]),s})));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async r=>{E.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};E.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new m(d.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new m(d.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:s.signal});return e.doc.publish([{type:X.ConnectionChanged,value:Us.Connected}]),E.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((o,c)=>{(async()=>{try{for await(const h of i)this.handleWatchDocumentsResponse(e,h),h.body.case==="initialization"&&o([i,s])}catch(h){e.doc.resetOnlineClients(),e.doc.publish([{type:X.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:X.ConnectionChanged,value:Us.Disconnected}]),E.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(h)?(h instanceof M&&Sr(h)===d.ErrUnauthenticated&&e.doc.publish([{type:X.AuthError,value:{reason:zr(h).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===yr.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(sr.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:r,docID:s}=t,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:j.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=j.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:X.SyncStatusChanged,value:qs.Synced}]),r.getStatus()===sr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return E.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:X.SyncStatusChanged,value:qs.SyncFailed}]),E.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(t){if(!(t instanceof M))return!1;if(t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable)return!0;if(Sr(t)===d.ErrUnauthenticated){if(this.authTokenInjector){const e=await this.authTokenInjector(zr(t).reason);this.setAuthToken(e)}return!0}return(Sr(t)===d.ErrClientNotActivated||Sr(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(t){return new Promise((e,r)=>{this.taskQueue.push(()=>t().then(e).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{E.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Zi={Client:ua,Document:ca,Primitive:U,Text:_n,Counter:es,Tree:ts,LogLevel:te,setLogLevel:sa,IntType:je.IntegerCnt,LongType:je.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:ua,Document:ca,Primitive:U,Text:_n,Counter:es,Tree:ts,LogLevel:te,setLogLevel:sa,IntType:je.IntegerCnt,LongType:je.LongCnt});const Qi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],fl=()=>{const n=Math.floor(Math.random()*Qi.length);return Qi[n]},_i=["red","yellow","orange","green","blue","purple"],dl=()=>{const n=Math.floor(Math.random()*_i.length);return _i[n]};async function gl(){const n=new Zi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new Zi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==X.PresenceChanged&&ml(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:fl(),color:dl()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const hs=4,fs=(n,t,e)=>{const r=document.createElement("div");return r.className="peer",e==="main"?r.innerHTML=`
    profile
    diff --git a/examples/profile-stack/index.html b/examples/profile-stack/index.html index f9570bc32..27dcb0f48 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-1ncFVCXa.js b/examples/react-tldraw/assets/index-DnUaLAgB.js similarity index 99% rename from examples/react-tldraw/assets/index-1ncFVCXa.js rename to examples/react-tldraw/assets/index-DnUaLAgB.js index 2067519b6..43101fc2d 100644 --- a/examples/react-tldraw/assets/index-1ncFVCXa.js +++ b/examples/react-tldraw/assets/index-DnUaLAgB.js @@ -548,7 +548,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert- * * SPDX-License-Identifier: Apache-2.0 */var bi=null;try{bi=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 at(e,t,n){this.low=e|0,this.high=t|0,this.unsigned=!!n}at.prototype.__isLong__;Object.defineProperty(at.prototype,"__isLong__",{value:!0});function qn(e){return(e&&e.__isLong__)===!0}function Ax(e){var t=Math.clz32(e&-e);return e?31-t:t}at.isLong=qn;var kx={},Ix={};function _l(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=Ix[e],r)?r:(n=ct(e,0,!0),i&&(Ix[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=kx[e],r)?r:(n=ct(e,e<0?-1:0,!1),i&&(kx[e]=n),n))}at.fromInt=_l;function wi(e,t){if(isNaN(e))return t?hs:qi;if(t){if(e<0)return hs;if(e>=LP)return NP}else{if(e<=-Tx)return yr;if(e+1>=Tx)return _P}return e<0?wi(-e,t).neg():ct(e%cd|0,e/cd|0,t)}at.fromNumber=wi;function ct(e,t,n){return new at(e,t,n)}at.fromBits=ct;var sm=Math.pow;function NC(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?hs:qi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return NC(e.substring(1),t,n).neg();for(var i=wi(sm(n,8)),o=qi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*cd+(this.low>>>0):this.high*cd+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,h=d.toString(t);if(a=u,a.isZero())return h+s;for(;h.length<6;)h="0"+h;s=""+h+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 qn(t)||(t=co(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(qn(t)||(t=co(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(Tc)};he.neg=he.negate;he.add=function(t){qn(t)||(t=co(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,h=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,h+=p>>>16,p&=65535,h+=n+a,h&=65535,ct(g<<16|m,h<<16|p,this.unsigned)};he.subtract=function(t){return qn(t)||(t=co(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(qn(t)||(t=co(t)),bi){var n=bi.mul(this.low,this.high,t.low,t.high);return ct(n,bi.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?hs:qi;if(this.eq(yr))return t.isOdd()?yr:qi;if(t.eq(yr))return this.isOdd()?yr:qi;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(Px)&&t.lt(Px))return wi(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,h=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*h,m+=v>>>16,v&=65535,m+=o*h,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*h,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*h+i*d+o*u+a*s,p&=65535,ct(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(qn(t)||(t=co(t)),t.isZero())throw Error("division by zero");if(bi){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var n=(this.unsigned?bi.div_u:bi.div_s)(this.low,this.high,t.low,t.high);return ct(n,bi.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hs:qi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return hs;if(t.gt(this.shru(1)))return OP;o=hs}else{if(this.eq(yr)){if(t.eq(Tc)||t.eq(y3))return yr;if(t.eq(yr))return Tc;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(qi)?t.isNegative()?Tc:y3:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?hs:qi;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=qi}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:sm(2,s-48),d=wi(r),h=d.mul(t);h.isNegative()||h.gt(i);)r-=u,d=wi(r,this.unsigned),h=d.mul(t);d.isZero()&&(d=Tc),o=o.add(d),i=i.sub(h)}return o};he.div=he.divide;he.modulo=function(t){if(qn(t)||(t=co(t)),bi){var n=(this.unsigned?bi.rem_u:bi.rem_s)(this.low,this.high,t.low,t.high);return ct(n,bi.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return ct(~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?Ax(this.low):Ax(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return qn(t)||(t=co(t)),ct(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return qn(t)||(t=co(t)),ct(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return qn(t)||(t=co(t)),ct(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low<>>32-t,this.unsigned):ct(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):ct(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?ct(this.high,0,this.unsigned):ct(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.low<>>n,this.high<>>n,this.unsigned)):(t-=32,n=32-t,ct(this.high<>>n,this.low<>>n,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,n=32-t,ct(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?ct(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:ct(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]};at.fromBytes=function(t,n,r){return r?at.fromBytesLE(t,n):at.fromBytesBE(t,n)};at.fromBytesLE=function(t,n){return new at(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};at.fromBytesBE=function(t,n){return new at(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};var Cn=(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))(Cn||{});class Jt extends Oh{constructor(n,r){super(r);k(this,"valueType");k(this,"value");this.valueType=Jt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Jt(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 at.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(at.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(J.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Oo(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Jt.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 at)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Jt.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=at.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(J.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class um extends FP{constructor(n){super(n);k(this,"prev");k(this,"next");this.value=n}static createAfter(n,r){const i=new um(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 fh{constructor(){k(this,"dummyHead");k(this,"last");k(this,"nodeMapByIndex");k(this,"nodeMapByCreatedAt");const t=Jt.of(0,to);t.setRemovedAt(to),this.dummyHead=new um(t),this.last=this.dummyHead,this.nodeMapByIndex=new hh,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new fh}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(J.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=um.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(J.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(J.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(J.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 vu{constructor(n,r){super(n);k(this,"elements");this.elements=r}static create(n,r){if(!r)return new jr(n,fh.create());const i=fh.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 vu&&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({...v,value:v.value?{attributes:Hc(v.value.getAttributes()),content:v.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,m,p,[d,d]]}setStyle(n,r,i,o,a){const[,s]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,u]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),d=[],h=this.rgaTreeSplit.findBetween(u,s),p=new Map,g=[];for(const v of h){const E=v.getCreatedAt().getActorID();let w,C=0n;if(a===void 0&&o===void 0?C=R0:a.size()>0?C=a.get(E)?a.get(E):0n:w=o.has(E)?o.get(E):to,v.canStyle(i,w,C)){const b=p.get(E),A=v.getCreatedAt();(!b||A.after(b))&&p.set(E,A),g.push(v)}}const m=[];for(const v of g){if(v.isRemoved())continue;const[E,w]=this.rgaTreeSplit.findIndexesFromRange(v.createPosRange());d.push({type:"style",actor:i.getActorID(),from:E,to:w,value:{attributes:Hc(r)}});for(const[C,b]of Object.entries(r)){const[A]=v.getValue().setAttr(C,b,i);A!==void 0&&m.push({parent:v.getValue(),child:A})}}return[p,m,d]}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:Hc(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new Ti(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 Nh extends so{constructor(n,r,i,o,a,s,u){super(n,u);k(this,"fromPos");k(this,"toPos");k(this,"maxCreatedAtMapByActor");k(this,"content");k(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 Nh(n,r,i,o,a,s,u)}execute(n,r,i){const o=n.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new Y(J.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Ti))throw new Y(J.ErrInvalidArgument,"fail to execute, only Text can execute edit");const a=o,[,s,u]=a.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,i);for(const d of u)n.registerGCPair(d);return{opInfos:s.map(({from:d,to:h,value:p})=>({type:"edit",from:d,to:h,value:p,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 zh extends so{constructor(n,r,i,o,a,s){super(n,s);k(this,"fromPos");k(this,"toPos");k(this,"maxCreatedAtMapByActor");k(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new zh(n,r,i,o,a,s)}execute(n,r,i){const o=n.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new Y(J.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Ti))throw new Y(J.ErrInvalidArgument,"fail to execute, only Text can execute edit");const a=o,[,s,u]=a.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,i);for(const d of s)n.registerGCPair(d);return{opInfos:u.map(({from:d,to:h,value:p})=>({type:"style",from:d,to:h,value:p,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 pKe=2,gKe="root",vs="text";function s0(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(J.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===vs}get paddedSize(){return this.size+(this.isText?0:pKe)}isAncestorOf(t){return vKe(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(J.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(J.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(J.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(J.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(J.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(J.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(J.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(J.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(J.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(J.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(J.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(J.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(J.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(J.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 vKe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var un=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(un||{});function zP(e,t,n,r){if(t>n)throw new Y(J.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(J.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(J.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),zP(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function HP(e,t,n=0){for(const r of e.children)HP(r,t,n+1);t(e,n)}function b1(e,t,n=0){for(const r of e._children)b1(r,t,n+1);t(e,n)}function E3(e,t,n=!0){if(t>e.size)throw new Y(J.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 E3(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 E3(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function jP(e){return e.isText||e.children.length===0?e:jP(e.children[0])}function yKe(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 bKe(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 Xi{constructor(t,n){k(this,"parentID");k(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Xi(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],Xi.of(r.id,Fn.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Xi.of(Fn.of(Ai.fromStruct(t.parentID.createdAt),t.parentID.offset),Fn.of(Ai.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(J.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 Fn{constructor(t,n){k(this,"createdAt");k(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new Fn(t,n)}static fromStruct(t){return Fn.of(Ai.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(J.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(J.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(Fn.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr(Fn.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,i){return(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r,i){return this.isText?!1:(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new Ds);const i=[];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 C3(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(C3)};return e.attrs&&(t.attributes=Hc((n=e.attrs)==null?void 0:n.toObject())),t}function zC(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()}="${Oo(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>zC(n)).join("")}`}function KP(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(KP),size:e.size,isRemoved:e.isRemoved}}class Pi extends Oh{constructor(n,r){super(r);k(this,"indexTree");k(this,"nodeMapByID");this.indexTree=new EKe(n),this.nodeMapByID=new UP(Fn.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Pi(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,h=s?0:d.indexOf(a)+1;for(let p=h;p{const w=E.getCreatedAt().getActorID();let C,b=0n;if(a===void 0&&o===void 0?b=R0:a.size()>0?b=a.get(w)?a.get(w):0n:C=o.has(w)?o.get(w):to,E.canStyle(i,C,b)&&r){const A=m.get(w),T=E.getCreatedAt();(!A||T.after(A))&&m.set(w,T);const B=E.setAttrs(r,i),D=B.reduce((O,[,z])=>(z&&(O[z.getKey()]=g[z.getKey()]),O),{}),I=E.parent,M=E.prevSibling||E.parent;Object.keys(D).length>0&&p.push({type:"style",from:this.toIndex(I,M),to:this.toIndex(E,E),fromPath:this.toPath(I,M),toPath:this.toPath(E,E),actor:i.getActorID(),value:D});for(const[O]of B)O&&v.push({parent:E,child:O})}}),[m,v,p]}removeStyle(n,r,i,o,a){const[s,u]=this.findNodesAndSplitText(n[0],i),[d,h]=this.findNodesAndSplitText(n[1],i),p=[],g=new Map,m=[];return this.traverseInPosRange(s,u,d,h,([v])=>{const E=v.getCreatedAt().getActorID();let w,C=0n;if(a===void 0&&o===void 0?C=R0:a.size()>0?C=a.get(E)?a.get(E):0n:w=o.has(E)?o.get(E):to,v.canStyle(i,w,C)&&r){const b=g.get(E),A=v.getCreatedAt();(!b||A.after(b))&&g.set(E,A),v.attrs||(v.attrs=new Ds);for(const D of r){const I=v.attrs.remove(D,i);for(const M of I)m.push({parent:v,child:M})}const T=v.parent,B=v.prevSibling||v.parent;p.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(T,B),to:this.toIndex(v,v),fromPath:this.toPath(T,B),toPath:this.toPath(v,v),value:r})}}),[g,m,p]}edit(n,r,i,o,a,s,u){const[d,h]=this.findNodesAndSplitText(n[0],o),[p,g]=this.findNodesAndSplitText(n[1],o),m=this.toIndex(d,h),v=this.toPath(d,h),E=[],w=[],C=[],b=new Map;this.traverseInPosRange(d,h,p,g,([B,D],I)=>{if(D===un.Start&&!I)for(const K of B.children)C.push(K);const M=B.getCreatedAt().getActorID();let O,z=0n;if(u===void 0&&s===void 0?z=R0:u.size()>0?z=u.get(M)?u.get(M):0n:O=s.has(M)?s.get(M):to,B.canDelete(o,O,z)||E.includes(B.parent)){const K=b.get(M),X=B.getCreatedAt();(!K||X.after(K))&&b.set(M,X),(D===un.Text||D===un.Start)&&E.push(B),w.push([B,D])}});const A=this.makeDeletionChanges(w,o),T=[];for(const B of E)B.remove(o),B.isRemoved&&T.push({parent:this,child:B});for(const B of C)B.removedAt||d.append(B);if(i>0){let B=0,D=d,I=h;for(;B{d.isRemoved&&(M.remove(o),T.push({parent:this,child:M})),this.nodeMapByID.put(M.id,M)}),I.isRemoved||B.push(I);if(B.length){const I=B.map(M=>C3(M));A.length&&A[A.length-1].from===m?A[A.length-1].value=I:A.push({type:"content",from:m,to:m,fromPath:v,toPath:v,actor:o.getActorID(),value:I})}}return[A,T,b]}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(J.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 Xi.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 zC(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,h;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),h=Xi.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?Hc((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:h};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===un.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?un.Text:un.Start]:[n,un.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,un.End];const s=o[a+1];return[s,s.isText?un.Text:un.Start]}findLeftToken([n,r]){if(r===un.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?un.Text:un.End]}return[n,un.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,un.Start];const s=o[a-1];return[s,s.isText?un.Text:un.End]}}class Hh extends so{constructor(n,r,i,o,a,s,u){super(n,u);k(this,"fromPos");k(this,"toPos");k(this,"contents");k(this,"splitLevel");k(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 Hh(n,r,i,o,a,s,u)}execute(n,r,i){var h;const o=n.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new Y(J.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Pi))throw new Y(J.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const a=this.getExecutedAt(),s=o,[u,d]=s.edit([this.fromPos,this.toPos],(h=this.contents)==null?void 0:h.map(p=>p.deepcopy()),this.splitLevel,a,(()=>{let p=a.getDelimiter();return this.contents!==void 0&&(p+=this.contents.length),()=>Ai.of(a.getLamport(),++p,a.getActorID())})(),this.maxCreatedAtMapByActor,i);for(const p of d)n.registerGCPair(p);return{opInfos:u.map(({from:p,to:g,value:m,splitLevel:v,fromPath:E,toPath:w})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:p,to:g,value:m,splitLevel:v,fromPath:E,toPath:w}))}}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=>zC(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class jc{constructor(t){k(this,"vector");this.vector=t||new Map}set(t,n){this.vector.set(t,n)}unset(t){this.vector.delete(t)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,n]of this)n>t&&(t=n);return t}max(t){const n=new Map;for(const[r,i]of t){const o=this.vector.get(r),a=o&&o>i?o:i;n.set(r,a)}for(const[r,i]of this){const o=t.get(r),a=o&&o>i?o:i;n.set(r,a)}return new jc(n)}afterOrEqual(t){const n=this.vector.get(t.getActorID());return n===void 0?!1:n>=t.getLamport()}deepcopy(){const t=new Map;for(const[n,r]of this.vector)t.set(n,r);return new jc(t)}filter(t){const n=new Map;for(const[r]of t){const i=this.vector.get(r);i!==void 0&&n.set(r,i)}return new jc(n)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,n]of this.vector)yield[t,n]}}const SKe=new jc(new Map);class as{constructor(t,n,r,i,o){k(this,"clientSeq");k(this,"serverSeq");k(this,"lamport");k(this,"actor");k(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=n,this.versionVector=i,this.actor=r}static of(t,n,r,i,o){return new as(t,n,r,i,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new as(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const n=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n;let r=t.versionVector;r.size()===0&&(r=r.deepcopy(),r.set(t.actor,t.lamport));const i=this.versionVector.max(r),o=new as(this.clientSeq,n,this.actor,i);return o.versionVector.set(this.actor,n),o}setClocks(t,n){const r=t>this.lamport?t+1n:this.lamport+1n;n.unset(C1);const i=this.versionVector.max(n);return i.set(this.actor,r),as.of(this.clientSeq,r,this.actor,i)}createTimeTicket(t){return Ai.of(this.lamport,t,this.actor)}setActor(t){return new as(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new as(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const xKe=new as(0,0n,C1,SKe);class dd{constructor({id:t,operations:n,presenceChange:r,message:i}){k(this,"id");k(this,"operations");k(this,"presenceChange");k(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 dd({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,this.id.getVersionVector());if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===Du.Put?n.set(this.id.getActorID(),Gi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:on.bytesToHex(on.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>on.bytesToHex(on.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return dd.create({id:on.bytesToChangeID(on.hexToBytes(n)),operations:r==null?void 0:r.map(a=>on.bytesToOperation(on.hexToBytes(a))),presenceChange:i,message:o})}}class w1{constructor(t,n,r,i,o,a,s){k(this,"documentKey");k(this,"checkpoint");k(this,"isRemoved");k(this,"changes");k(this,"snapshot");k(this,"minSyncedTicket");k(this,"versionVector");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=a,this.minSyncedTicket=s,this.versionVector=o}static create(t,n,r,i,o,a,s){return new w1(t,n,r,i,o,a,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}getVersionVector(){return this.versionVector}}class Uc{constructor(t,n){k(this,"serverSeq");k(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new Uc(t,n)}increaseClientSeq(t){return t===0?this:new Uc(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Uc.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==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const AKe=new Uc(0n,0);class zo{constructor(t,n){k(this,"createdAt");k(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new zo(t,n)}static fromStruct(t){return zo.of(Ai.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 zo(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 kKe=zo.of(to,0);class no{constructor(t,n){k(this,"id");k(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new no(t,n)}static fromStruct(t){const n=zo.fromStruct(t.id);return no.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return zo.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 yu extends FP{constructor(n,r,i){super(r);k(this,"id");k(this,"removedAt");k(this,"prev");k(this,"next");k(this,"insPrev");k(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new yu(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(J.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,i){if(!t.length)return[[],new Map,new Map];const[o,a]=this.filterNodes(t,n,r,i),s=new Map,u=new Map,d=this.makeChanges(a,n);for(const h of o){const p=h.getCreatedAt().getActorID();(!s.has(p)||h.getID().getCreatedAt().after(s.get(p)))&&s.set(p,h.getID().getCreatedAt()),u.set(h.getID().toIDString(),h),h.remove(n)}return this.deleteIndexNodes(a),[d,s,u]}filterNodes(t,n,r,i){const o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const h=d.getCreatedAt().getActorID();let p,g=0n;i===void 0&&r===void 0?g=R0:i.size()>0?g=i.get(h)?i.get(h):0n:p=r.has(h)?r.get(h):to,d.canDelete(n,p,g)?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 Ko=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))(Ko||{});class Ur extends Oh{constructor(n,r,i){super(i);k(this,"valueType");k(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=at.fromNumber(r).toInt():this.value=Bx(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=at.fromNumber(r):this.value=r;break;default:throw new Y(J.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 at.fromBytesLE(Array.from(r));default:throw new Y(J.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 at?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(J.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()===Cn.Long?this.value=this.value+n.getValue().toInt():this.value=at.fromNumber(this.value+Bx(n.getValue())).toInt(),this}}class fd extends so{constructor(n,r,i){super(n,i);k(this,"value");this.value=r}static create(n,r,i){return new fd(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(J.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ur))throw new Y(J.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()===Cn.Long?n.getValue().multiply(-1):n.getValue()*-1;return fd.create(this.getParentCreatedAt(),Jt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ys extends so{constructor(n,r,i,o,a,s,u){super(n,u);k(this,"fromPos");k(this,"toPos");k(this,"maxCreatedAtMapByActor");k(this,"attributes");k(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 ys(n,r,i,o,a,[],s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ys(n,r,i,o,new Map,a,s)}execute(n,r,i){const o=n.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new Y(J.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Pi))throw new Y(J.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const a=o;let s,u;if(this.attributes.size){const d={};[...this.attributes].forEach(([h,p])=>d[h]=p),[,u,s]=a.style([this.fromPos,this.toPos],d,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}else{const d=this.attributesToRemove;[,u,s]=a.removeStyle([this.fromPos,this.toPos],d,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}for(const d of u)n.registerGCPair(d);return{opInfos:s.map(({from:d,to:h,value:p,fromPath:g,toPath:m})=>({type:"tree-style",from:d,to:h,value:this.attributes.size?{attributes:p}:{attributesToRemove:p},fromPath:g,toPath:m,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 IKe(e){const t=new OC,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function DKe(e){if(e.type===Du.Put)return new ch({type:Dl.PUT,presence:IKe(e.presence)});if(e.type===Du.Clear)return new ch({type:Dl.CLEAR});throw new Y(J.ErrUnimplemented,"unimplemented type")}function TKe(e){return new MP({serverSeq:e.getServerSeq(),clientSeq:e.getClientSeq()})}function VP(e){return new y1({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:XC(e.getActorID()),versionVector:HC(e.getVersionVector())})}function Te(e){if(e)return new Ie({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:XC(e.getActorID())})}function HC(e){if(!e)return;const t=new E1;for(const[n,r]of e)t.vector[n]=BigInt(r.toString());return t}function GP(e){switch(e){case Cn.Null:return Ve.NULL;case Cn.Boolean:return Ve.BOOLEAN;case Cn.Integer:return Ve.INTEGER;case Cn.Long:return Ve.LONG;case Cn.Double:return Ve.DOUBLE;case Cn.String:return Ve.STRING;case Cn.Bytes:return Ve.BYTES;case Cn.Date:return Ve.DATE;default:throw new Y(J.ErrInvalidType,`unsupported type: ${e}`)}}function JP(e){switch(e){case Ko.IntegerCnt:return Ve.INTEGER_CNT;case Ko.LongCnt:return Ve.LONG_CNT;default:throw new Y(J.ErrInvalidType,`unsupported type: ${e}`)}}function i2(e){if(e instanceof wr)return new li({type:Ve.JSON_OBJECT,createdAt:Te(e.getCreatedAt()),value:aB(e)});if(e instanceof jr)return new li({type:Ve.JSON_ARRAY,createdAt:Te(e.getCreatedAt()),value:aVe(e)});if(e instanceof Ti)return new li({type:Ve.TEXT,createdAt:Te(e.getCreatedAt())});if(e instanceof Jt)return new li({type:GP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ur)return new li({type:JP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Pi)return new li({type:Ve.TREE,createdAt:Te(e.getCreatedAt()),value:uVe(e)});throw new Y(J.ErrUnimplemented,"unimplemented element")}function PKe(e){return new uh({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function Sp(e){return new Is({createdAt:Te(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function xp(e){return new Il({parentId:F0(e.getParentID()),leftSiblingId:F0(e.getLeftSiblingID())})}function F0(e){return new mu({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function WP(e){const t=new LC;if(e instanceof Tl){const n=e,r=new Ug;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.key=n.getKey(),r.value=i2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof _h){const n=e,r=new Kg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.value=i2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof au){const n=e,r=new Vg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof Tu){const n=e,r=new Gg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof Nh){const n=e,r=new Jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Sp(n.getFromPos()),r.to=Sp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof zh){const n=e,r=new Wg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Sp(n.getFromPos()),r.to=Sp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof fd){const n=e,r=new Yg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.value=i2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof Hh){const n=e,r=new qg,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=Te(a);r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=xp(n.getFromPos()),r.to=xp(n.getToPos()),r.contents=OKe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=Te(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ys){const n=e,r=new Xg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=xp(n.getFromPos()),r.to=xp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(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=Te(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(J.ErrUnimplemented,"unimplemented operation");return t}function BKe(e){const t=[];for(const n of e)t.push(WP(n));return t}function MKe(e){const t=new PP({id:VP(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=BKe(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=DKe(e.getPresenceChange())),t}function $Ke(e){const t=[];for(const n of e)t.push(MKe(n));return t}function RKe(e){const t=[];for(const n of e)t.push(new BP({key:n.getStrKey(),element:UC(n.getValue())}));return t}function FKe(e){const t=[];for(const n of e)t.push(new im({element:UC(n.getValue())}));return t}function LKe(e){const t=[];for(const n of e){const r=new om;r.id=PKe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=Te(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new ud;s.value=a.getValue(),s.updatedAt=Te(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function OKe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new am({content:jC(n)}));return t}function _Ke(e){const t={};for(const n of e)t[n.getKey()]=new ud({value:n.getValue(),updatedAt:Te(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function jC(e){if(!e)return[];const t=[];return b1(e,(n,r)=>{const i=new lh({id:F0(n.id),type:n.type,removedAt:Te(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=F0(n.insPrevID)),n.insNextID&&(i.insNextId=F0(n.insNextID)),n.attrs&&(i.attributes=_Ke(n.attrs)),t.push(i)}),t}function NKe(e){const t=new Sr;return t.body.case="jsonObject",t.body.value=new Zg({nodes:RKe(e.getRHT()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function YP(e){const t=new Sr;return t.body.case="jsonArray",t.body.value=new Qg({nodes:FKe(e.getElements()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function zKe(e){const t=new Sr;return t.body.case="primitive",t.body.value=new em({type:GP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function HKe(e){const t=new Sr;return t.body.case="text",t.body.value=new tm({nodes:LKe(e.getRGATreeSplit()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function jKe(e){const t=new Sr;return t.body.case="counter",t.body.value=new nm({type:JP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function qP(e){const t=new Sr;return t.body.case="tree",t.body.value=new rm({nodes:jC(e.getRoot()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function UC(e){if(e instanceof wr)return NKe(e);if(e instanceof jr)return YP(e);if(e instanceof Jt)return zKe(e);if(e instanceof Ti)return HKe(e);if(e instanceof Ur)return jKe(e);if(e instanceof Pi)return qP(e);throw new Y(J.ErrUnimplemented,"unimplemented element")}function UKe(e){return new Rs({documentKey:e.getDocumentKey(),checkpoint:TKe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:$Ke(e.getChanges()),snapshot:e.getSnapshot(),versionVector:HC(e.getVersionVector()),minSyncedTicket:Te(e.getMinSyncedTicket())})}function f0(e){if(!(e instanceof Nt))return{};const t=e.findDetails(uKe);for(const n of t)return n.metadata;return{}}function dc(e){return f0(e).code??""}function XP(e){return as.of(e.clientSeq,BigInt(e.lamport),YC(e.actorId),KC(e.versionVector),BigInt(e.serverSeq))}function KC(e){if(!e)return;const t=new jc;return Object.entries(e.vector).forEach(([n,r])=>{t.set(n,BigInt(r.toString()))}),t}function Pe(e){if(e)return Ai.of(BigInt(e.lamport),e.delimiter,YC(e.actorId))}function VC(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function KKe(e){const t=e.type;if(t===Dl.PUT){const n=VC(e.presence);return{type:Du.Put,presence:n}}if(t===Dl.CLEAR)return{type:Du.Clear};throw new Y(J.ErrInvalidType,`unsupported type: ${t}`)}function VKe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,VC(r))}),t}function ZP(e){switch(e){case Ve.NULL:return Cn.Null;case Ve.BOOLEAN:return Cn.Boolean;case Ve.INTEGER:return Cn.Integer;case Ve.LONG:return Cn.Long;case Ve.DOUBLE:return Cn.Double;case Ve.STRING:return Cn.String;case Ve.BYTES:return Cn.Bytes;case Ve.DATE:return Cn.Date}throw new Y(J.ErrUnimplemented,`unimplemented value type: ${e}`)}function lm(e){switch(e){case Ve.INTEGER_CNT:return Ko.IntegerCnt;case Ve.LONG_CNT:return Ko.LongCnt}throw new Y(J.ErrUnimplemented,`unimplemented value type: ${e}`)}function o2(e){switch(e.type){case Ve.JSON_OBJECT:return e.value?oB(e.value):wr.create(Pe(e.createdAt));case Ve.JSON_ARRAY:return e.value?oVe(e.value):jr.create(Pe(e.createdAt));case Ve.TEXT:return Ti.create(hd.create(),Pe(e.createdAt));case Ve.TREE:return sVe(e.value);case Ve.NULL:case Ve.BOOLEAN:case Ve.INTEGER:case Ve.LONG:case Ve.DOUBLE:case Ve.STRING:case Ve.BYTES:case Ve.DATE:return Jt.of(Jt.valueFromBytes(ZP(e.type),e.value),Pe(e.createdAt));case Ve.INTEGER_CNT:case Ve.LONG_CNT:return Ur.create(lm(e.type),Ur.valueFromBytes(lm(e.type),e.value),Pe(e.createdAt))}}function Ap(e){return no.of(zo.of(Pe(e.createdAt),e.offset),e.relativeOffset)}function QP(e){return zo.of(Pe(e.createdAt),e.offset)}function GKe(e){const t=ph.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Pe(i.updatedAt))});const n=yu.create(QP(e.id),t);return n.remove(Pe(e.removedAt)),n}function hc(e){return Xi.of(L0(e.parentId),L0(e.leftSiblingId))}function L0(e){return Fn.of(Pe(e.createdAt),e.offset)}function JKe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=GC(n.content);t.push(r)}),t}function GC(e){if(e.length===0)return;const t=[];for(const i of e)t.push(YKe(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(),Pi.create(n,to).getRoot()}function WKe(e){const t=Ds.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Pe(r.updatedAt),r.isRemoved);return t}function YKe(e){const t=L0(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=WKe(e.attributes)),e.insPrevId&&(n.insPrevID=L0(e.insPrevId)),e.insNextId&&(n.insNextID=L0(e.insNextId)),n.removedAt=Pe(e.removedAt),n}function eB(e){if(e.body.case==="set"){const t=e.body.value;return Tl.create(t.key,o2(t.value),Pe(t.parentCreatedAt),Pe(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return _h.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),o2(t.value),Pe(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return au.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return Tu.create(Pe(t.parentCreatedAt),Pe(t.createdAt),Pe(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,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),Nh.create(Pe(t.parentCreatedAt),Ap(t.from),Ap(t.to),n,t.content,r,Pe(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,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),zh.create(Pe(t.parentCreatedAt),Ap(t.from),Ap(t.to),n,r,Pe(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return fd.create(Pe(t.parentCreatedAt),o2(t.value),Pe(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,Pe(i))}),Hh.create(Pe(t.parentCreatedAt),hc(t.from),hc(t.to),JKe(t.contents),t.splitLevel,n,Pe(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,Pe(a))}),(r==null?void 0:r.length)>0?ys.createTreeRemoveStyleOperation(Pe(t.parentCreatedAt),hc(t.from),hc(t.to),i,r,Pe(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ys.create(Pe(t.parentCreatedAt),hc(t.from),hc(t.to),i,n,Pe(t.executedAt)))}else throw new Y(J.ErrUnimplemented,"unimplemented operation")}}function qKe(e){const t=[];for(const n of e){const r=eB(n);r&&t.push(r)}return t}function tB(e){const t=[];for(const n of e)t.push(dd.create({id:XP(n.id),operations:qKe(n.operations),presenceChange:n.presenceChange?KKe(n.presenceChange):void 0,message:n.message}));return t}function XKe(e){return Uc.of(BigInt(e.serverSeq),e.clientSeq)}function ZKe(e){return w1.create(e.documentKey,XKe(e.checkpoint),e.isRemoved,tB(e.changes),KC(e.versionVector),e.snapshot,Pe(e.minSyncedTicket))}function nB(e){const t=new dh;for(const r of e.nodes){const i=JC(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new wr(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function rB(e){const t=new fh;for(const r of e.nodes)t.insert(JC(r.element));const n=new jr(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function QKe(e){const t=Jt.of(Jt.valueFromBytes(ZP(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function eVe(e){const t=new hd;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,GKe(i));i.insPrevId&&o.setInsPrev(t.findNode(QP(i.insPrevId))),n=o}const r=new Ti(t,Pe(e.createdAt));return r.setMovedAt(Pe(e.movedAt)),r.setRemovedAt(Pe(e.removedAt)),r}function tVe(e){const t=Ur.create(lm(e.type),Ur.valueFromBytes(lm(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function iB(e){const t=GC(e.nodes);return Pi.create(t,Pe(e.createdAt))}function JC(e){if(e.body.case==="jsonObject")return nB(e.body.value);if(e.body.case==="jsonArray")return rB(e.body.value);if(e.body.case==="primitive")return QKe(e.body.value);if(e.body.case==="text")return eVe(e.body.value);if(e.body.case==="counter")return tVe(e.body.value);if(e.body.case==="tree")return iB(e.body.value);throw new Y(J.ErrUnimplemented,"unimplemented element")}function nVe(e){if(!e)return{root:wr.create(to),presences:new Map};const t=Yy.fromBinary(e);return{root:JC(t.root),presences:VKe(t.presences)}}function rVe(e){const t=HC(e);return WC(t.toBinary())}function iVe(e){const t=qC(e),n=E1.fromBinary(t);return KC(n)}function oB(e){if(!e)throw new Y(J.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return nB(t.body.value)}function aB(e){return UC(e).toBinary()}function oVe(e){if(!e)throw new Y(J.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return rB(t.body.value)}function aVe(e){return YP(e).toBinary()}function sVe(e){if(!e)throw new Y(J.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return iB(t.body.value)}function uVe(e){return qP(e).toBinary()}function WC(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function YC(e){return WC(e)}function qC(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function XC(e){return qC(e)}function lVe(e){const t=y1.fromBinary(e);return XP(t)}function cVe(e){const t=LC.fromBinary(e);return eB(t)}const on={fromPresence:VC,toChangePack:UKe,fromChangePack:ZKe,fromChanges:tB,toTreeNodes:jC,fromTreeNodes:GC,objectToBytes:aB,bytesToObject:oB,bytesToSnapshot:nVe,bytesToHex:WC,hexToBytes:qC,toHexString:YC,toUint8Array:XC,toOperation:WP,toChangeID:VP,PbChangeID:y1,bytesToChangeID:lVe,bytesToOperation:cVe,versionVectorToHex:rVe,hexToVersionVector:iVe};var or=(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))(or||{});let tl=3;function sB(e){tl=e}const $e={trivial:(...e)=>{tl>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{tl>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{tl>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{tl>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{tl>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=>tl<=e};function uB(){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 dVe{constructor(t,n,r,i,o){k(this,"reconnectStreamDelay");k(this,"doc");k(this,"docID");k(this,"syncMode");k(this,"remoteChangeEventReceived");k(this,"watchStream");k(this,"watchLoopTimerID");k(this,"watchAbortController");k(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===Xp.RealtimeSyncOff?!1:this.syncMode===Xp.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Xp.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 a2=()=>{};class hVe{constructor(t){k(this,"finalized",!1);k(this,"observers",[]);k(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(J.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(J.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=a2),i.error===void 0&&(i.error=a2),i.complete===void 0&&(i.complete=a2);const o=uB(),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){$e.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 Pc{constructor(t,n,r,i){k(this,"id");k(this,"delimiter");k(this,"message");k(this,"root");k(this,"operations");k(this,"presenceChange");k(this,"previousPresence");k(this,"reversePresenceKeys");this.id=t,this.delimiter=RP,this.root=n,this.operations=[],this.previousPresence=Gi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new Pc(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 dd.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 gh{constructor(t){k(this,"rootObject");k(this,"elementPairMapByCreatedAt");k(this,"gcElementSetByCreatedAt");k(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 Ti||n instanceof Pi)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new gh(wr.create(to))}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(J.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 vu&&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 vu&&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 vu&&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 gh(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),o=i.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function lB(e,t){const n=new mh(e);return new Proxy(t,n.getHandlers())}class mh{constructor(t){k(this,"context");k(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]=${JSON.stringify(i)}`),mh.setInternal(t,n,r,i),!0),get:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():nl(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),mh.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(J.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=cm(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(Tl.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(J.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=cm(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(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function pVe(e,t){const n=new Xt(e,t);return new Proxy(t,n.getHandlers())}function gVe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function mVe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class Xt{constructor(t,n){k(this,"context");k(this,"handlers");k(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 Xs(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return Xs(t,s)}:i==="getLast"?()=>Xs(t,r.getLast()):i==="deleteByID"?a=>{const s=Xt.deleteInternalByID(t,r,a);return Xs(t,s)}:i==="insertAfter"?(a,s)=>{const u=Xt.insertAfterInternal(t,r,a,s);return Xs(t,u)}:i==="insertBefore"?(a,s)=>{const u=Xt.insertBeforeInternal(t,r,a,s);return Xs(t,u)}:i==="moveBefore"?(a,s)=>{Xt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{Xt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{Xt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{Xt.moveLastInternal(t,r,a)}:gVe(i)?nl(t,r.get(Number(i))):i==="push"?a=>Xt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>Xt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?Xt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>Xt.includes(t,r,a,s):i==="indexOf"?(a,s)=>Xt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>Xt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>Xt.toTestString(r):typeof i=="string"&&mVe(i)?(...a)=>{const s=Array.from(r).map(u=>nl(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`array[${i}]`),Xt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield Xs(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=cm(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return Xt.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(au.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(au.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(au.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(au.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=cm(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(_h.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return Xt.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(Tu.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(Tu.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 h=s;h=o)return!1;if(Jt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Jt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Jt.isSupport(r))return Array.from(n).map(d=>nl(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 S1{constructor(t,n){k(this,"context");k(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(J.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(J.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?ld(i):void 0,s=this.context.issueTimeTicket(),[u,,d,h]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new Nh(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(h)}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(J.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(J.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=ld(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 zh(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(J.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(J.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([no.fromStruct(t[0]),no.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(J.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(J.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(J.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(J.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(J.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(J.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class x1{constructor(t,n){k(this,"valueType");k(this,"value");k(this,"context");k(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(J.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Jt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(fd.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(J.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ZC(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===vs){cB(e);const{value:o}=e,a=Nr.create(Fn.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!$P(a)){const d=ld(a);s=new Ds;for(const[h,p]of Object.entries(d))s.set(h,p,i)}const u=Nr.create(Fn.of(i,0),r,void 0,s);t.append(u);for(const d of o)ZC(d,u,n)}}function vVe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===vs){const{value:o}=t;i=Nr.create(Fn.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!$P(a)){const u=ld(a);s=new Ds;for(const[d,h]of Object.entries(u))s.set(d,h,r)}i=Nr.create(Fn.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)ZC(u,i,e)}return i}function cB(e){if(!e.value.length)throw new Y(J.ErrInvalidArgument,"text node cannot have empty value");return!0}function Mx(e){if(!e.length)return!0;if(e[0].type===vs)for(const n of e){const{type:r}=n;if(r!==vs)throw new Y(J.ErrInvalidArgument,"element node and text node cannot be passed together");cB(n)}else for(const n of e){const{type:r}=n;if(r===vs)throw new Y(J.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class A1{constructor(t){k(this,"initialRoot");k(this,"context");k(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(Fn.of(t.issueTimeTicket(),0),gKe);const n=Nr.create(Fn.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ZC(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(J.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?ld(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ys.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(J.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?ld(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const h of d)this.context.registerGCPair(h);this.context.push(ys.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(J.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(ys.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Mx(r),r[0].type!==vs))for(const h of r){const{children:p=[]}=h;Mx(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===vs){let h="";for(const p of r){const{value:g}=p;h+=g}a.push(Nr.create(Fn.of(this.context.issueTimeTicket(),0),vs,h))}else a=r.map(h=>h&&vVe(this.context,h)).filter(h=>h);const[,s,u]=this.tree.edit([t,n],a.length?a.map(h=>h==null?void 0:h.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const h of s)this.context.registerGCPair(h);return this.context.push(Hh.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(J.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(J.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(J.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(J.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(J.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(J.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(J.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(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(J.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(J.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(J.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function $x(e,t){return lB(e,t)}function Xs(e,t){if(t){if(t instanceof Jt)return t;if(t instanceof wr)return lB(e,t);if(t instanceof jr)return pVe(e,t);if(t instanceof Ti)return new S1(e,t);if(t instanceof Ur){const n=new x1(Ko.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Pi){const n=new A1;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function nl(e,t){const n=Xs(e,t);return n instanceof Jt?n.getValue():n}function cm(e,t,n){let r;if(Jt.isSupport(t))r=Jt.of(t,n);else if(Array.isArray(t))r=jr.create(n,Xt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof S1?(r=Ti.create(hd.create(),n),t.initialize(e,r)):t instanceof x1?(r=Ur.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof A1?(r=Pi.create(t.buildRoot(e),n),t.initialize(e,r)):r=wr.create(n,mh.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const Rx=50;class yVe{constructor(){k(this,"undoStack",[]);k(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Rx&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Rx&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const EVe="yorkie-devtools-panel",CVe="yorkie-devtools-sdk";let pc="disconnected";const Fx=new Map,qp=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=qp);function kp(e,t){(t!=null&&t.force||pc!=="disconnected")&&window.postMessage({source:CVe,...e},"*")}function bVe(e){if(!e.isEnableDevtools()||typeof window>"u"||Fx.has(e.getKey()))return;qp.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==bn.StatusChanged&&r.type!==bn.Snapshot&&r.type!==bn.LocalChange&&r.type!==bn.RemoteChange&&r.type!==bn.Initialized&&r.type!==bn.Watched&&r.type!==bn.Unwatched&&r.type!==bn.PresenceChanged)||(qp.get(e.getKey()).push(n),pc==="synced"&&kp({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Fx.set(e.getKey(),[t]),kp({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==EVe)return;switch(n.data.msg){case"devtools::connect":if(pc!=="disconnected")break;pc="connected",kp({msg:"doc::available",docKey:e.getKey()}),$e.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":pc="disconnected",$e.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":pc="synced",kp({msg:"doc::sync::full",docKey:e.getKey(),events:qp.get(e.getKey())}),$e.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Zs=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Zs||{}),bn=(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.AuthError="auth-error",e))(bn||{}),b3=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(b3||{}),w3=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(w3||{});class QC{constructor(t,n){k(this,"key");k(this,"status");k(this,"opts");k(this,"changeID");k(this,"checkpoint");k(this,"localChanges");k(this,"root");k(this,"clone");k(this,"eventStream");k(this,"eventStreamObserver");k(this,"onlineClients");k(this,"presences");k(this,"history");k(this,"internalHistory");k(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=gh.create(),this.changeID=xKe,this.checkpoint=AKe,this.localChanges=[],this.eventStream=fVe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new yVe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},bVe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(J.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=$x(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new r2(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){$e.isEnabled(or.Trivial)&&$e.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,xt.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:xt.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:xt.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),$e.isEnabled(or.Trivial)&&$e.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(J.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==="auth-error"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="auth-error"&&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 h of u.value.operations)this.isSameElementOrChildOf(h.path,o)&&d.push(h);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(J.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])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const n=t.hasSnapshot();n?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),xt.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),n||this.garbageCollect(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),$e.isEnabled(or.Trivial)&&$e.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:Gi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return w1.create(this.key,n,!1,t,this.getVersionVector())}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=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return $x(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n,r,i=-1){const{root:o,presences:a}=on.bytesToSnapshot(r);this.root=new gh(o),this.presences=a,this.changeID=this.changeID.setClocks(n.maxLamport(),n),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,xt.Local),this.publish([{type:"snapshot",source:xt.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?on.bytesToHex(r):void 0,snapshotVector:on.versionVectorToHex(n)}}])}applyChanges(t,n){$e.isEnabled(or.Debug)&&$e.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),$e.isEnabled(or.Trivial)&&$e.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of t)this.applyChange(r,n);$e.isEnabled(or.Debug)&&$e.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 Du.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:xt.Remote,value:{clientID:i,presence:a.presence}});break;case Du.Clear:r.push({type:"unwatched",source:xt.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.syncClocks(t.getID()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===xt.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:xt.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===ml.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(n===ml.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:xt.Remote,value:{clientID:r,presence:o}})}else if(n===ml.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(C1),this.publish([{source:t==="removed"?xt.Remote:xt.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,snapshotVector:i}=t.value;if(!n)return;this.applySnapshot(BigInt(r),on.hexToVersionVector(i),on.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=dd.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(J.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?Gi(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?Gi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Gi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Gi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Gi(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}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(J.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(J.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new r2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.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:xt.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:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(J.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(J.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new r2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.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:xt.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:xt.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])}getVersionVector(){return this.changeID.getVersionVector()}}function wVe(e,t){let n=t;return{authInterceptor:o=>async a=>(e&&a.header.set("x-api-key",e),n&&a.header.set("authorization",n),await o(a)),setToken:o=>{n=o}}}const SVe="yorkie-js-sdk",xVe="0.5.6",AVe="Yorkie JS SDK",kVe="./src/yorkie.ts",IVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},DVe=["dist"],TVe={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"},PVe={node:">=18.0.0",npm:">=7.1.0"},BVe={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},MVe={name:"hackerwins",email:"susukang98@gmail.com"},$Ve="Apache-2.0",RVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},FVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",LVe={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},OVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Lx={name:SVe,version:xVe,description:AVe,main:kVe,publishConfig:IVe,files:DVe,scripts:TVe,engines:PVe,repository:BVe,author:MVe,license:$Ve,bugs:RVe,homepage:FVe,devDependencies:LVe,dependencies:OVe};function _Ve(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Lx.name+"/"+Lx.version),await e(t))}const NVe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Xp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Xp||{});const Ip={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},s2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class e9{constructor(t,n){k(this,"id");k(this,"key");k(this,"status");k(this,"attachmentMap");k(this,"apiKey");k(this,"authTokenInjector");k(this,"conditions");k(this,"syncLoopDuration");k(this,"reconnectStreamDelay");k(this,"retrySyncLoopDelay");k(this,"rpcClient");k(this,"setAuthToken");k(this,"taskQueue");k(this,"processing",!1);k(this,"keepalive",!1);n=n||Ip,this.key=n.key?n.key:uB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.authTokenInjector=n.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration??Ip.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay??Ip.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay??Ip.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=wVe(this.apiKey);this.setAuthToken=i,this.rpcClient=_Ue(sKe,aKe({baseUrl:t,interceptors:[r,_Ve()],fetch:(o,a)=>{const s={...a,keepalive:this.keepalive};return fetch(o,s)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const n=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw $e.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(t.keepalive){this.keepalive=!0;const r=n();return this.keepalive=!1,r}return this.enqueueTask(n)}attach(t,n={}){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Zs.Detached)throw new Y(J.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 h;const{topic:a,payload:s}=o.value,u=(h=o.options)==null?void 0:h.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:on.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=on.fromChangePack(o.changePack);if(t.applyChangePack(a),t.getStatus()===Zs.Removed)return t;t.applyStatus(Zs.Attached),this.attachmentMap.set(t.getKey(),new dVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const s=t.getRootObject();if(n.initialRoot){const u=n.initialRoot;t.update(d=>{for(const[h,p]of Object.entries(u))if(!s.has(h)){const g=h;d[g]=p}})}return t}).catch(async o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),await this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(J.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:on.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=on.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Zs.Removed&&t.applyStatus(Zs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(J.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(J.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(J.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(async r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(J.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=on.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=on.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),await 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(J.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(J.ErrDocumentNotAttached,`${t} is not attached`);if(!NVe(r))throw new Y(J.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??s2.maxRetries,s=s2.maxBackoff;let u=0;const d=p=>Math.min(s2.initialRetryInterval*2**p,s),h=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(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(async p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),await this.handleConnectError(p))if(p instanceof Nt&&dc(p)===J.ErrUnauthenticated&&o.doc.publish([{type:bn.AuthError,value:{reason:f0(p).reason,method:"Broadcast"}}]),uh(),d(u-1)),$e.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw $e.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const t=()=>{if(!this.isActive()){$e.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).catch(async i=>{throw i instanceof Nt&&dc(i)===J.ErrUnauthenticated&&r.doc.publish([{type:bn.AuthError,value:{reason:f0(i).reason,method:"PushPull"}}]),i})));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};$e.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(J.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(J.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:bn.ConnectionChanged,value:b3.Connected}]),$e.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:bn.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:bn.ConnectionChanged,value:b3.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(d)?(d instanceof Nt&&dc(d)===J.ErrUnauthenticated&&n.doc.publish([{type:bn.AuthError,value:{reason:f0(d).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===ml.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(Zs.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:on.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=on.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:bn.SyncStatusChanged,value:w3.Synced}]),r.getStatus()===Zs.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return $e.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(async a=>{throw r.publish([{type:bn.SyncStatusChanged,value:w3.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}async handleConnectError(t){if(!(t instanceof Nt))return!1;if(t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable)return!0;if(dc(t)===J.ErrUnauthenticated){if(this.authTokenInjector){const n=await this.authTokenInjector(f0(t).reason);this.setAuthToken(n)}return!0}return(dc(t)===J.ErrClientNotActivated||dc(t)===J.ErrClientNotFound)&&this.deactivateInternal(),!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{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Ko.IntegerCnt,Ko.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:e9,Document:QC,Primitive:Jt,Text:S1,Counter:x1,Tree:A1,LogLevel:or,setLogLevel:sB,IntType:Ko.IntegerCnt,LongType:Ko.LongCnt});var S3={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(fc,function(){var n=null,r={};C();var i=[],o=function(I){if(I=I||{},I.seed!==void 0&&I.seed!==null&&I.seed===parseInt(I.seed,10))n=I.seed;else if(typeof I.seed=="string")n=B(I.seed);else{if(I.seed!==void 0&&I.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var M,O,z;if(I.count!==null&&I.count!==void 0){for(var K=I.count,X=[],Z=0;ZX.length;){var pe=o(I);n!==null&&(I.seed=n),X.push(pe)}return I.count=K,X}return M=a(I),O=s(M,I),z=u(M,O,I),d([M,O,z],I)};function a(I){if(i.length>0){var M=D(I.hue),O=v(M),z=(M[1]-M[0])/i.length,K=parseInt((O-M[0])/z);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var X=(M[0]+K*z)%359,Z=(M[0]+(K+1)*z)%359;return M=[X,Z],O=v(M),O<0&&(O=360+O),O}else{var M=p(I.hue);return O=v(M),O<0&&(O=360+O),O}}function s(I,M){if(M.hue==="monochrome")return 0;if(M.luminosity==="random")return v([0,100]);var O=g(I),z=O[0],K=O[1];switch(M.luminosity){case"bright":z=55;break;case"dark":z=K-10;break;case"light":K=55;break}return v([z,K])}function u(I,M,O){var z=h(I,M),K=100;switch(O.luminosity){case"dark":K=z+20;break;case"light":z=(K+z)/2;break;case"random":z=0,K=100;break}return v([z,K])}function d(I,M){switch(M.format){case"hsvArray":return I;case"hslArray":return T(I);case"hsl":var O=T(I);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var z=T(I),Z=M.alpha||Math.random();return"hsla("+z[0]+", "+z[1]+"%, "+z[2]+"%, "+Z+")";case"rgbArray":return b(I);case"rgb":var K=b(I);return"rgb("+K.join(", ")+")";case"rgba":var X=b(I),Z=M.alpha||Math.random();return"rgba("+X.join(", ")+", "+Z+")";default:return E(I)}}function h(I,M){for(var O=m(I).lowerBounds,z=0;z=K&&M<=Z){var me=(pe-X)/(Z-K),Ce=X-me*K;return me*M+Ce}}return 0}function p(I){if(typeof parseInt(I)=="number"){var M=parseInt(I);if(M<360&&M>0)return[M,M]}if(typeof I=="string"){if(r[I]){var O=r[I];if(O.hueRange)return O.hueRange}else if(I.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var z=A(I)[0];return[z,z]}}return[0,360]}function g(I){return m(I).saturationRange}function m(I){I>=334&&I<=360&&(I-=360);for(var M in r){var O=r[M];if(O.hueRange&&I>=O.hueRange[0]&&I<=O.hueRange[1])return r[M]}return"Color not found"}function v(I){if(n===null){var M=.618033988749895,O=Math.random();return O+=M,O%=1,Math.floor(I[0]+O*(I[1]+1-I[0]))}else{var z=I[1]||1,K=I[0]||0;n=(n*9301+49297)%233280;var X=n/233280;return Math.floor(K+X*(z-K))}}function E(I){var M=b(I);function O(K){var X=K.toString(16);return X.length==1?"0"+X:X}var z="#"+O(M[0])+O(M[1])+O(M[2]);return z}function w(I,M,O){var z=O[0][0],K=O[O.length-1][0],X=O[O.length-1][1],Z=O[0][1];r[I]={hueRange:M,lowerBounds:O,saturationRange:[z,K],brightnessRange:[X,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(I){var M=I[0];M===0&&(M=1),M===360&&(M=359),M=M/360;var O=I[1]/100,z=I[2]/100,K=Math.floor(M*6),X=M*6-K,Z=z*(1-O),pe=z*(1-X*O),me=z*(1-(1-X)*O),Ce=256,W=256,U=256;switch(K){case 0:Ce=z,W=me,U=Z;break;case 1:Ce=pe,W=z,U=Z;break;case 2:Ce=Z,W=z,U=me;break;case 3:Ce=Z,W=pe,U=z;break;case 4:Ce=me,W=Z,U=z;break;case 5:Ce=z,W=Z,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(W*255),Math.floor(U*255)];return ne}function A(I){I=I.replace(/^#/,""),I=I.length===3?I.replace(/(.)/g,"$1$1"):I;var M=parseInt(I.substr(0,2),16)/255,O=parseInt(I.substr(2,2),16)/255,z=parseInt(I.substr(4,2),16)/255,K=Math.max(M,O,z),X=K-Math.min(M,O,z),Z=K?X/K:0;switch(K){case M:return[60*((O-z)/X%6)||0,Z,K];case O:return[60*((z-M)/X+2)||0,Z,K];case z:return[60*((M-O)/X+4)||0,Z,K]}}function T(I){var M=I[0],O=I[1]/100,z=I[2]/100,K=(2-O)*z;return[M,Math.round(O*z/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(I){for(var M=0,O=0;O!==I.length&&!(M>=Number.MAX_SAFE_INTEGER);O++)M+=I.charCodeAt(O);return M}function D(I){if(isNaN(I)){if(typeof I=="string"){if(r[I]){var O=r[I];if(O.hueRange)return O.hueRange}else if(I.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var z=A(I)[0];return m(z).hueRange}}}else{var M=parseInt(I);if(M<360&&M>0)return m(I).hueRange}return[0,360]}return o})})(S3,S3.exports);var zVe=S3.exports;const HVe=vh(zVe),Ox=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 jVe{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. +`));for(const r of t)this.applyChange(r,n);$e.isEnabled(or.Debug)&&$e.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 Du.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:xt.Remote,value:{clientID:i,presence:a.presence}});break;case Du.Clear:r.push({type:"unwatched",source:xt.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.syncClocks(t.getID()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===xt.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:xt.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===ml.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(n===ml.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:xt.Remote,value:{clientID:r,presence:o}})}else if(n===ml.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(C1),this.publish([{source:t==="removed"?xt.Remote:xt.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,snapshotVector:i}=t.value;if(!n)return;this.applySnapshot(BigInt(r),on.hexToVersionVector(i),on.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=dd.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(J.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?Gi(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?Gi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Gi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Gi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Gi(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}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(J.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(J.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new r2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.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:xt.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:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(J.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(J.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Pc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new r2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.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:xt.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:xt.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])}getVersionVector(){return this.changeID.getVersionVector()}}function wVe(e,t){let n=t;return{authInterceptor:o=>async a=>(e&&a.header.set("x-api-key",e),n&&a.header.set("authorization",n),await o(a)),setToken:o=>{n=o}}}const SVe="yorkie-js-sdk",xVe="0.5.7",AVe="Yorkie JS SDK",kVe="./src/yorkie.ts",IVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},DVe=["dist"],TVe={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"},PVe={node:">=18.0.0",npm:">=7.1.0"},BVe={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},MVe={name:"hackerwins",email:"susukang98@gmail.com"},$Ve="Apache-2.0",RVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},FVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",LVe={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},OVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Lx={name:SVe,version:xVe,description:AVe,main:kVe,publishConfig:IVe,files:DVe,scripts:TVe,engines:PVe,repository:BVe,author:MVe,license:$Ve,bugs:RVe,homepage:FVe,devDependencies:LVe,dependencies:OVe};function _Ve(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Lx.name+"/"+Lx.version),await e(t))}const NVe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Xp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Xp||{});const Ip={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},s2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class e9{constructor(t,n){k(this,"id");k(this,"key");k(this,"status");k(this,"attachmentMap");k(this,"apiKey");k(this,"authTokenInjector");k(this,"conditions");k(this,"syncLoopDuration");k(this,"reconnectStreamDelay");k(this,"retrySyncLoopDelay");k(this,"rpcClient");k(this,"setAuthToken");k(this,"taskQueue");k(this,"processing",!1);k(this,"keepalive",!1);n=n||Ip,this.key=n.key?n.key:uB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.authTokenInjector=n.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration??Ip.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay??Ip.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay??Ip.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=wVe(this.apiKey);this.setAuthToken=i,this.rpcClient=_Ue(sKe,aKe({baseUrl:t,interceptors:[r,_Ve()],fetch:(o,a)=>{const s={...a,keepalive:this.keepalive};return fetch(o,s)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const n=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw $e.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(t.keepalive){this.keepalive=!0;const r=n();return this.keepalive=!1,r}return this.enqueueTask(n)}attach(t,n={}){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Zs.Detached)throw new Y(J.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 h;const{topic:a,payload:s}=o.value,u=(h=o.options)==null?void 0:h.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:on.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=on.fromChangePack(o.changePack);if(t.applyChangePack(a),t.getStatus()===Zs.Removed)return t;t.applyStatus(Zs.Attached),this.attachmentMap.set(t.getKey(),new dVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const s=t.getRootObject();if(n.initialRoot){const u=n.initialRoot;t.update(d=>{for(const[h,p]of Object.entries(u))if(!s.has(h)){const g=h;d[g]=p}})}return t}).catch(async o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),await this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(J.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:on.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=on.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Zs.Removed&&t.applyStatus(Zs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(J.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(J.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(J.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(async r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(J.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(J.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=on.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=on.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),await 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(J.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(J.ErrDocumentNotAttached,`${t} is not attached`);if(!NVe(r))throw new Y(J.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??s2.maxRetries,s=s2.maxBackoff;let u=0;const d=p=>Math.min(s2.initialRetryInterval*2**p,s),h=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(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(async p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),await this.handleConnectError(p))if(p instanceof Nt&&dc(p)===J.ErrUnauthenticated&&o.doc.publish([{type:bn.AuthError,value:{reason:f0(p).reason,method:"Broadcast"}}]),uh(),d(u-1)),$e.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw $e.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const t=()=>{if(!this.isActive()){$e.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).catch(async i=>{throw i instanceof Nt&&dc(i)===J.ErrUnauthenticated&&r.doc.publish([{type:bn.AuthError,value:{reason:f0(i).reason,method:"PushPull"}}]),i})));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};$e.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(J.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(J.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:bn.ConnectionChanged,value:b3.Connected}]),$e.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:bn.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:bn.ConnectionChanged,value:b3.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(d)?(d instanceof Nt&&dc(d)===J.ErrUnauthenticated&&n.doc.publish([{type:bn.AuthError,value:{reason:f0(d).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===ml.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(Zs.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:on.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=on.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:bn.SyncStatusChanged,value:w3.Synced}]),r.getStatus()===Zs.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return $e.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(async a=>{throw r.publish([{type:bn.SyncStatusChanged,value:w3.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}async handleConnectError(t){if(!(t instanceof Nt))return!1;if(t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable)return!0;if(dc(t)===J.ErrUnauthenticated){if(this.authTokenInjector){const n=await this.authTokenInjector(f0(t).reason);this.setAuthToken(n)}return!0}return(dc(t)===J.ErrClientNotActivated||dc(t)===J.ErrClientNotFound)&&this.deactivateInternal(),!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{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Ko.IntegerCnt,Ko.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:e9,Document:QC,Primitive:Jt,Text:S1,Counter:x1,Tree:A1,LogLevel:or,setLogLevel:sB,IntType:Ko.IntegerCnt,LongType:Ko.LongCnt});var S3={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(fc,function(){var n=null,r={};C();var i=[],o=function(I){if(I=I||{},I.seed!==void 0&&I.seed!==null&&I.seed===parseInt(I.seed,10))n=I.seed;else if(typeof I.seed=="string")n=B(I.seed);else{if(I.seed!==void 0&&I.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var M,O,z;if(I.count!==null&&I.count!==void 0){for(var K=I.count,X=[],Z=0;ZX.length;){var pe=o(I);n!==null&&(I.seed=n),X.push(pe)}return I.count=K,X}return M=a(I),O=s(M,I),z=u(M,O,I),d([M,O,z],I)};function a(I){if(i.length>0){var M=D(I.hue),O=v(M),z=(M[1]-M[0])/i.length,K=parseInt((O-M[0])/z);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var X=(M[0]+K*z)%359,Z=(M[0]+(K+1)*z)%359;return M=[X,Z],O=v(M),O<0&&(O=360+O),O}else{var M=p(I.hue);return O=v(M),O<0&&(O=360+O),O}}function s(I,M){if(M.hue==="monochrome")return 0;if(M.luminosity==="random")return v([0,100]);var O=g(I),z=O[0],K=O[1];switch(M.luminosity){case"bright":z=55;break;case"dark":z=K-10;break;case"light":K=55;break}return v([z,K])}function u(I,M,O){var z=h(I,M),K=100;switch(O.luminosity){case"dark":K=z+20;break;case"light":z=(K+z)/2;break;case"random":z=0,K=100;break}return v([z,K])}function d(I,M){switch(M.format){case"hsvArray":return I;case"hslArray":return T(I);case"hsl":var O=T(I);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var z=T(I),Z=M.alpha||Math.random();return"hsla("+z[0]+", "+z[1]+"%, "+z[2]+"%, "+Z+")";case"rgbArray":return b(I);case"rgb":var K=b(I);return"rgb("+K.join(", ")+")";case"rgba":var X=b(I),Z=M.alpha||Math.random();return"rgba("+X.join(", ")+", "+Z+")";default:return E(I)}}function h(I,M){for(var O=m(I).lowerBounds,z=0;z=K&&M<=Z){var me=(pe-X)/(Z-K),Ce=X-me*K;return me*M+Ce}}return 0}function p(I){if(typeof parseInt(I)=="number"){var M=parseInt(I);if(M<360&&M>0)return[M,M]}if(typeof I=="string"){if(r[I]){var O=r[I];if(O.hueRange)return O.hueRange}else if(I.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var z=A(I)[0];return[z,z]}}return[0,360]}function g(I){return m(I).saturationRange}function m(I){I>=334&&I<=360&&(I-=360);for(var M in r){var O=r[M];if(O.hueRange&&I>=O.hueRange[0]&&I<=O.hueRange[1])return r[M]}return"Color not found"}function v(I){if(n===null){var M=.618033988749895,O=Math.random();return O+=M,O%=1,Math.floor(I[0]+O*(I[1]+1-I[0]))}else{var z=I[1]||1,K=I[0]||0;n=(n*9301+49297)%233280;var X=n/233280;return Math.floor(K+X*(z-K))}}function E(I){var M=b(I);function O(K){var X=K.toString(16);return X.length==1?"0"+X:X}var z="#"+O(M[0])+O(M[1])+O(M[2]);return z}function w(I,M,O){var z=O[0][0],K=O[O.length-1][0],X=O[O.length-1][1],Z=O[0][1];r[I]={hueRange:M,lowerBounds:O,saturationRange:[z,K],brightnessRange:[X,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(I){var M=I[0];M===0&&(M=1),M===360&&(M=359),M=M/360;var O=I[1]/100,z=I[2]/100,K=Math.floor(M*6),X=M*6-K,Z=z*(1-O),pe=z*(1-X*O),me=z*(1-(1-X)*O),Ce=256,W=256,U=256;switch(K){case 0:Ce=z,W=me,U=Z;break;case 1:Ce=pe,W=z,U=Z;break;case 2:Ce=Z,W=z,U=me;break;case 3:Ce=Z,W=pe,U=z;break;case 4:Ce=me,W=Z,U=z;break;case 5:Ce=z,W=Z,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(W*255),Math.floor(U*255)];return ne}function A(I){I=I.replace(/^#/,""),I=I.length===3?I.replace(/(.)/g,"$1$1"):I;var M=parseInt(I.substr(0,2),16)/255,O=parseInt(I.substr(2,2),16)/255,z=parseInt(I.substr(4,2),16)/255,K=Math.max(M,O,z),X=K-Math.min(M,O,z),Z=K?X/K:0;switch(K){case M:return[60*((O-z)/X%6)||0,Z,K];case O:return[60*((z-M)/X+2)||0,Z,K];case z:return[60*((M-O)/X+4)||0,Z,K]}}function T(I){var M=I[0],O=I[1]/100,z=I[2]/100,K=(2-O)*z;return[M,Math.round(O*z/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(I){for(var M=0,O=0;O!==I.length&&!(M>=Number.MAX_SAFE_INTEGER);O++)M+=I.charCodeAt(O);return M}function D(I){if(isNaN(I)){if(typeof I=="string"){if(r[I]){var O=r[I];if(O.hueRange)return O.hueRange}else if(I.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var z=A(I)[0];return m(z).hueRange}}}else{var M=parseInt(I);if(M<360&&M>0)return m(I).hueRange}return[0,360]}return o})})(S3,S3.exports);var zVe=S3.exports;const HVe=vh(zVe),Ox=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 jVe{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,h)=>d+h,1),u=Math.floor(Number(s));return Ox(u)}return Ox(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 _x={separator:"_",dictionaries:[]},UVe=e=>{const t=[...e&&e.dictionaries||_x.dictionaries],n={..._x,...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 jVe(n).generate()};var KVe=["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"],dm={exports:{}};/** * @license * Lodash diff --git a/examples/react-tldraw/index.html b/examples/react-tldraw/index.html index e0a8d5531..4b5dce45d 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-4GhU6Gpr.js b/examples/react-todomvc/assets/index-XuPK589l.js similarity index 99% rename from examples/react-todomvc/assets/index-4GhU6Gpr.js rename to examples/react-todomvc/assets/index-XuPK589l.js index a91ed4c10..def418ef6 100644 --- a/examples/react-todomvc/assets/index-4GhU6Gpr.js +++ b/examples/react-todomvc/assets/index-XuPK589l.js @@ -59,7 +59,7 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var vt=null;try{vt=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 K(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}K.prototype.__isLong__;Object.defineProperty(K.prototype,"__isLong__",{value:!0});function Be(n){return(n&&n.__isLong__)===!0}function Xh(n){var e=Math.clz32(n&-n);return n?31-e:e}K.isLong=Be;var Zh={},eg={};function Ni(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=eg[n],r)?r:(t=H(n,0,!0),i&&(eg[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Zh[n],r)?r:(t=H(n,n<0?-1:0,!1),i&&(Zh[n]=t),t))}K.fromInt=Ni;function wt(n,e){if(isNaN(n))return e?hr:Ot;if(e){if(n<0)return hr;if(n>=ny)return sy}else{if(n<=-ng)return Ve;if(n+1>=ng)return iy}return n<0?wt(-n,e).neg():H(n%gs|0,n/gs|0,e)}K.fromNumber=wt;function H(n,e,t){return new K(n,e,t)}K.fromBits=H;var ml=Math.pow;function Yf(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?hr:Ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Yf(n.substring(1),e,t).neg();for(var i=wt(ml(t,8)),s=Ot,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*gs+(this.low>>>0):this.high*gs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+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(Ve)?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 Be(e)||(e=$t(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(Be(e)||(e=$t(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};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(Ve)?Ve:this.not().add(Wi)};C.neg=C.negate;C.add=function(e){Be(e)||(e=$t(e));var t=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,c=e.low&65535,d=0,h=0,m=0,y=0;return y+=s+c,m+=y>>>16,y&=65535,m+=i+l,h+=m>>>16,m&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,H(m<<16|y,d<<16|h,this.unsigned)};C.subtract=function(e){return Be(e)||(e=$t(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Be(e)||(e=$t(e)),vt){var t=vt.mul(this.low,this.high,e.low,e.high);return H(t,vt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?hr:Ot;if(this.eq(Ve))return e.isOdd()?Ve:Ot;if(e.eq(Ve))return this.isOdd()?Ve: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(rg)&&e.lt(rg))return wt(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,c=e.low>>>16,d=e.low&65535,h=0,m=0,y=0,w=0;return w+=o*d,y+=w>>>16,w&=65535,y+=s*d,m+=y>>>16,y&=65535,y+=o*c,m+=y>>>16,y&=65535,m+=i*d,h+=m>>>16,m&=65535,m+=s*c,h+=m>>>16,m&=65535,m+=o*l,h+=m>>>16,m&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,H(y<<16|w,h<<16|m,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Be(e)||(e=$t(e)),e.isZero())throw Error("division by zero");if(vt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?vt.div_u:vt.div_s)(this.low,this.high,e.low,e.high);return H(t,vt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hr:Ot;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return hr;if(e.gt(this.shru(1)))return ry;s=hr}else{if(this.eq(Ve)){if(e.eq(Wi)||e.eq(Kc))return Ve;if(e.eq(Ve))return Wi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Ot)?e.isNegative()?Wi:Kc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(Ve))return this.unsigned?hr: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();s=Ot}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:ml(2,a-48),c=wt(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=wt(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=Wi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Be(e)||(e=$t(e)),vt){var t=(this.unsigned?vt.rem_u:vt.rem_s)(this.low,this.high,e.low,e.high);return H(t,vt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return H(~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?Xh(this.low):Xh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Be(e)||(e=$t(e)),H(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Be(e)||(e=$t(e)),H(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Be(e)||(e=$t(e)),H(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?H(this.low<>>32-e,this.unsigned):H(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):H(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?H(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?H(this.high,0,this.unsigned):H(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?H(this.high,this.low,this.unsigned):e<32?(t=32-e,H(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,H(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?H(this.high,this.low,this.unsigned):e<32?(t=32-e,H(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,H(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?H(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:H(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]};K.fromBytes=function(e,t,r){return r?K.fromBytesLE(e,t):K.fromBytesBE(e,t)};K.fromBytesLE=function(e,t){return new K(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};K.fromBytesBE=function(e,t){return new K(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};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 se extends Do{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=se.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new se(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 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 K.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(K.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${en(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=se.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 K)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return se.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=K.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class pl extends ty{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new pl(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}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 ko{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=se.of(0,bt);e.setRemovedAt(bt),this.dummyHead=new pl(e),this.last=this.dummyHead,this.nodeMapByIndex=new So,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new ko}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.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 i=this.findNextBeforeExecutedAt(e,r),s=pl.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.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 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 k(S.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 i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}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()),i=r.isRemoved();return r.remove(t)&&!i&&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 et extends Hr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new et(t,ko.create());const i=ko.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new et(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}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 i=r.getValue();if(t(i,this))return;i instanceof Hr&&i.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({...w,value:w.value?{attributes:es(w.value.getAttributes()),content:w.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,y,h,[c,c]]}setStyle(t,r,i,s,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,l]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),c=[],d=this.rgaTreeSplit.findBetween(l,a),h=new Map,m=[];for(const w of d){const T=w.getCreatedAt().getActorID();let P,p=0n;if(o===void 0&&s===void 0?p=_s:o.size()>0?p=o.get(T)?o.get(T):0n:P=s.has(T)?s.get(T):bt,w.canStyle(i,P,p)){const g=h.get(T),v=w.getCreatedAt();(!g||v.after(g))&&h.set(T,v),m.push(w)}}const y=[];for(const w of m){if(w.isRemoved())continue;const[T,P]=this.rgaTreeSplit.findIndexesFromRange(w.createPosRange());c.push({type:"style",actor:i.getActorID(),from:T,to:P,value:{attributes:es(r)}});for(const[p,g]of Object.entries(r)){const[v]=w.getValue().setAttr(p,g,i);v!==void 0&&y.push({parent:w.getValue(),child:v})}}return[h,y,c]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===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 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 i=r.getValue();t.push({attributes:es(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new It(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 i of r.getValue().getGCPairs())t.push(i)}return t}}class Ro extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Ro(t,r,i,s,o,a,l)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,l]=o.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,i);for(const c of l)t.registerGCPair(c);return{opInfos:a.map(({from:c,to:d,value:h})=>({type:"edit",from:c,to:d,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.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 Lo extends Jt{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Lo(t,r,i,s,o,a)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,l]=o.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,i);for(const c of a)t.registerGCPair(c);return{opInfos:l.map(({from:c,to:d,value:h})=>({type:"style",from:c,to:d,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const J1=2,$1="root",mr="text";function Os(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(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 r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===mr}get paddedSize(){return this.size+(this.isText?0:J1)}isAncestorOf(e){return U1(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),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);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 k(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 k(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 k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.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 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,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.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 U1(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 oy(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),oy(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function ay(n,e,t=0){for(const r of n.children)ay(r,e,t+1);e(n,t)}function $l(n,e,t=0){for(const r of n._children)$l(r,e,t+1);e(n,t)}function Wc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Wc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Wc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function ly(n){return n.isText||n.children.length===0?n:ly(n.children[0])}function j1(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 i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}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 K1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>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 Rt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Rt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Rt.of(r.id,Ce.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Rt.of(Ce.of(kt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ce.of(kt.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(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&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 Ce{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ce(e,t)}static fromStruct(e){return Ce.of(kt.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 s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(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 r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Xe(Ce.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Xe(Ce.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,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=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,r,i){return(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r,i){return this.isText?!1:(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Tr);const i=[];for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}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 Hc(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(Hc)};return n.attrs&&(e.attributes=es((t=n.attrs)==null?void 0:t.toObject())),e}function Qf(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()}="${en(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Qf(t)).join("")}`}function cy(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(cy),size:n.size,isRemoved:n.isRemoved}}class Et extends Do{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new V1(t),this.nodeMapByID=new uy(Ce.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new Et(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[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const P=T.getCreatedAt().getActorID();let p,g=0n;if(o===void 0&&s===void 0?g=_s:o.size()>0?g=o.get(P)?o.get(P):0n:p=s.has(P)?s.get(P):bt,T.canStyle(i,p,g)&&r){const v=y.get(P),I=T.getCreatedAt();(!v||I.after(v))&&y.set(P,I);const E=T.setAttrs(r,i),N=E.reduce((q,[,$])=>($&&(q[$.getKey()]=m[$.getKey()]),q),{}),D=T.parent,R=T.prevSibling||T.parent;Object.keys(N).length>0&&h.push({type:"style",from:this.toIndex(D,R),to:this.toIndex(T,T),fromPath:this.toPath(D,R),toPath:this.toPath(T,T),actor:i.getActorID(),value:N});for(const[q]of E)q&&w.push({parent:T,child:q})}}),[y,w,h]}removeStyle(t,r,i,s,o){const[a,l]=this.findNodesAndSplitText(t[0],i),[c,d]=this.findNodesAndSplitText(t[1],i),h=[],m=new Map,y=[];return this.traverseInPosRange(a,l,c,d,([w])=>{const T=w.getCreatedAt().getActorID();let P,p=0n;if(o===void 0&&s===void 0?p=_s:o.size()>0?p=o.get(T)?o.get(T):0n:P=s.has(T)?s.get(T):bt,w.canStyle(i,P,p)&&r){const g=m.get(T),v=w.getCreatedAt();(!g||v.after(g))&&m.set(T,v),w.attrs||(w.attrs=new Tr);for(const N of r){const D=w.attrs.remove(N,i);for(const R of D)y.push({parent:w,child:R})}const I=w.parent,E=w.prevSibling||w.parent;h.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(I,E),to:this.toIndex(w,w),fromPath:this.toPath(I,E),toPath:this.toPath(w,w),value:r})}}),[m,y,h]}edit(t,r,i,s,o,a,l){const[c,d]=this.findNodesAndSplitText(t[0],s),[h,m]=this.findNodesAndSplitText(t[1],s),y=this.toIndex(c,d),w=this.toPath(c,d),T=[],P=[],p=[],g=new Map;this.traverseInPosRange(c,d,h,m,([E,N],D)=>{if(N===me.Start&&!D)for(const Se of E.children)p.push(Se);const R=E.getCreatedAt().getActorID();let q,$=0n;if(l===void 0&&a===void 0?$=_s:l.size()>0?$=l.get(R)?l.get(R):0n:q=a.has(R)?a.get(R):bt,E.canDelete(s,q,$)||T.includes(E.parent)){const Se=g.get(R),Er=E.getCreatedAt();(!Se||Er.after(Se))&&g.set(R,Er),(N===me.Text||N===me.Start)&&T.push(E),P.push([E,N])}});const v=this.makeDeletionChanges(P,s),I=[];for(const E of T)E.remove(s),E.isRemoved&&I.push({parent:this,child:E});for(const E of p)E.removedAt||c.append(E);if(i>0){let E=0,N=c,D=d;for(;E{c.isRemoved&&(R.remove(s),I.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),D.isRemoved||E.push(D);if(E.length){const D=E.map(R=>Hc(R));v.length&&v[v.length-1].from===y?v[v.length-1].value=D:v.push({type:"content",from:y,to:y,fromPath:w,toPath:w,actor:s.getActorID(),value:D})}}return[v,I,g]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);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 i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Rt.fromTreePos(i)}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 Qf(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=(i,s=void 0,o=void 0,a=0)=>{var y,w,T,P;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Rt.fromTreePos(h).toStruct());const m={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(y=i.removedAt)==null?void 0:y.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(T=i.insNextID)==null?void 0:T.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?es((P=i.attrs)==null?void 0:P.toObject()):void 0,index:l,path:c,pos:d};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(P,y)):i.push({type:"content",from:p,to:g,fromPath:this.toPath(T,h),toPath:this.toPath(P,y),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===me.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?me.Text:me.Start]:[t,me.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,me.End];const a=s[o+1];return[a,a.isText?me.Text:me.Start]}findLeftToken([t,r]){if(r===me.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?me.Text:me.End]}return[t,me.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,me.Start];const a=s[o-1];return[a,a.isText?me.Text:me.End]}}class Bo extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Bo(t,r,i,s,o,a,l)}execute(t,r,i){var d;const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=this.getExecutedAt(),a=s,[l,c]=a.edit([this.fromPos,this.toPos],(d=this.contents)==null?void 0:d.map(h=>h.deepcopy()),this.splitLevel,o,(()=>{let h=o.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>kt.of(o.getLamport(),++h,o.getActorID())})(),this.maxCreatedAtMapByActor,i);for(const h of c)t.registerGCPair(h);return{opInfos:l.map(({from:h,to:m,value:y,splitLevel:w,fromPath:T,toPath:P})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:m,value:y,splitLevel:w,fromPath:T,toPath:P}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=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`${t}.EDIT(${r},${i},${s.map(o=>Qf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ts{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new ts(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new ts(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new ts(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const H1=new ts(new Map);class ar{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new ar(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new ar(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n;let r=e.versionVector;r.size()===0&&(r=r.deepcopy(),r.set(e.actor,e.lamport));const i=this.versionVector.max(r),s=new ar(this.clientSeq,t,this.actor,i);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const r=e>this.lamport?e+1n:this.lamport+1n;t.unset(Jl);const i=this.versionVector.max(t);return i.set(this.actor,r),ar.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return kt.of(this.lamport,e,this.actor)}setActor(e){return new ar(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new ar(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const _1=new ar(0,0n,Jl,H1);class ms{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new ms({id:e,operations:t,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 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 i=[],s=[];for(const o of this.operations){const a=o.execute(e,r,this.id.getVersionVector());if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Xr.Put?t.set(this.id.getActorID(),Nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:de.bytesToHex(de.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>de.bytesToHex(de.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return ms.create({id:de.bytesToChangeID(de.hexToBytes(t)),operations:r==null?void 0:r.map(o=>de.bytesToOperation(de.hexToBytes(o))),presenceChange:i,message:s})}}class zl{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new zl(e,t,r,i,s,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}getVersionVector(){return this.versionVector}}class ns{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ns(e,t)}increaseClientSeq(e){return e===0?this:new ns(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return ns.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==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const G1=new ns(0n,0);class rn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new rn(e,t)}static fromStruct(e){return rn.of(kt.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 rn(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 Y1=rn.of(bt,0);class Ft{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Ft(e,t)}static fromStruct(e){const t=rn.fromStruct(e.id);return Ft.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return rn.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 _r extends ty{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new _r(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i: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 i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.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 i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r,i){if(!e.length)return[[],new Map,new Map];const[s,o]=this.filterNodes(e,t,r,i),a=new Map,l=new Map,c=this.makeChanges(o,t);for(const d of s){const h=d.getCreatedAt().getActorID();(!a.has(h)||d.getID().getCreatedAt().after(a.get(h)))&&a.set(h,d.getID().getCreatedAt()),l.set(d.getID().toIDString(),d),d.remove(t)}return this.deleteIndexNodes(o),[c,a,l]}filterNodes(e,t,r,i){const s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID();let h,m=0n;i===void 0&&r===void 0?m=_s:i.size()>0?m=i.get(d)?i.get(d):0n:h=r.has(d)?r.get(d):bt,c.canDelete(t,h,m)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var sn=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(sn||{});class tt extends Do{constructor(t,r,i){super(i);u(this,"valueType");u(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=K.fromNumber(r).toInt():this.value=ig(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=K.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new tt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return K.fromBytesLE(Array.from(r));default:throw new k(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=tt.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 K?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!!tt.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 k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.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=K.fromNumber(this.value+ig(t.getValue())).toInt(),this}}class ys extends Jt{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ys(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof tt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ys.create(this.getParentCreatedAt(),se.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class pr extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new pr(t,r,i,s,o,[],a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new pr(t,r,i,s,new Map,o,a)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=s;let a,l;if(this.attributes.size){const c={};[...this.attributes].forEach(([d,h])=>c[d]=h),[,l,a]=o.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}else{const c=this.attributesToRemove;[,l,a]=o.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}for(const c of l)t.registerGCPair(c);return{opInfos:a.map(({from:c,to:d,value:h,fromPath:m,toPath:y})=>({type:"tree-style",from:c,to:d,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:m,toPath:y,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()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.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 Q1(n){const e=new _f,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function X1(n){if(n.type===Xr.Put)return new vo({type:Ii.PUT,presence:Q1(n.presence)});if(n.type===Xr.Clear)return new vo({type:Ii.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function Z1(n){return new Xp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function fy(n){return new Fl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ld(n.getActorID()),versionVector:Xf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ld(n.getActorID())})}function Xf(n){if(!n)return;const e=new Ml;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function dy(n){switch(n){case ve.Null:return z.NULL;case ve.Boolean:return z.BOOLEAN;case ve.Integer:return z.INTEGER;case ve.Long:return z.LONG;case ve.Double:return z.DOUBLE;case ve.String:return z.STRING;case ve.Bytes:return z.BYTES;case ve.Date:return z.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function hy(n){switch(n){case sn.IntegerCnt:return z.INTEGER_CNT;case sn.LongCnt:return z.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function Iu(n){if(n instanceof He)return new at({type:z.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:xy(n)});if(n instanceof et)return new at({type:z.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:DS(n)});if(n instanceof It)return new at({type:z.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof se)return new at({type:dy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof tt)return new at({type:hy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Et)return new at({type:z.TREE,createdAt:F(n.getCreatedAt()),value:RS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function eS(n){return new po({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function ta(n){return new kr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function na(n){return new Ai({parentId:Gs(n.getParentID()),leftSiblingId:Gs(n.getLeftSiblingID())})}function Gs(n){return new Wr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function gy(n){const e=new Hf;if(n instanceof Ei){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Iu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Oo){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=Iu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Fr){const t=n,r=new Za;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 Zr){const t=n,r=new el;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 Ro){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Lo){const t=n,r=new nl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ys){const t=n,r=new rl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=Iu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Bo){const t=n,r=new il,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=na(t.getFromPos()),r.to=na(t.getToPos()),r.contents=aS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof pr){const t=n,r=new sl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=na(t.getFromPos()),r.to=na(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function tS(n){const e=[];for(const t of n)e.push(gy(t));return e}function nS(n){const e=new Yp({id:fy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=tS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=X1(n.getPresenceChange())),e}function rS(n){const e=[];for(const t of n)e.push(nS(t));return e}function iS(n){const e=[];for(const t of n)e.push(new Qp({key:t.getStrKey(),element:ed(t.getValue())}));return e}function sS(n){const e=[];for(const t of n)e.push(new dl({element:ed(t.getValue())}));return e}function oS(n){const e=[];for(const t of n){const r=new hl;r.id=eS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new ds;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function aS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new gl({content:Zf(t)}));return e}function lS(n){const e={};for(const t of n)e[t.getKey()]=new ds({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Zf(n){if(!n)return[];const e=[];return $l(n,(t,r)=>{const i=new yo({id:Gs(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Gs(t.insPrevID)),t.insNextID&&(i.insNextId=Gs(t.insNextID)),t.attrs&&(i.attributes=lS(t.attrs)),e.push(i)}),e}function uS(n){const e=new _e;return e.body.case="jsonObject",e.body.value=new ol({nodes:iS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function my(n){const e=new _e;return e.body.case="jsonArray",e.body.value=new al({nodes:sS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function cS(n){const e=new _e;return e.body.case="primitive",e.body.value=new ll({type:dy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function fS(n){const e=new _e;return e.body.case="text",e.body.value=new ul({nodes:oS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new _e;return e.body.case="counter",e.body.value=new cl({type:hy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function py(n){const e=new _e;return e.body.case="tree",e.body.value=new fl({nodes:Zf(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function ed(n){if(n instanceof He)return uS(n);if(n instanceof et)return my(n);if(n instanceof se)return cS(n);if(n instanceof It)return fS(n);if(n instanceof tt)return dS(n);if(n instanceof Et)return py(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function hS(n){return new Ir({documentKey:n.getDocumentKey(),checkpoint:Z1(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:rS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Xf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function Fs(n){if(!(n instanceof ne))return{};const e=n.findDetails(R1);for(const t of e)return t.metadata;return{}}function Oi(n){return Fs(n).code??""}function yy(n){return ar.of(n.clientSeq,BigInt(n.lamport),od(n.actorId),td(n.versionVector),BigInt(n.serverSeq))}function td(n){if(!n)return;const e=new ts;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return kt.of(BigInt(n.lamport),n.delimiter,od(n.actorId))}function nd(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function gS(n){const e=n.type;if(e===Ii.PUT){const t=nd(n.presence);return{type:Xr.Put,presence:t}}if(e===Ii.CLEAR)return{type:Xr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function mS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,nd(r))}),e}function vy(n){switch(n){case z.NULL:return ve.Null;case z.BOOLEAN:return ve.Boolean;case z.INTEGER:return ve.Integer;case z.LONG:return ve.Long;case z.DOUBLE:return ve.Double;case z.STRING:return ve.String;case z.BYTES:return ve.Bytes;case z.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function yl(n){switch(n){case z.INTEGER_CNT:return sn.IntegerCnt;case z.LONG_CNT:return sn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Eu(n){switch(n.type){case z.JSON_OBJECT:return n.value?Ey(n.value):He.create(M(n.createdAt));case z.JSON_ARRAY:return n.value?PS(n.value):et.create(M(n.createdAt));case z.TEXT:return It.create(ps.create(),M(n.createdAt));case z.TREE:return OS(n.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 se.of(se.valueFromBytes(vy(n.type),n.value),M(n.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return tt.create(yl(n.type),tt.valueFromBytes(yl(n.type),n.value),M(n.createdAt))}}function ra(n){return Ft.of(rn.of(M(n.createdAt),n.offset),n.relativeOffset)}function wy(n){return rn.of(M(n.createdAt),n.offset)}function pS(n){const e=To.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=_r.create(wy(n.id),e);return t.remove(M(n.removedAt)),t}function Ri(n){return Rt.of(Ys(n.parentId),Ys(n.leftSiblingId))}function Ys(n){return Ce.of(M(n.createdAt),n.offset)}function yS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=rd(t.content);e.push(r)}),e}function rd(n){if(n.length===0)return;const e=[];for(const i of n)e.push(wS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),Et.create(t,bt).getRoot()}function vS(n){const e=Tr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function wS(n){const e=Ys(n.id),t=Xe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=vS(n.attributes)),n.insPrevId&&(t.insPrevID=Ys(n.insPrevId)),n.insNextId&&(t.insNextID=Ys(n.insNextId)),t.removedAt=M(n.removedAt),t}function Sy(n){if(n.body.case==="set"){const e=n.body.value;return Ei.create(e.key,Eu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Oo.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Eu(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Fr.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 Zr.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(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Ro.create(M(e.parentCreatedAt),ra(e.from),ra(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(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Lo.create(M(e.parentCreatedAt),ra(e.from),ra(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 ys.create(M(e.parentCreatedAt),Eu(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,i])=>{t.set(r,M(i))}),Bo.create(M(e.parentCreatedAt),Ri(e.from),Ri(e.to),yS(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,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?pr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Ri(e.from),Ri(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),pr.create(M(e.parentCreatedAt),Ri(e.from),Ri(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function SS(n){const e=[];for(const t of n){const r=Sy(t);r&&e.push(r)}return e}function ky(n){const e=[];for(const t of n)e.push(ms.create({id:yy(t.id),operations:SS(t.operations),presenceChange:t.presenceChange?gS(t.presenceChange):void 0,message:t.message}));return e}function kS(n){return ns.of(BigInt(n.serverSeq),n.clientSeq)}function TS(n){return zl.create(n.documentKey,kS(n.checkpoint),n.isRemoved,ky(n.changes),td(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function Ty(n){const e=new wo;for(const r of n.nodes){const i=id(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new He(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Ay(n){const e=new ko;for(const r of n.nodes)e.insert(id(r.element));const t=new et(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function AS(n){const e=se.of(se.valueFromBytes(vy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function IS(n){const e=new ps;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,pS(i));i.insPrevId&&s.setInsPrev(e.findNode(wy(i.insPrevId))),t=s}const r=new It(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function ES(n){const e=tt.create(yl(n.type),tt.valueFromBytes(yl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Iy(n){const e=rd(n.nodes);return Et.create(e,M(n.createdAt))}function id(n){if(n.body.case==="jsonObject")return Ty(n.body.value);if(n.body.case==="jsonArray")return Ay(n.body.value);if(n.body.case==="primitive")return AS(n.body.value);if(n.body.case==="text")return IS(n.body.value);if(n.body.case==="counter")return ES(n.body.value);if(n.body.case==="tree")return Iy(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function xS(n){if(!n)return{root:He.create(bt),presences:new Map};const e=Tc.fromBinary(n);return{root:id(e.root),presences:mS(e.presences)}}function CS(n){const e=Xf(n);return sd(e.toBinary())}function NS(n){const e=ad(n),t=Ml.fromBinary(e);return td(t)}function Ey(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ty(e.body.value)}function xy(n){return ed(n).toBinary()}function PS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ay(e.body.value)}function DS(n){return my(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Iy(e.body.value)}function RS(n){return py(n).toBinary()}function sd(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function od(n){return sd(n)}function ad(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ld(n){return ad(n)}function LS(n){const e=Fl.fromBinary(n);return yy(e)}function BS(n){const e=Hf.fromBinary(n);return Sy(e)}const de={fromPresence:nd,toChangePack:hS,fromChangePack:TS,fromChanges:ky,toTreeNodes:Zf,fromTreeNodes:rd,objectToBytes:xy,bytesToObject:Ey,bytesToSnapshot:xS,bytesToHex:sd,hexToBytes:ad,toHexString:od,toUint8Array:ld,toOperation:gy,toChangeID:fy,PbChangeID:Fl,bytesToChangeID:LS,bytesToOperation:BS,versionVectorToHex:CS,hexToVersionVector:NS};var Me=(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))(Me||{});let ai=3;function Cy(n){ai=n}const J={trivial:(...n)=>{ai>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{ai>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{ai>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{ai>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{ai>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=>ai<=n};function Ny(){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 bS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ia.RealtimeSyncOff?!1:this.syncMode===Ia.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ia.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 xu=()=>{};class FS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(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 i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=xu),i.error===void 0&&(i.error=xu),i.complete===void 0&&(i.complete=xu);const s=Ny(),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){J.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 Hi{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=ey,this.root=t,this.operations=[],this.previousPresence=Nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Hi(e,t,r,i)}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 ms.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 Ao{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(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 It||t instanceof Et)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Ao(He.create(bt))}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 i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),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 Hr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Hr&&e.getDescendants(i=>(r(i),!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 Hr&&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 Ao(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Py(n,e){const t=new Io(n);return new Proxy(e,t.getHandlers())}class Io{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),Io.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():li(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]`),Io.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=vl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ei.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=vl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function JS(n,e){const t=new le(n,e);return new Proxy(e,t.getHandlers())}function $S(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class le{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Nr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Nr(e,a)}:i==="getLast"?()=>Nr(e,r.getLast()):i==="deleteByID"?o=>{const a=le.deleteInternalByID(e,r,o);return Nr(e,a)}:i==="insertAfter"?(o,a)=>{const l=le.insertAfterInternal(e,r,o,a);return Nr(e,l)}:i==="insertBefore"?(o,a)=>{const l=le.insertBeforeInternal(e,r,o,a);return Nr(e,l)}:i==="moveBefore"?(o,a)=>{le.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{le.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{le.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{le.moveLastInternal(e,r,o)}:$S(i)?li(e,r.get(Number(i))):i==="push"?o=>le.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>le.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?le.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>le.includes(e,r,o,a):i==="indexOf"?(o,a)=>le.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>le.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>le.toTestString(r):typeof i=="string"&&zS(i)?(...o)=>{const a=Array.from(r).map(l=>li(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(Me.Trivial)&&J.trivial(`array[${i}]`),le.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Nr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=vl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return le.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(Fr.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(Fr.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(Fr.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(Fr.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=vl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Oo.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return le.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.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),c=[];for(let d=a;d=s)return!1;if(se.isSupport(r))return Array.from(t).map(c=>li(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(se.isSupport(r))return Array.from(t).map(c=>li(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(se.isSupport(r))return Array.from(t).map(c=>li(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Ul{constructor(e,t){u(this,"context");u(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,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(Me.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?hs(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Ro(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}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 k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(Me.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=hs(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Lo(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(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 k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Ft.fromStruct(e[0]),Ft.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(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 k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class jl{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(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 k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=se.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ys.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ud(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===mr){Dy(n);const{value:s}=n,o=Xe.create(Ce.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Zp(o)){const c=hs(o);a=new Tr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Xe.create(Ce.of(i,0),r,void 0,a);e.append(l);for(const c of s)ud(c,l,t)}}function US(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===mr){const{value:s}=e;i=Xe.create(Ce.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Zp(o)){const l=hs(o);a=new Tr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Xe.create(Ce.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)ud(l,i,n)}return i}function Dy(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function sg(n){if(!n.length)return!0;if(n[0].type===mr)for(const t of n){const{type:r}=t;if(r!==mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Dy(t)}else for(const t of n){const{type:r}=t;if(r===mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Vl{constructor(e){u(this,"initialRoot");u(this,"context");u(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 Xe.create(Ce.of(e.issueTimeTicket(),0),$1);const t=Xe.create(Ce.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ud(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?hs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(pr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?hs(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(pr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(pr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(sg(r),r[0].type!==mr))for(const d of r){const{children:h=[]}=d;sg(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===mr){let d="";for(const h of r){const{value:m}=h;d+=m}o.push(Xe.create(Ce.of(this.context.issueTimeTicket(),0),mr,d))}else o=r.map(d=>d&&US(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Bo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(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,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(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,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.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 k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function og(n,e){return Py(n,e)}function Nr(n,e){if(e){if(e instanceof se)return e;if(e instanceof He)return Py(n,e);if(e instanceof et)return JS(n,e);if(e instanceof It)return new Ul(n,e);if(e instanceof tt){const t=new jl(sn.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Et){const t=new Vl;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function li(n,e){const t=Nr(n,e);return t instanceof se?t.getValue():t}function vl(n,e,t){let r;if(se.isSupport(e))r=se.of(e,t);else if(Array.isArray(e))r=et.create(t,le.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Ul?(r=It.create(ps.create(),t),e.initialize(n,r)):e instanceof jl?(r=tt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof Vl?(r=Et.create(e.buildRoot(n),t),e.initialize(n,r)):r=He.create(t,Io.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const ag=50;class jS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=ag&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=ag&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const VS="yorkie-devtools-panel",qS="yorkie-devtools-sdk";let Li="disconnected";const lg=new Map,Aa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Aa);function ia(n,e){(e!=null&&e.force||Li!=="disconnected")&&window.postMessage({source:qS,...n},"*")}function KS(n){if(!n.isEnableDevtools()||typeof window>"u"||lg.has(n.getKey()))return;Aa.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Ee.StatusChanged&&r.type!==Ee.Snapshot&&r.type!==Ee.LocalChange&&r.type!==Ee.RemoteChange&&r.type!==Ee.Initialized&&r.type!==Ee.Watched&&r.type!==Ee.Unwatched&&r.type!==Ee.PresenceChanged)||(Aa.get(n.getKey()).push(t),Li==="synced"&&ia({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});lg.set(n.getKey(),[e]),ia({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==VS)return;switch(t.data.msg){case"devtools::connect":if(Li!=="disconnected")break;Li="connected",ia({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Li="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Li="synced",ia({msg:"doc::sync::full",docKey:n.getKey(),events:Aa.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Pr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Pr||{}),Ee=(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.AuthError="auth-error",n))(Ee||{}),_c=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(_c||{}),Gc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Gc||{});class Oy{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Ao.create(),this.changeID=_1,this.checkpoint=G1,this.localChanges=[],this.eventStream=MS(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new jS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},KS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=og(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Au(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(Me.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.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 c=[];o.length>0&&c.push({type:"local-change",source:Y.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()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(Me.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="auth-error"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="auth-error"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}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 c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.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((s,o)=>s===r[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),Y.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(Me.Trivial)&&J.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 zl.create(this.key,t,!1,e,this.getVersionVector())}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=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return og(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r,i=-1){const{root:s,presences:o}=de.bytesToSnapshot(r);this.root=new Ao(s),this.presences=o,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,Y.Local),this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?de.bytesToHex(r):void 0,snapshotVector:de.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(Me.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(Me.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);J.isEnabled(Me.Debug)&&J.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=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Xr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Xr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,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 t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===yi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===yi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===yi.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(Jl),this.publish([{source:e==="removed"?Y.Remote:Y.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,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),de.hexToVersionVector(i),de.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ms.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);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 k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)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?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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Au(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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:Y.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:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Au(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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:Y.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:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function WS(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const HS="yorkie-js-sdk",_S="0.5.6",GS="Yorkie JS SDK",YS="./src/yorkie.ts",QS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},XS=["dist"],ZS={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"},ek={node:">=18.0.0",npm:">=7.1.0"},tk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},nk={name:"hackerwins",email:"susukang98@gmail.com"},rk="Apache-2.0",ik={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},sk="https://github.com/yorkie-team/yorkie-js-sdk#readme",ok={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ak={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},ug={name:HS,version:_S,description:GS,main:YS,publishConfig:QS,files:XS,scripts:ZS,engines:ek,repository:tk,author:nk,license:rk,bugs:ik,homepage:sk,devDependencies:ok,dependencies:ak};function lk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",ug.name+"/"+ug.version),await n(e))}const uk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ia=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ia||{});const sa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Cu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ry{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"authTokenInjector");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"setAuthToken");u(this,"taskQueue");u(this,"processing",!1);u(this,"keepalive",!1);t=t||sa,this.key=t.key?t.key:Ny(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??sa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??sa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??sa.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=WS(this.apiKey);this.setAuthToken=i,this.rpcClient=l1(O1,D1({baseUrl:e,interceptors:[r,lk()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw J.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Pr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:de.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=de.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Pr.Removed)return e;e.applyStatus(Pr.Attached),this.attachmentMap.set(e.getKey(),new bS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const m=d;c[m]=h}})}return e}).catch(async s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.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:de.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=de.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Pr.Removed&&e.applyStatus(Pr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=de.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(i=>{const s=de.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),await 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,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!uk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Cu.maxRetries,a=Cu.maxBackoff;let l=0;const c=h=>Math.min(Cu.initialRetryInterval*2**h,a),d=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":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),await this.handleConnectError(h))if(h instanceof ne&&Oi(h)===S.ErrUnauthenticated&&s.doc.publish([{type:Ee.AuthError,value:{reason:Fs(h).reason,method:"Broadcast"}}]),ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.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).catch(async i=>{throw i instanceof ne&&Oi(i)===S.ErrUnauthenticated&&r.doc.publish([{type:Ee.AuthError,value:{reason:Fs(i).reason,method:"PushPull"}}]),i})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.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 k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:Ee.ConnectionChanged,value:_c.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:Ee.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Ee.ConnectionChanged,value:_c.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(c)?(c instanceof ne&&Oi(c)===S.ErrUnauthenticated&&t.doc.publish([{type:Ee.AuthError,value:{reason:Fs(c).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===yi.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(Pr.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:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:de.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=de.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Ee.SyncStatusChanged,value:Gc.Synced}]),r.getStatus()===Pr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Ee.SyncStatusChanged,value:Gc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof ne))return!1;if(e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable)return!0;if(Oi(e)===S.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Fs(e).reason);this.setAuthToken(t)}return!0}return(Oi(e)===S.ErrClientNotActivated||Oi(e)===S.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(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const cg={Client:Ry,Document:Oy,Primitive:se,Text:Ul,Counter:jl,Tree:Vl,LogLevel:Me,setLogLevel:Cy,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ry,Document:Oy,Primitive:se,Text:Ul,Counter:jl,Tree:Vl,LogLevel:Me,setLogLevel:Cy,IntType:sn.IntegerCnt,LongType:sn.LongCnt});var Ly={exports:{}};/*! +`));for(const r of e)this.applyChange(r,t);J.isEnabled(Me.Debug)&&J.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=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Xr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Xr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,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 t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===yi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===yi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===yi.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(Jl),this.publish([{source:e==="removed"?Y.Remote:Y.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,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),de.hexToVersionVector(i),de.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ms.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);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 k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)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?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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Au(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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:Y.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:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Au(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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:Y.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:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function WS(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const HS="yorkie-js-sdk",_S="0.5.7",GS="Yorkie JS SDK",YS="./src/yorkie.ts",QS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},XS=["dist"],ZS={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"},ek={node:">=18.0.0",npm:">=7.1.0"},tk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},nk={name:"hackerwins",email:"susukang98@gmail.com"},rk="Apache-2.0",ik={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},sk="https://github.com/yorkie-team/yorkie-js-sdk#readme",ok={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ak={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},ug={name:HS,version:_S,description:GS,main:YS,publishConfig:QS,files:XS,scripts:ZS,engines:ek,repository:tk,author:nk,license:rk,bugs:ik,homepage:sk,devDependencies:ok,dependencies:ak};function lk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",ug.name+"/"+ug.version),await n(e))}const uk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ia=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ia||{});const sa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Cu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ry{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"authTokenInjector");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"setAuthToken");u(this,"taskQueue");u(this,"processing",!1);u(this,"keepalive",!1);t=t||sa,this.key=t.key?t.key:Ny(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??sa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??sa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??sa.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=WS(this.apiKey);this.setAuthToken=i,this.rpcClient=l1(O1,D1({baseUrl:e,interceptors:[r,lk()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw J.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Pr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:de.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=de.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Pr.Removed)return e;e.applyStatus(Pr.Attached),this.attachmentMap.set(e.getKey(),new bS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const m=d;c[m]=h}})}return e}).catch(async s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.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:de.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=de.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Pr.Removed&&e.applyStatus(Pr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=de.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(i=>{const s=de.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),await 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,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!uk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Cu.maxRetries,a=Cu.maxBackoff;let l=0;const c=h=>Math.min(Cu.initialRetryInterval*2**h,a),d=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":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),await this.handleConnectError(h))if(h instanceof ne&&Oi(h)===S.ErrUnauthenticated&&s.doc.publish([{type:Ee.AuthError,value:{reason:Fs(h).reason,method:"Broadcast"}}]),ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.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).catch(async i=>{throw i instanceof ne&&Oi(i)===S.ErrUnauthenticated&&r.doc.publish([{type:Ee.AuthError,value:{reason:Fs(i).reason,method:"PushPull"}}]),i})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.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 k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:Ee.ConnectionChanged,value:_c.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:Ee.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Ee.ConnectionChanged,value:_c.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(c)?(c instanceof ne&&Oi(c)===S.ErrUnauthenticated&&t.doc.publish([{type:Ee.AuthError,value:{reason:Fs(c).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===yi.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(Pr.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:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:de.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=de.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Ee.SyncStatusChanged,value:Gc.Synced}]),r.getStatus()===Pr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Ee.SyncStatusChanged,value:Gc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof ne))return!1;if(e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable)return!0;if(Oi(e)===S.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Fs(e).reason);this.setAuthToken(t)}return!0}return(Oi(e)===S.ErrClientNotActivated||Oi(e)===S.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(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const cg={Client:Ry,Document:Oy,Primitive:se,Text:Ul,Counter:jl,Tree:Vl,LogLevel:Me,setLogLevel:Cy,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ry,Document:Oy,Primitive:se,Text:Ul,Counter:jl,Tree:Vl,LogLevel:Me,setLogLevel:Cy,IntType:sn.IntegerCnt,LongType:sn.LongCnt});var Ly={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames diff --git a/examples/react-todomvc/index.html b/examples/react-todomvc/index.html index 97c89b32f..58a11d9de 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-CUyGqr_M.js b/examples/simultaneous-cursors/assets/index-DzqXtCgP.js similarity index 99% rename from examples/simultaneous-cursors/assets/index-CUyGqr_M.js rename to examples/simultaneous-cursors/assets/index-DzqXtCgP.js index d5c50cf2d..8db8f4658 100644 --- a/examples/simultaneous-cursors/assets/index-CUyGqr_M.js +++ b/examples/simultaneous-cursors/assets/index-DzqXtCgP.js @@ -59,4 +59,4 @@ Error generating stack: `+s.message+` * * SPDX-License-Identifier: Apache-2.0 */var wt=null;try{wt=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 K(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}K.prototype.__isLong__;Object.defineProperty(K.prototype,"__isLong__",{value:!0});function Be(n){return(n&&n.__isLong__)===!0}function eg(n){var e=Math.clz32(n&-n);return n?31-e:e}K.isLong=Be;var tg={},ng={};function Pi(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=ng[n],r)?r:(t=_(n,0,!0),i&&(ng[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=tg[n],r)?r:(t=_(n,n<0?-1:0,!1),i&&(tg[n]=t),t))}K.fromInt=Pi;function St(n,e){if(isNaN(n))return e?gr:Rt;if(e){if(n<0)return gr;if(n>=iy)return ay}else{if(n<=-ig)return qe;if(n+1>=ig)return oy}return n<0?St(-n,e).neg():_(n%ms|0,n/ms|0,e)}K.fromNumber=St;function _(n,e,t){return new K(n,e,t)}K.fromBits=_;var pl=Math.pow;function Zf(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?gr:Rt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Zf(n.substring(1),e,t).neg();for(var i=St(pl(t,8)),s=Rt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*ms+(this.low>>>0):this.high*ms+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=u,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+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(qe)?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 Be(e)||(e=zt(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(Be(e)||(e=zt(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};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(qe)?qe:this.not().add(_i)};C.neg=C.negate;C.add=function(e){Be(e)||(e=zt(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,u=e.low>>>16,c=e.low&65535,d=0,h=0,m=0,y=0;return y+=s+c,m+=y>>>16,y&=65535,m+=i+u,h+=m>>>16,m&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,_(m<<16|y,d<<16|h,this.unsigned)};C.subtract=function(e){return Be(e)||(e=zt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Be(e)||(e=zt(e)),wt){var t=wt.mul(this.low,this.high,e.low,e.high);return _(t,wt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?gr:Rt;if(this.eq(qe))return e.isOdd()?qe:Rt;if(e.eq(qe))return this.isOdd()?qe:Rt;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(sg)&&e.lt(sg))return St(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,u=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,m=0,y=0,w=0;return w+=o*d,y+=w>>>16,w&=65535,y+=s*d,m+=y>>>16,y&=65535,y+=o*c,m+=y>>>16,y&=65535,m+=i*d,h+=m>>>16,m&=65535,m+=s*c,h+=m>>>16,m&=65535,m+=o*u,h+=m>>>16,m&=65535,h+=r*d+i*c+s*u+o*a,h&=65535,_(y<<16|w,h<<16|m,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Be(e)||(e=zt(e)),e.isZero())throw Error("division by zero");if(wt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?wt.div_u:wt.div_s)(this.low,this.high,e.low,e.high);return _(t,wt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?gr:Rt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return gr;if(e.gt(this.shru(1)))return sy;s=gr}else{if(this.eq(qe)){if(e.eq(_i)||e.eq(Hc))return qe;if(e.eq(qe))return _i;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Rt)?e.isNegative()?_i:Hc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(qe))return this.unsigned?gr:Rt;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=Rt}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),u=a<=48?1:pl(2,a-48),c=St(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=u,c=St(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=_i),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Be(e)||(e=zt(e)),wt){var t=(this.unsigned?wt.rem_u:wt.rem_s)(this.low,this.high,e.low,e.high);return _(t,wt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return _(~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?eg(this.low):eg(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Be(e)||(e=zt(e)),_(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Be(e)||(e=zt(e)),_(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Be(e)||(e=zt(e)),_(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?_(this.low<>>32-e,this.unsigned):_(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):_(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?_(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?_(this.high,0,this.unsigned):_(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?_(this.high,this.low,this.unsigned):e<32?(t=32-e,_(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,_(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Be(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?_(this.high,this.low,this.unsigned):e<32?(t=32-e,_(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,_(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?_(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:_(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]};K.fromBytes=function(e,t,r){return r?K.fromBytesLE(e,t):K.fromBytesBE(e,t)};K.fromBytesLE=function(e,t){return new K(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};K.fromBytesBE=function(e,t){return new K(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};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 ie extends Oo{constructor(t,r){super(r);l(this,"valueType");l(this,"value");this.valueType=ie.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ie(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 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 K.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(K.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${tn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ie.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 K)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ie.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=K.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class yl extends ry{constructor(t){super(t);l(this,"prev");l(this,"next");this.value=t}static createAfter(t,r){const i=new yl(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}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 To{constructor(){l(this,"dummyHead");l(this,"last");l(this,"nodeMapByIndex");l(this,"nodeMapByCreatedAt");const e=ie.of(0,Ft);e.setRemovedAt(Ft),this.dummyHead=new yl(e),this.last=this.dummyHead,this.nodeMapByIndex=new ko,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new To}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.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 i=this.findNextBeforeExecutedAt(e,r),s=yl.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.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 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 k(S.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 i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}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()),i=r.isRemoved();return r.remove(t)&&!i&&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 tt extends _r{constructor(t,r){super(t);l(this,"elements");this.elements=r}static create(t,r){if(!r)return new tt(t,To.create());const i=To.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}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 i=r.getValue();if(t(i,this))return;i instanceof _r&&i.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({...w,value:w.value?{attributes:ts(w.value.getAttributes()),content:w.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,y,h,[c,c]]}setStyle(t,r,i,s,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,u]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),c=[],d=this.rgaTreeSplit.findBetween(u,a),h=new Map,m=[];for(const w of d){const T=w.getCreatedAt().getActorID();let P,p=0n;if(o===void 0&&s===void 0?p=Gs:o.size()>0?p=o.get(T)?o.get(T):0n:P=s.has(T)?s.get(T):Ft,w.canStyle(i,P,p)){const g=h.get(T),v=w.getCreatedAt();(!g||v.after(g))&&h.set(T,v),m.push(w)}}const y=[];for(const w of m){if(w.isRemoved())continue;const[T,P]=this.rgaTreeSplit.findIndexesFromRange(w.createPosRange());c.push({type:"style",actor:i.getActorID(),from:T,to:P,value:{attributes:ts(r)}});for(const[p,g]of Object.entries(r)){const[v]=w.getValue().setAttr(p,g,i);v!==void 0&&y.push({parent:w.getValue(),child:v})}}return[h,y,c]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===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 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 i=r.getValue();t.push({attributes:ts(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Et(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 i of r.getValue().getGCPairs())t.push(i)}return t}}class Lo extends $t{constructor(t,r,i,s,o,a,u){super(t,u);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"content");l(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,u){return new Lo(t,r,i,s,o,a,u)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,u]=o.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,i);for(const c of u)t.registerGCPair(c);return{opInfos:a.map(({from:c,to:d,value:h})=>({type:"edit",from:c,to:d,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.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 Bo extends $t{constructor(t,r,i,s,o,a){super(t,a);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Bo(t,r,i,s,o,a)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,u]=o.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,i);for(const c of a)t.registerGCPair(c);return{opInfos:u.map(({from:c,to:d,value:h})=>({type:"style",from:c,to:d,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const J1=2,$1="root",pr="text";function Rs(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(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 r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===pr}get paddedSize(){return this.size+(this.isText?0:J1)}isAncestorOf(e){return U1(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),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);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 k(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 k(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 k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.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 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,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.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 U1(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 ly(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||u)&&r([s,s.isText?"Text":"Start"],c),ly(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function uy(n,e,t=0){for(const r of n.children)uy(r,e,t+1);e(n,t)}function zl(n,e,t=0){for(const r of n._children)zl(r,e,t+1);e(n,t)}function Gc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Gc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Gc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function cy(n){return n.isText||n.children.length===0?n:cy(n.children[0])}function j1(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 i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}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 K1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>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 Lt{constructor(e,t){l(this,"parentID");l(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Lt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Lt.of(r.id,Ce.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Lt.of(Ce.of(Tt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ce.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){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&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 Ce{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ce(e,t)}static fromStruct(e){return Ce.of(Tt.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 s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(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 r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Ze(Ce.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ze(Ce.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,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=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,r,i){return(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r,i){return this.isText?!1:(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Ar);const i=[];for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}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 Yc(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(Yc)};return n.attrs&&(e.attributes=ts((t=n.attrs)==null?void 0:t.toObject())),e}function ed(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()}="${tn(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>ed(t)).join("")}`}function dy(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(dy),size:n.size,isRemoved:n.isRemoved}}class xt extends Oo{constructor(t,r){super(r);l(this,"indexTree");l(this,"nodeMapByID");this.indexTree=new V1(t),this.nodeMapByID=new fy(Ce.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new xt(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[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,u=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=u.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const P=T.getCreatedAt().getActorID();let p,g=0n;if(o===void 0&&s===void 0?g=Gs:o.size()>0?g=o.get(P)?o.get(P):0n:p=s.has(P)?s.get(P):Ft,T.canStyle(i,p,g)&&r){const v=y.get(P),I=T.getCreatedAt();(!v||I.after(v))&&y.set(P,I);const E=T.setAttrs(r,i),N=E.reduce((q,[,$])=>($&&(q[$.getKey()]=m[$.getKey()]),q),{}),D=T.parent,R=T.prevSibling||T.parent;Object.keys(N).length>0&&h.push({type:"style",from:this.toIndex(D,R),to:this.toIndex(T,T),fromPath:this.toPath(D,R),toPath:this.toPath(T,T),actor:i.getActorID(),value:N});for(const[q]of E)q&&w.push({parent:T,child:q})}}),[y,w,h]}removeStyle(t,r,i,s,o){const[a,u]=this.findNodesAndSplitText(t[0],i),[c,d]=this.findNodesAndSplitText(t[1],i),h=[],m=new Map,y=[];return this.traverseInPosRange(a,u,c,d,([w])=>{const T=w.getCreatedAt().getActorID();let P,p=0n;if(o===void 0&&s===void 0?p=Gs:o.size()>0?p=o.get(T)?o.get(T):0n:P=s.has(T)?s.get(T):Ft,w.canStyle(i,P,p)&&r){const g=m.get(T),v=w.getCreatedAt();(!g||v.after(g))&&m.set(T,v),w.attrs||(w.attrs=new Ar);for(const N of r){const D=w.attrs.remove(N,i);for(const R of D)y.push({parent:w,child:R})}const I=w.parent,E=w.prevSibling||w.parent;h.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(I,E),to:this.toIndex(w,w),fromPath:this.toPath(I,E),toPath:this.toPath(w,w),value:r})}}),[m,y,h]}edit(t,r,i,s,o,a,u){const[c,d]=this.findNodesAndSplitText(t[0],s),[h,m]=this.findNodesAndSplitText(t[1],s),y=this.toIndex(c,d),w=this.toPath(c,d),T=[],P=[],p=[],g=new Map;this.traverseInPosRange(c,d,h,m,([E,N],D)=>{if(N===me.Start&&!D)for(const Se of E.children)p.push(Se);const R=E.getCreatedAt().getActorID();let q,$=0n;if(u===void 0&&a===void 0?$=Gs:u.size()>0?$=u.get(R)?u.get(R):0n:q=a.has(R)?a.get(R):Ft,E.canDelete(s,q,$)||T.includes(E.parent)){const Se=g.get(R),xr=E.getCreatedAt();(!Se||xr.after(Se))&&g.set(R,xr),(N===me.Text||N===me.Start)&&T.push(E),P.push([E,N])}});const v=this.makeDeletionChanges(P,s),I=[];for(const E of T)E.remove(s),E.isRemoved&&I.push({parent:this,child:E});for(const E of p)E.removedAt||c.append(E);if(i>0){let E=0,N=c,D=d;for(;E{c.isRemoved&&(R.remove(s),I.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),D.isRemoved||E.push(D);if(E.length){const D=E.map(R=>Yc(R));v.length&&v[v.length-1].from===y?v[v.length-1].value=D:v.push({type:"content",from:y,to:y,fromPath:w,toPath:w,actor:s.getActorID(),value:D})}}return[v,I,g]}editT(t,r,i,s,o){const a=this.findPos(t[0]),u=this.findPos(t[1]);this.edit([a,u],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);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 i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Lt.fromTreePos(i)}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 ed(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=(i,s=void 0,o=void 0,a=0)=>{var y,w,T,P;let u,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(u=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Lt.fromTreePos(h).toStruct());const m={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(y=i.removedAt)==null?void 0:y.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(T=i.insNextID)==null?void 0:T.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?ts((P=i.attrs)==null?void 0:P.toObject()):void 0,index:u,path:c,pos:d};for(let p=0;p0&&p===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(P,y)):i.push({type:"content",from:p,to:g,fromPath:this.toPath(T,h),toPath:this.toPath(P,y),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===me.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?me.Text:me.Start]:[t,me.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,me.End];const a=s[o+1];return[a,a.isText?me.Text:me.Start]}findLeftToken([t,r]){if(r===me.End){const u=t.allChildren;if(u.length>0){const c=u[u.length-1];return[c,c.isText?me.Text:me.End]}return[t,me.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,me.Start];const a=s[o-1];return[a,a.isText?me.Text:me.End]}}class bo extends $t{constructor(t,r,i,s,o,a,u){super(t,u);l(this,"fromPos");l(this,"toPos");l(this,"contents");l(this,"splitLevel");l(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,u){return new bo(t,r,i,s,o,a,u)}execute(t,r,i){var d;const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=this.getExecutedAt(),a=s,[u,c]=a.edit([this.fromPos,this.toPos],(d=this.contents)==null?void 0:d.map(h=>h.deepcopy()),this.splitLevel,o,(()=>{let h=o.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>Tt.of(o.getLamport(),++h,o.getActorID())})(),this.maxCreatedAtMapByActor,i);for(const h of c)t.registerGCPair(h);return{opInfos:u.map(({from:h,to:m,value:y,splitLevel:w,fromPath:T,toPath:P})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:m,value:y,splitLevel:w,fromPath:T,toPath:P}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=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`${t}.EDIT(${r},${i},${s.map(o=>ed(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ns{constructor(e){l(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new ns(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new ns(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new ns(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const _1=new ns(new Map);class lr{constructor(e,t,r,i,s){l(this,"clientSeq");l(this,"serverSeq");l(this,"lamport");l(this,"actor");l(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new lr(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new lr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n;let r=e.versionVector;r.size()===0&&(r=r.deepcopy(),r.set(e.actor,e.lamport));const i=this.versionVector.max(r),s=new lr(this.clientSeq,t,this.actor,i);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const r=e>this.lamport?e+1n:this.lamport+1n;t.unset($l);const i=this.versionVector.max(t);return i.set(this.actor,r),lr.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return Tt.of(this.lamport,e,this.actor)}setActor(e){return new lr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new lr(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const H1=new lr(0,0n,$l,_1);class ps{constructor({id:e,operations:t,presenceChange:r,message:i}){l(this,"id");l(this,"operations");l(this,"presenceChange");l(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new ps({id:e,operations:t,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 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 i=[],s=[];for(const o of this.operations){const a=o.execute(e,r,this.id.getVersionVector());if(!a)continue;const{opInfos:u,reverseOp:c}=a;i.push(...u),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Xr.Put?t.set(this.id.getActorID(),Pt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:de.bytesToHex(de.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>de.bytesToHex(de.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return ps.create({id:de.bytesToChangeID(de.hexToBytes(t)),operations:r==null?void 0:r.map(o=>de.bytesToOperation(de.hexToBytes(o))),presenceChange:i,message:s})}}class Ul{constructor(e,t,r,i,s,o,a){l(this,"documentKey");l(this,"checkpoint");l(this,"isRemoved");l(this,"changes");l(this,"snapshot");l(this,"minSyncedTicket");l(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Ul(e,t,r,i,s,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}getVersionVector(){return this.versionVector}}class rs{constructor(e,t){l(this,"serverSeq");l(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new rs(e,t)}increaseClientSeq(e){return e===0?this:new rs(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return rs.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==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const G1=new rs(0n,0);class sn{constructor(e,t){l(this,"createdAt");l(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new sn(e,t)}static fromStruct(e){return sn.of(Tt.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 sn(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 Y1=sn.of(Ft,0);class Mt{constructor(e,t){l(this,"id");l(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Mt(e,t)}static fromStruct(e){const t=sn.fromStruct(e.id);return Mt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return sn.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 Hr extends ry{constructor(t,r,i){super(r);l(this,"id");l(this,"removedAt");l(this,"prev");l(this,"next");l(this,"insPrev");l(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i: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 i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.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 i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r,i){if(!e.length)return[[],new Map,new Map];const[s,o]=this.filterNodes(e,t,r,i),a=new Map,u=new Map,c=this.makeChanges(o,t);for(const d of s){const h=d.getCreatedAt().getActorID();(!a.has(h)||d.getID().getCreatedAt().after(a.get(h)))&&a.set(h,d.getID().getCreatedAt()),u.set(d.getID().toIDString(),d),d.remove(t)}return this.deleteIndexNodes(o),[c,a,u]}filterNodes(e,t,r,i){const s=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID();let h,m=0n;i===void 0&&r===void 0?m=Gs:i.size()>0?m=i.get(d)?i.get(d):0n:h=r.has(d)?r.get(d):Ft,c.canDelete(t,h,m)?s.push(c):o.push(c)}return o.push(u),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var on=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(on||{});class nt extends Oo{constructor(t,r,i){super(i);l(this,"valueType");l(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=K.fromNumber(r).toInt():this.value=og(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=K.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new nt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return K.fromBytesLE(Array.from(r));default:throw new k(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=nt.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 K?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!!nt.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 k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.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=K.fromNumber(this.value+og(t.getValue())).toInt(),this}}class vs extends $t{constructor(t,r,i){super(t,i);l(this,"value");this.value=r}static create(t,r,i){return new vs(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return vs.create(this.getParentCreatedAt(),ie.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class yr extends $t{constructor(t,r,i,s,o,a,u){super(t,u);l(this,"fromPos");l(this,"toPos");l(this,"maxCreatedAtMapByActor");l(this,"attributes");l(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new yr(t,r,i,s,o,[],a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new yr(t,r,i,s,new Map,o,a)}execute(t,r,i){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=s;let a,u;if(this.attributes.size){const c={};[...this.attributes].forEach(([d,h])=>c[d]=h),[,u,a]=o.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}else{const c=this.attributesToRemove;[,u,a]=o.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor,i)}for(const c of u)t.registerGCPair(c);return{opInfos:a.map(({from:c,to:d,value:h,fromPath:m,toPath:y})=>({type:"tree-style",from:c,to:d,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:m,toPath:y,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()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.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 Q1(n){const e=new Qf,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function X1(n){if(n.type===Xr.Put)return new wo({type:Ei.PUT,presence:Q1(n.presence)});if(n.type===Xr.Clear)return new wo({type:Ei.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function Z1(n){return new ey({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function hy(n){return new Ml({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:fd(n.getActorID()),versionVector:td(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:fd(n.getActorID())})}function td(n){if(!n)return;const e=new Jl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function gy(n){switch(n){case ve.Null:return z.NULL;case ve.Boolean:return z.BOOLEAN;case ve.Integer:return z.INTEGER;case ve.Long:return z.LONG;case ve.Double:return z.DOUBLE;case ve.String:return z.STRING;case ve.Bytes:return z.BYTES;case ve.Date:return z.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function my(n){switch(n){case on.IntegerCnt:return z.INTEGER_CNT;case on.LongCnt:return z.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function Eu(n){if(n instanceof He)return new lt({type:z.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ny(n)});if(n instanceof tt)return new lt({type:z.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:DS(n)});if(n instanceof Et)return new lt({type:z.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ie)return new lt({type:gy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof nt)return new lt({type:my(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof xt)return new lt({type:z.TREE,createdAt:F(n.getCreatedAt()),value:RS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function eS(n){return new yo({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function na(n){return new Tr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ra(n){return new Ii({parentId:Ys(n.getParentID()),leftSiblingId:Ys(n.getLeftSiblingID())})}function Ys(n){return new Wr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function py(n){const e=new Yf;if(n instanceof xi){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Eu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Ro){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=Eu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Mr){const t=n,r=new el;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 Zr){const t=n,r=new tl;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 Lo){const t=n,r=new nl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=na(t.getFromPos()),r.to=na(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Bo){const t=n,r=new rl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=na(t.getFromPos()),r.to=na(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof vs){const t=n,r=new il;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=Eu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof bo){const t=n,r=new sl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ra(t.getFromPos()),r.to=ra(t.getToPos()),r.contents=aS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof yr){const t=n,r=new ol;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ra(t.getFromPos()),r.to=ra(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,u]of t.getAttributes())o[a]=u}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function tS(n){const e=[];for(const t of n)e.push(py(t));return e}function nS(n){const e=new Xp({id:hy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=tS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=X1(n.getPresenceChange())),e}function rS(n){const e=[];for(const t of n)e.push(nS(t));return e}function iS(n){const e=[];for(const t of n)e.push(new Zp({key:t.getStrKey(),element:rd(t.getValue())}));return e}function sS(n){const e=[];for(const t of n)e.push(new hl({element:rd(t.getValue())}));return e}function oS(n){const e=[];for(const t of n){const r=new gl;r.id=eS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new hs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function aS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new ml({content:nd(t)}));return e}function lS(n){const e={};for(const t of n)e[t.getKey()]=new hs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function nd(n){if(!n)return[];const e=[];return zl(n,(t,r)=>{const i=new vo({id:Ys(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Ys(t.insPrevID)),t.insNextID&&(i.insNextId=Ys(t.insNextID)),t.attrs&&(i.attributes=lS(t.attrs)),e.push(i)}),e}function uS(n){const e=new Ge;return e.body.case="jsonObject",e.body.value=new al({nodes:iS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function yy(n){const e=new Ge;return e.body.case="jsonArray",e.body.value=new ll({nodes:sS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function cS(n){const e=new Ge;return e.body.case="primitive",e.body.value=new ul({type:gy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function fS(n){const e=new Ge;return e.body.case="text",e.body.value=new cl({nodes:oS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new Ge;return e.body.case="counter",e.body.value=new fl({type:my(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function vy(n){const e=new Ge;return e.body.case="tree",e.body.value=new dl({nodes:nd(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function rd(n){if(n instanceof He)return uS(n);if(n instanceof tt)return yy(n);if(n instanceof ie)return cS(n);if(n instanceof Et)return fS(n);if(n instanceof nt)return dS(n);if(n instanceof xt)return vy(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function hS(n){return new Er({documentKey:n.getDocumentKey(),checkpoint:Z1(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:rS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:td(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function Ms(n){if(!(n instanceof te))return{};const e=n.findDetails(R1);for(const t of e)return t.metadata;return{}}function Ri(n){return Ms(n).code??""}function wy(n){return lr.of(n.clientSeq,BigInt(n.lamport),ud(n.actorId),id(n.versionVector),BigInt(n.serverSeq))}function id(n){if(!n)return;const e=new ns;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return Tt.of(BigInt(n.lamport),n.delimiter,ud(n.actorId))}function sd(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function gS(n){const e=n.type;if(e===Ei.PUT){const t=sd(n.presence);return{type:Xr.Put,presence:t}}if(e===Ei.CLEAR)return{type:Xr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function mS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,sd(r))}),e}function Sy(n){switch(n){case z.NULL:return ve.Null;case z.BOOLEAN:return ve.Boolean;case z.INTEGER:return ve.Integer;case z.LONG:return ve.Long;case z.DOUBLE:return ve.Double;case z.STRING:return ve.String;case z.BYTES:return ve.Bytes;case z.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function vl(n){switch(n){case z.INTEGER_CNT:return on.IntegerCnt;case z.LONG_CNT:return on.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function xu(n){switch(n.type){case z.JSON_OBJECT:return n.value?Cy(n.value):He.create(M(n.createdAt));case z.JSON_ARRAY:return n.value?PS(n.value):tt.create(M(n.createdAt));case z.TEXT:return Et.create(ys.create(),M(n.createdAt));case z.TREE:return OS(n.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 ie.of(ie.valueFromBytes(Sy(n.type),n.value),M(n.createdAt));case z.INTEGER_CNT:case z.LONG_CNT:return nt.create(vl(n.type),nt.valueFromBytes(vl(n.type),n.value),M(n.createdAt))}}function ia(n){return Mt.of(sn.of(M(n.createdAt),n.offset),n.relativeOffset)}function ky(n){return sn.of(M(n.createdAt),n.offset)}function pS(n){const e=Ao.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(ky(n.id),e);return t.remove(M(n.removedAt)),t}function Li(n){return Lt.of(Qs(n.parentId),Qs(n.leftSiblingId))}function Qs(n){return Ce.of(M(n.createdAt),n.offset)}function yS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=od(t.content);e.push(r)}),e}function od(n){if(n.length===0)return;const e=[];for(const i of n)e.push(wS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),xt.create(t,Ft).getRoot()}function vS(n){const e=Ar.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function wS(n){const e=Qs(n.id),t=Ze.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=vS(n.attributes)),n.insPrevId&&(t.insPrevID=Qs(n.insPrevId)),n.insNextId&&(t.insNextID=Qs(n.insNextId)),t.removedAt=M(n.removedAt),t}function Ty(n){if(n.body.case==="set"){const e=n.body.value;return xi.create(e.key,xu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Ro.create(M(e.parentCreatedAt),M(e.prevCreatedAt),xu(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Mr.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 Zr.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(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Lo.create(M(e.parentCreatedAt),ia(e.from),ia(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(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Bo.create(M(e.parentCreatedAt),ia(e.from),ia(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 vs.create(M(e.parentCreatedAt),xu(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,i])=>{t.set(r,M(i))}),bo.create(M(e.parentCreatedAt),Li(e.from),Li(e.to),yS(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,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?yr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Li(e.from),Li(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),yr.create(M(e.parentCreatedAt),Li(e.from),Li(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function SS(n){const e=[];for(const t of n){const r=Ty(t);r&&e.push(r)}return e}function Ay(n){const e=[];for(const t of n)e.push(ps.create({id:wy(t.id),operations:SS(t.operations),presenceChange:t.presenceChange?gS(t.presenceChange):void 0,message:t.message}));return e}function kS(n){return rs.of(BigInt(n.serverSeq),n.clientSeq)}function TS(n){return Ul.create(n.documentKey,kS(n.checkpoint),n.isRemoved,Ay(n.changes),id(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function Iy(n){const e=new So;for(const r of n.nodes){const i=ad(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new He(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Ey(n){const e=new To;for(const r of n.nodes)e.insert(ad(r.element));const t=new tt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function AS(n){const e=ie.of(ie.valueFromBytes(Sy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function IS(n){const e=new ys;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,pS(i));i.insPrevId&&s.setInsPrev(e.findNode(ky(i.insPrevId))),t=s}const r=new Et(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function ES(n){const e=nt.create(vl(n.type),nt.valueFromBytes(vl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xy(n){const e=od(n.nodes);return xt.create(e,M(n.createdAt))}function ad(n){if(n.body.case==="jsonObject")return Iy(n.body.value);if(n.body.case==="jsonArray")return Ey(n.body.value);if(n.body.case==="primitive")return AS(n.body.value);if(n.body.case==="text")return IS(n.body.value);if(n.body.case==="counter")return ES(n.body.value);if(n.body.case==="tree")return xy(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function xS(n){if(!n)return{root:He.create(Ft),presences:new Map};const e=Ec.fromBinary(n);return{root:ad(e.root),presences:mS(e.presences)}}function CS(n){const e=td(n);return ld(e.toBinary())}function NS(n){const e=cd(n),t=Jl.fromBinary(e);return id(t)}function Cy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=Ge.fromBinary(n);return Iy(e.body.value)}function Ny(n){return rd(n).toBinary()}function PS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=Ge.fromBinary(n);return Ey(e.body.value)}function DS(n){return yy(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=Ge.fromBinary(n);return xy(e.body.value)}function RS(n){return vy(n).toBinary()}function ld(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ud(n){return ld(n)}function cd(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function fd(n){return cd(n)}function LS(n){const e=Ml.fromBinary(n);return wy(e)}function BS(n){const e=Yf.fromBinary(n);return Ty(e)}const de={fromPresence:sd,toChangePack:hS,fromChangePack:TS,fromChanges:Ay,toTreeNodes:nd,fromTreeNodes:od,objectToBytes:Ny,bytesToObject:Cy,bytesToSnapshot:xS,bytesToHex:ld,hexToBytes:cd,toHexString:ud,toUint8Array:fd,toOperation:py,toChangeID:hy,PbChangeID:Ml,bytesToChangeID:LS,bytesToOperation:BS,versionVectorToHex:CS,hexToVersionVector:NS};var Me=(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))(Me||{});let li=3;function Py(n){li=n}const J={trivial:(...n)=>{li>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{li>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{li>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{li>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{li>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=>li<=n};function Dy(){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 bS{constructor(e,t,r,i,s){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=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ea.RealtimeSyncOff?!1:this.syncMode===Ea.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ea.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 Cu=()=>{};class FS{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,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Cu),i.error===void 0&&(i.error=Cu),i.complete===void 0&&(i.complete=Cu);const s=Dy(),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){J.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 Hi{constructor(e,t,r,i){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=ny,this.root=t,this.operations=[],this.previousPresence=Pt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Hi(e,t,r,i)}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 ps.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 Io{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 Et||t instanceof xt)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Io(He.create(Ft))}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 i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),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 _r&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof _r&&e.getDescendants(i=>(r(i),!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 _r&&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 Io(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Oy(n,e){const t=new Eo(n);return new Proxy(e,t.getHandlers())}class Eo{constructor(e){l(this,"context");l(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),Eo.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():ui(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(Me.Trivial)&&J.trivial(`obj[${r}]`),Eo.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=wl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(xi.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=wl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function JS(n,e){const t=new ae(n,e);return new Proxy(e,t.getHandlers())}function $S(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class ae{constructor(e,t){l(this,"context");l(this,"handlers");l(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Pr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Pr(e,a)}:i==="getLast"?()=>Pr(e,r.getLast()):i==="deleteByID"?o=>{const a=ae.deleteInternalByID(e,r,o);return Pr(e,a)}:i==="insertAfter"?(o,a)=>{const u=ae.insertAfterInternal(e,r,o,a);return Pr(e,u)}:i==="insertBefore"?(o,a)=>{const u=ae.insertBeforeInternal(e,r,o,a);return Pr(e,u)}:i==="moveBefore"?(o,a)=>{ae.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ae.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ae.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ae.moveLastInternal(e,r,o)}:$S(i)?ui(e,r.get(Number(i))):i==="push"?o=>ae.pushInternal(e,r,o):i==="splice"?(o,a,...u)=>ae.splice(e,r,o,a,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ae.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ae.includes(e,r,o,a):i==="indexOf"?(o,a)=>ae.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ae.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ae.toTestString(r):typeof i=="string"&&zS(i)?(...o)=>{const a=Array.from(r).map(u=>ui(e,u));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(Me.Trivial)&&J.trivial(`array[${i}]`),ae.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Pr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=wl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return ae.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(Mr.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(Mr.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(Mr.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(Mr.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=wl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Ro.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return ae.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Zr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),u=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(ie.isSupport(r))return Array.from(t).map(c=>ui(e,c)).includes(r,o);for(let u=o;u=s)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ui(e,c)).indexOf(r,o);for(let u=o;u=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ui(e,c)).lastIndexOf(r,o);for(let u=o;u>0;u--)if(((a=t.get(u))==null?void 0:a.getID())===r.getID())return u;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class jl{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,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(Me.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?gs(i):void 0,a=this.context.issueTimeTicket(),[u,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Lo(this.text.getCreatedAt(),s[0],s[1],u,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}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 k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(Me.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=gs(r),o=this.context.issueTimeTicket(),[a,u]=this.text.setStyle(i,s,o);for(const c of u)this.context.registerGCPair(c);return this.context.push(new Bo(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(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 k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Mt.fromStruct(e[0]),Mt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(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 k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class Vl{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 k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ie.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(vs.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function dd(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===pr){Ry(n);const{value:s}=n,o=Ze.create(Ce.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!ty(o)){const c=gs(o);a=new Ar;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const u=Ze.create(Ce.of(i,0),r,void 0,a);e.append(u);for(const c of s)dd(c,u,t)}}function US(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===pr){const{value:s}=e;i=Ze.create(Ce.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!ty(o)){const u=gs(o);a=new Ar;for(const[c,d]of Object.entries(u))a.set(c,d,r)}i=Ze.create(Ce.of(n.issueTimeTicket(),0),t,void 0,a);for(const u of s)dd(u,i,n)}return i}function Ry(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function ag(n){if(!n.length)return!0;if(n[0].type===pr)for(const t of n){const{type:r}=t;if(r!==pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Ry(t)}else for(const t of n){const{type:r}=t;if(r===pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class ql{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 Ze.create(Ce.of(e.issueTimeTicket(),0),$1);const t=Ze.create(Ce.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)dd(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?gs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(yr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?gs(r):void 0,[u,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(yr.create(this.tree.getCreatedAt(),i,s,u,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,u]=this.tree.removeStyle([i,s],r,o);for(const c of u)this.context.registerGCPair(c);this.context.push(yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(ag(r),r[0].type!==pr))for(const d of r){const{children:h=[]}=d;ag(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===pr){let d="";for(const h of r){const{value:m}=h;d+=m}o.push(Ze.create(Ce.of(this.context.issueTimeTicket(),0),pr,d))}else o=r.map(d=>d&&US(this.context,d)).filter(d=>d);const[,a,u]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(bo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,u,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(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,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(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,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.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 k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function lg(n,e){return Oy(n,e)}function Pr(n,e){if(e){if(e instanceof ie)return e;if(e instanceof He)return Oy(n,e);if(e instanceof tt)return JS(n,e);if(e instanceof Et)return new jl(n,e);if(e instanceof nt){const t=new Vl(on.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof xt){const t=new ql;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ui(n,e){const t=Pr(n,e);return t instanceof ie?t.getValue():t}function wl(n,e,t){let r;if(ie.isSupport(e))r=ie.of(e,t);else if(Array.isArray(e))r=tt.create(t,ae.buildArrayElements(n,e));else if(typeof e=="object")e instanceof jl?(r=Et.create(ys.create(),t),e.initialize(n,r)):e instanceof Vl?(r=nt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof ql?(r=xt.create(e.buildRoot(n),t),e.initialize(n,r)):r=He.create(t,Eo.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const ug=50;class jS{constructor(){l(this,"undoStack",[]);l(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=ug&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=ug&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const VS="yorkie-devtools-panel",qS="yorkie-devtools-sdk";let Bi="disconnected";const cg=new Map,Ia=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Ia);function sa(n,e){(e!=null&&e.force||Bi!=="disconnected")&&window.postMessage({source:qS,...n},"*")}function KS(n){if(!n.isEnableDevtools()||typeof window>"u"||cg.has(n.getKey()))return;Ia.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Ee.StatusChanged&&r.type!==Ee.Snapshot&&r.type!==Ee.LocalChange&&r.type!==Ee.RemoteChange&&r.type!==Ee.Initialized&&r.type!==Ee.Watched&&r.type!==Ee.Unwatched&&r.type!==Ee.PresenceChanged)||(Ia.get(n.getKey()).push(t),Bi==="synced"&&sa({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});cg.set(n.getKey(),[e]),sa({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==VS)return;switch(t.data.msg){case"devtools::connect":if(Bi!=="disconnected")break;Bi="connected",sa({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Bi="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Bi="synced",sa({msg:"doc::sync::full",docKey:n.getKey(),events:Ia.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Dr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Dr||{}),Ee=(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.AuthError="auth-error",n))(Ee||{}),Qc=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Qc||{}),Xc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Xc||{});class Ly{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=Io.create(),this.changeID=H1,this.checkpoint=G1,this.localChanges=[],this.eventStream=MS(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new jS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},KS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=lg(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Iu(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(Me.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),u=i.getReversePresence();u&&a.push({type:"presence",value:u}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.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()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(Me.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="broadcast"&&a(c)},r)}if(e==="auth-error"){const a=t;return this.eventStream.subscribe(u=>{for(const c of u)c.type==="auth-error"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const u of a){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const c=[];for(const d of u.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...u,value:{...u.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(u=>{for(const c of u)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.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((s,o)=>s===r[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),Y.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(Me.Trivial)&&J.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:Pt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Ul.create(this.key,t,!1,e,this.getVersionVector())}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=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return lg(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r,i=-1){const{root:s,presences:o}=de.bytesToSnapshot(r);this.root=new Io(s),this.presences=o,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,Y.Local),this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?de.bytesToHex(r):void 0,snapshotVector:de.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(Me.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(Me.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);J.isEnabled(Me.Debug)&&J.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=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Xr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Xr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,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 t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===vi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===vi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===vi.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($l),this.publish([{source:e==="removed"?Y.Remote:Y.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,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),de.hexToVersionVector(i),de.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ps.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);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 k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)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?Pt(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?Pt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Pt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Pt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Pt(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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new Iu(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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(),u=[];i.length>0&&u.push({type:"local-change",source:Y.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()&&u.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new Iu(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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(),u=[];i.length>0&&u.push({type:"local-change",source:Y.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()&&u.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function WS(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const _S="yorkie-js-sdk",HS="0.5.6",GS="Yorkie JS SDK",YS="./src/yorkie.ts",QS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},XS=["dist"],ZS={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"},ek={node:">=18.0.0",npm:">=7.1.0"},tk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},nk={name:"hackerwins",email:"susukang98@gmail.com"},rk="Apache-2.0",ik={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},sk="https://github.com/yorkie-team/yorkie-js-sdk#readme",ok={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ak={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},fg={name:_S,version:HS,description:GS,main:YS,publishConfig:QS,files:XS,scripts:ZS,engines:ek,repository:tk,author:nk,license:rk,bugs:ik,homepage:sk,devDependencies:ok,dependencies:ak};function lk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",fg.name+"/"+fg.version),await n(e))}const uk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ea=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ea||{});const oa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Nu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class By{constructor(e,t){l(this,"id");l(this,"key");l(this,"status");l(this,"attachmentMap");l(this,"apiKey");l(this,"authTokenInjector");l(this,"conditions");l(this,"syncLoopDuration");l(this,"reconnectStreamDelay");l(this,"retrySyncLoopDelay");l(this,"rpcClient");l(this,"setAuthToken");l(this,"taskQueue");l(this,"processing",!1);l(this,"keepalive",!1);t=t||oa,this.key=t.key?t.key:Dy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??oa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??oa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??oa.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=WS(this.apiKey);this.setAuthToken=i,this.rpcClient=l1(O1,D1({baseUrl:e,interceptors:[r,lk()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw J.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Dr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,u=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(u==null||u(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:de.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=de.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Dr.Removed)return e;e.applyStatus(Dr.Attached),this.attachmentMap.set(e.getKey(),new bS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(u))if(!a.has(d)){const m=d;c[m]=h}})}return e}).catch(async s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.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:de.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=de.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Dr.Removed&&e.applyStatus(Dr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=de.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(i=>{const s=de.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),await 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,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!uk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Nu.maxRetries,a=Nu.maxBackoff;let u=0;const c=h=>Math.min(Nu.initialRetryInterval*2**h,a),d=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":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),await this.handleConnectError(h))if(h instanceof te&&Ri(h)===S.ErrUnauthenticated&&s.doc.publish([{type:Ee.AuthError,value:{reason:Ms(h).reason,method:"Broadcast"}}]),ud(),c(u-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.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).catch(async i=>{throw i instanceof te&&Ri(i)===S.ErrUnauthenticated&&r.doc.publish([{type:Ee.AuthError,value:{reason:Ms(i).reason,method:"PushPull"}}]),i})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.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 k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:Ee.ConnectionChanged,value:Qc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:Ee.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Ee.ConnectionChanged,value:Qc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(c)?(c instanceof te&&Ri(c)===S.ErrUnauthenticated&&t.doc.publish([{type:Ee.AuthError,value:{reason:Ms(c).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===vi.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(Dr.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:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:de.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=de.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Ee.SyncStatusChanged,value:Xc.Synced}]),r.getStatus()===Dr.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Ee.SyncStatusChanged,value:Xc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof te))return!1;if(e.code===H.Canceled||e.code===H.Unknown||e.code===H.ResourceExhausted||e.code===H.Unavailable)return!0;if(Ri(e)===S.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Ms(e).reason);this.setAuthToken(t)}return!0}return(Ri(e)===S.ErrClientNotActivated||Ri(e)===S.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(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const by={Client:By,Document:Ly,Primitive:ie,Text:jl,Counter:Vl,Tree:ql,LogLevel:Me,setLogLevel:Py,IntType:on.IntegerCnt,LongType:on.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:By,Document:Ly,Primitive:ie,Text:jl,Counter:Vl,Tree:ql,LogLevel:Me,setLogLevel:Py,IntType:on.IntegerCnt,LongType:on.LongCnt});class ck{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const fk=({xPos:n,yPos:e})=>{const[t,r]=je.useState([]),i=je.useRef(null),[s,o]=je.useState([]),a=(u,c)=>{const d=new ck(u,c);s.push(d),o(s),t.push(d),r(t)};return je.useEffect(()=>{const c=i.current.getContext("2d"),d=()=>{c.clearRect(0,0,c.canvas.width,c.canvas.height);const h=.7*(1*4e3)/60;for(let m=0;mh)s.shift();else{c.lineWidth=5,c.lineJoin="round";const T=0,P=0,p=0;c.strokeStyle=`rgb(${T},${P},${p})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(y.x,y.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),je.useEffect(()=>{a(n,e)},[n,e]),ce.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},dk="_goUp0_1lnal_1",hk="_goUpAnimation0_1lnal_1",gk="_fadeOut_1lnal_1",mk="_goUp1_1lnal_16",pk="_goUpAnimation1_1lnal_1",yk="_goUp2_1lnal_31",vk="_goUpAnimation2_1lnal_1",wk="_leftRight0_1lnal_46",Sk="_leftRightAnimation0_1lnal_1",kk="_leftRight1_1lnal_60",Tk="_leftRightAnimation1_1lnal_1",Ak="_leftRight2_1lnal_74",Ik="_leftRightAnimation2_1lnal_1",Pu={goUp0:dk,goUpAnimation0:hk,fadeOut:gk,goUp1:mk,goUpAnimation1:pk,goUp2:yk,goUpAnimation2:vk,leftRight0:wk,leftRightAnimation0:Sk,leftRight1:kk,leftRightAnimation1:Tk,leftRight2:Ak,leftRightAnimation2:Ik};function Ek({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ce.jsx("div",{className:"single-animation-container",children:ce.jsx("div",{className:`absolute select-none pointer-events-none ${Pu.disappear} text-${t%5+2}xl ${Pu["goUp"+t%3]}`,style:{left:n,top:e},children:ce.jsx("div",{className:Pu["leftRight"+t%3],children:ce.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ce.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function dg(n,e){const t=je.useRef(n);je.useEffect(()=>{t.current=n},[n]),je.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const xk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=je.useState([]),o=100;return dg(()=>{s(a=>a.filter(u=>u.timestamp>Date.now()-4e3))},1e3),dg(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ce.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ce.jsx(Ek,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},Ck=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ce.jsxs(ce.Fragment,{children:[ce.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ce.jsx(xk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ce.jsx(fk,{xPos:e,yPos:t})]}),Nk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=je.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ce.jsxs("div",{className:"cursor-selector-container",children:[ce.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ce.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ce.jsx("div",{className:"num-users-container",children:ce.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Du=new by.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),si=new by.Document("simultaneous-cursors",{enableDevtools:!0}),Pk=()=>{const[n,e]=je.useState([]),t=r=>{si.update((i,s)=>{s.set({cursorShape:r})})};return je.useEffect(()=>{(async()=>{await Du.activate(),si.subscribe("presence",a=>{e(si.getPresences())}),await Du.attach(si,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Du.deactivate()})})();const i=()=>{si.update((a,u)=>{u.set({pointerDown:!1})})},s=()=>{si.update((a,u)=>{u.set({pointerDown:!0})})},o=a=>{si.update((u,c)=>{c.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)}},[]),ce.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ce.jsx(Ck,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ce.jsx(Nk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Ou.createRoot(document.getElementById("root")).render(ce.jsx(Pk,{})); +`));for(const r of e)this.applyChange(r,t);J.isEnabled(Me.Debug)&&J.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=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Xr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Xr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,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 t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===vi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===vi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===vi.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($l),this.publish([{source:e==="removed"?Y.Remote:Y.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,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),de.hexToVersionVector(i),de.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ps.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);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 k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)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?Pt(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?Pt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Pt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Pt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Pt(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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new Iu(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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(),u=[];i.length>0&&u.push({type:"local-change",source:Y.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()&&u.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Hi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new Iu(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.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(),u=[];i.length>0&&u.push({type:"local-change",source:Y.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()&&u.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function WS(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const _S="yorkie-js-sdk",HS="0.5.7",GS="Yorkie JS SDK",YS="./src/yorkie.ts",QS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},XS=["dist"],ZS={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"},ek={node:">=18.0.0",npm:">=7.1.0"},tk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},nk={name:"hackerwins",email:"susukang98@gmail.com"},rk="Apache-2.0",ik={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},sk="https://github.com/yorkie-team/yorkie-js-sdk#readme",ok={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},ak={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},fg={name:_S,version:HS,description:GS,main:YS,publishConfig:QS,files:XS,scripts:ZS,engines:ek,repository:tk,author:nk,license:rk,bugs:ik,homepage:sk,devDependencies:ok,dependencies:ak};function lk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",fg.name+"/"+fg.version),await n(e))}const uk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ea=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ea||{});const oa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Nu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class By{constructor(e,t){l(this,"id");l(this,"key");l(this,"status");l(this,"attachmentMap");l(this,"apiKey");l(this,"authTokenInjector");l(this,"conditions");l(this,"syncLoopDuration");l(this,"reconnectStreamDelay");l(this,"retrySyncLoopDelay");l(this,"rpcClient");l(this,"setAuthToken");l(this,"taskQueue");l(this,"processing",!1);l(this,"keepalive",!1);t=t||oa,this.key=t.key?t.key:Dy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??oa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??oa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??oa.retrySyncLoopDelay;const{authInterceptor:r,setToken:i}=WS(this.apiKey);this.setAuthToken=i,this.rpcClient=l1(O1,D1({baseUrl:e,interceptors:[r,lk()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw J.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Dr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,u=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(u==null||u(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:de.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=de.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Dr.Removed)return e;e.applyStatus(Dr.Attached),this.attachmentMap.set(e.getKey(),new bS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(u))if(!a.has(d)){const m=d;c[m]=h}})}return e}).catch(async s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.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:de.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=de.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Dr.Removed&&e.applyStatus(Dr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=de.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(i=>{const s=de.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),await 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,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!uk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Nu.maxRetries,a=Nu.maxBackoff;let u=0;const c=h=>Math.min(Nu.initialRetryInterval*2**h,a),d=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":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),await this.handleConnectError(h))if(h instanceof te&&Ri(h)===S.ErrUnauthenticated&&s.doc.publish([{type:Ee.AuthError,value:{reason:Ms(h).reason,method:"Broadcast"}}]),ud(),c(u-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.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).catch(async i=>{throw i instanceof te&&Ri(i)===S.ErrUnauthenticated&&r.doc.publish([{type:Ee.AuthError,value:{reason:Ms(i).reason,method:"PushPull"}}]),i})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.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 k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:Ee.ConnectionChanged,value:Qc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:Ee.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Ee.ConnectionChanged,value:Qc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(c)?(c instanceof te&&Ri(c)===S.ErrUnauthenticated&&t.doc.publish([{type:Ee.AuthError,value:{reason:Ms(c).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===vi.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(Dr.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:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:de.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=de.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Ee.SyncStatusChanged,value:Xc.Synced}]),r.getStatus()===Dr.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Ee.SyncStatusChanged,value:Xc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof te))return!1;if(e.code===H.Canceled||e.code===H.Unknown||e.code===H.ResourceExhausted||e.code===H.Unavailable)return!0;if(Ri(e)===S.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Ms(e).reason);this.setAuthToken(t)}return!0}return(Ri(e)===S.ErrClientNotActivated||Ri(e)===S.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(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const by={Client:By,Document:Ly,Primitive:ie,Text:jl,Counter:Vl,Tree:ql,LogLevel:Me,setLogLevel:Py,IntType:on.IntegerCnt,LongType:on.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:By,Document:Ly,Primitive:ie,Text:jl,Counter:Vl,Tree:ql,LogLevel:Me,setLogLevel:Py,IntType:on.IntegerCnt,LongType:on.LongCnt});class ck{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const fk=({xPos:n,yPos:e})=>{const[t,r]=je.useState([]),i=je.useRef(null),[s,o]=je.useState([]),a=(u,c)=>{const d=new ck(u,c);s.push(d),o(s),t.push(d),r(t)};return je.useEffect(()=>{const c=i.current.getContext("2d"),d=()=>{c.clearRect(0,0,c.canvas.width,c.canvas.height);const h=.7*(1*4e3)/60;for(let m=0;mh)s.shift();else{c.lineWidth=5,c.lineJoin="round";const T=0,P=0,p=0;c.strokeStyle=`rgb(${T},${P},${p})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(y.x,y.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),je.useEffect(()=>{a(n,e)},[n,e]),ce.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},dk="_goUp0_1lnal_1",hk="_goUpAnimation0_1lnal_1",gk="_fadeOut_1lnal_1",mk="_goUp1_1lnal_16",pk="_goUpAnimation1_1lnal_1",yk="_goUp2_1lnal_31",vk="_goUpAnimation2_1lnal_1",wk="_leftRight0_1lnal_46",Sk="_leftRightAnimation0_1lnal_1",kk="_leftRight1_1lnal_60",Tk="_leftRightAnimation1_1lnal_1",Ak="_leftRight2_1lnal_74",Ik="_leftRightAnimation2_1lnal_1",Pu={goUp0:dk,goUpAnimation0:hk,fadeOut:gk,goUp1:mk,goUpAnimation1:pk,goUp2:yk,goUpAnimation2:vk,leftRight0:wk,leftRightAnimation0:Sk,leftRight1:kk,leftRightAnimation1:Tk,leftRight2:Ak,leftRightAnimation2:Ik};function Ek({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ce.jsx("div",{className:"single-animation-container",children:ce.jsx("div",{className:`absolute select-none pointer-events-none ${Pu.disappear} text-${t%5+2}xl ${Pu["goUp"+t%3]}`,style:{left:n,top:e},children:ce.jsx("div",{className:Pu["leftRight"+t%3],children:ce.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ce.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function dg(n,e){const t=je.useRef(n);je.useEffect(()=>{t.current=n},[n]),je.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const xk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=je.useState([]),o=100;return dg(()=>{s(a=>a.filter(u=>u.timestamp>Date.now()-4e3))},1e3),dg(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ce.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ce.jsx(Ek,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},Ck=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ce.jsxs(ce.Fragment,{children:[ce.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ce.jsx(xk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ce.jsx(fk,{xPos:e,yPos:t})]}),Nk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=je.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ce.jsxs("div",{className:"cursor-selector-container",children:[ce.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ce.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ce.jsx("div",{className:"num-users-container",children:ce.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Du=new by.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),si=new by.Document("simultaneous-cursors",{enableDevtools:!0}),Pk=()=>{const[n,e]=je.useState([]),t=r=>{si.update((i,s)=>{s.set({cursorShape:r})})};return je.useEffect(()=>{(async()=>{await Du.activate(),si.subscribe("presence",a=>{e(si.getPresences())}),await Du.attach(si,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Du.deactivate()})})();const i=()=>{si.update((a,u)=>{u.set({pointerDown:!1})})},s=()=>{si.update((a,u)=>{u.set({pointerDown:!0})})},o=a=>{si.update((u,c)=>{c.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)}},[]),ce.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ce.jsx(Ck,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ce.jsx(Nk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Ou.createRoot(document.getElementById("root")).render(ce.jsx(Pk,{})); diff --git a/examples/simultaneous-cursors/index.html b/examples/simultaneous-cursors/index.html index 39f3c1c82..b285d0753 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-DBSPfpB3.js b/examples/vanilla-codemirror6/assets/index-B0zBj6cl.js similarity index 99% rename from examples/vanilla-codemirror6/assets/index-DBSPfpB3.js rename to examples/vanilla-codemirror6/assets/index-B0zBj6cl.js index e84252605..7cdf5af1a 100644 --- a/examples/vanilla-codemirror6/assets/index-DBSPfpB3.js +++ b/examples/vanilla-codemirror6/assets/index-B0zBj6cl.js @@ -20,7 +20,7 @@ var bS=Object.defineProperty;var SS=(n,e,t)=>e in n?bS(n,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var $t=null;try{$t=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 Y(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}Y.prototype.__isLong__;Object.defineProperty(Y.prototype,"__isLong__",{value:!0});function ze(n){return(n&&n.__isLong__)===!0}function Rd(n){var e=Math.clz32(n&-n);return n?31-e:e}Y.isLong=ze;var Ed={},Dd={};function Lr(n,e){var t,i,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(i=Dd[n],i)?i:(t=te(n,0,!0),r&&(Dd[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(i=Ed[n],i)?i:(t=te(n,n<0?-1:0,!1),r&&(Ed[n]=t),t))}Y.fromInt=Lr;function Ct(n,e){if(isNaN(n))return e?En:Ft;if(e){if(n<0)return En;if(n>=tO)return rO}else{if(n<=-Bd)return tt;if(n+1>=Bd)return nO}return n<0?Ct(-n,e).neg():te(n%ds|0,n/ds|0,e)}Y.fromNumber=Ct;function te(n,e,t){return new Y(n,e,t)}Y.fromBits=te;var Sl=Math.pow;function Yu(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?En:Ft;if(t=t||10,t<2||360)throw Error("interior hyphen");if(i===0)return Yu(n.substring(1),e,t).neg();for(var r=Ct(Sl(t,8)),s=Ft,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*ds+(this.low>>>0):this.high*ds+(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=ei(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=ei(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?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(Jr)};C.neg=C.negate;C.add=function(e){ze(e)||(e=ei(e));var t=this.high>>>16,i=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,p=0;return p+=s+h,f+=p>>>16,p&=65535,f+=r+l,u+=f>>>16,f&=65535,u+=i+a,c+=u>>>16,u&=65535,c+=t+o,c&=65535,te(f<<16|p,c<<16|u,this.unsigned)};C.subtract=function(e){return ze(e)||(e=ei(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(ze(e)||(e=ei(e)),$t){var t=$t.mul(this.low,this.high,e.low,e.high);return te(t,$t.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?En:Ft;if(this.eq(tt))return e.isOdd()?tt:Ft;if(e.eq(tt))return this.isOdd()?tt:Ft;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(qd)&&e.lt(qd))return Ct(this.toNumber()*e.toNumber(),this.unsigned);var i=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,p=0,g=0;return g+=o*c,p+=g>>>16,g&=65535,p+=s*c,f+=p>>>16,p&=65535,p+=o*h,f+=p>>>16,p&=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+=i*c+r*h+s*l+o*a,u&=65535,te(p<<16|g,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(ze(e)||(e=ei(e)),e.isZero())throw Error("division by zero");if($t){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?$t.div_u:$t.div_s)(this.low,this.high,e.low,e.high);return te(t,$t.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?En:Ft;var i,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return En;if(e.gt(this.shru(1)))return iO;s=En}else{if(this.eq(tt)){if(e.eq(Jr)||e.eq(Xc))return tt;if(e.eq(tt))return Jr;var o=this.shr(1);return i=o.div(e).shl(1),i.eq(Ft)?e.isNegative()?Jr:Xc:(r=this.sub(e.mul(i)),s=i.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?En:Ft;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=Ft}for(r=this;r.gte(e);){i=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(i)/Math.LN2),l=a<=48?1:Sl(2,a-48),h=Ct(i),c=h.mul(e);c.isNegative()||c.gt(r);)i-=l,h=Ct(i,this.unsigned),c=h.mul(e);h.isZero()&&(h=Jr),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(ze(e)||(e=ei(e)),$t){var t=(this.unsigned?$t.rem_u:$t.rem_s)(this.low,this.high,e.low,e.high);return te(t,$t.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return te(~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?Rd(this.low):Rd(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return ze(e)||(e=ei(e)),te(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return ze(e)||(e=ei(e)),te(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return ze(e)||(e=ei(e)),te(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?te(this.low<>>32-e,this.unsigned):te(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):te(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?te(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?te(this.high,0,this.unsigned):te(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?te(this.high,this.low,this.unsigned):e<32?(t=32-e,te(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,te(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?te(this.high,this.low,this.unsigned):e<32?(t=32-e,te(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,te(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?te(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:te(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]};Y.fromBytes=function(e,t,i){return i?Y.fromBytesLE(e,t):Y.fromBytesBE(e,t)};Y.fromBytesLE=function(e,t){return new Y(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Y.fromBytesBE=function(e,t){return new Y(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var $e=(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))($e||{});class ge extends Vo{constructor(t,i){super(i);d(this,"valueType");d(this,"value");this.valueType=ge.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,i){return new ge(t,i)}static valueFromBytes(t,i){switch(t){case 0:return null;case 1:return!!i[0];case 2:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 4:{const r=new DataView(i.buffer);return i.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(i);case 3:return Y.fromBytesLE(Array.from(i));case 6:return i;case 7:return new Date(Y.fromBytesLE(Array.from(i),!0).toNumber());default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${wi(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ge.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 Y)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ge.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,i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),i}case 5:return new TextEncoder().encode(this.value);case 3:{const i=this.value.toBytesLE();return Uint8Array.from(i)}case 6:return this.value;case 7:{const t=this.value,i=Y.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class wl extends eO{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,i){const r=new wl(i),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 mo{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=ge.of(0,Gt);e.setRemovedAt(Gt),this.dummyHead=new wl(e),this.last=this.dummyHead,this.nodeMapByIndex=new go,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new mo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;i.getNext()&&i.getNext().getPositionedAt().after(t);)i=i.getNext();return i}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,i=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,i),s=wl.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,i){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(w.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||i.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),i),s.getValue().setMovedAt(i))}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(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,i]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||i>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 i=this.nodeMapByCreatedAt.get(e.toIDString()),r=i.isRemoved();return i.remove(t)&&!r&&this.nodeMapByIndex.splayNode(i),i.getValue()}deleteByIndex(e,t){const i=this.getByIndex(e);if(i)return i.remove(t)&&this.nodeMapByIndex.splayNode(i),i.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 i=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${i}}`):e.push(`[${i}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class dt extends rr{constructor(t,i){super(t);d(this,"elements");this.elements=i}static create(t,i){if(!i)return new dt(t,mo.create());const r=mo.create();for(const s of i)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,i){this.elements.insertAfter(t,i)}moveAfter(t,i,r){this.elements.moveAfter(t,i,r)}get(t){const i=this.elements.getByIndex(t);return i==null?void 0:i.getValue()}getByID(t){const i=this.elements.getByID(t);return i==null?void 0:i.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,i){return this.elements.delete(t,i)}deleteByIndex(t,i){return this.elements.deleteByIndex(t,i)}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 i of this.elements){const r=i.getValue();if(t(r,this))return;r instanceof rr&&r.getDescendants(t)}}toJSON(){const t=[];for(const i of this)t.push(i.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let i=0;i({...g,value:g.value?{attributes:ts(g.value.getAttributes()),content:g.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,u,[h,h]]}setStyle(t,i,r,s,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,l]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),h=[],c=this.rgaTreeSplit.findBetween(l,a),u=new Map,f=[];for(const g of c){const O=g.getCreatedAt().getActorID();let y,S=0n;if(o===void 0&&s===void 0?S=Ks:o.size()>0?S=o.get(O)?o.get(O):0n:y=s.has(O)?s.get(O):Gt,g.canStyle(r,y,S)){const k=u.get(O),$=g.getCreatedAt();(!k||$.after(k))&&u.set(O,$),f.push(g)}}const p=[];for(const g of f){if(g.isRemoved())continue;const[O,y]=this.rgaTreeSplit.findIndexesFromRange(g.createPosRange());h.push({type:"style",actor:r.getActorID(),from:O,to:y,value:{attributes:ts(i)}});for(const[S,k]of Object.entries(i)){const[$]=g.getValue().setAttr(S,k,r);$!==void 0&&p.push({parent:g.getValue(),child:$})}}return[u,p,h]}indexRangeToPosRange(t,i){const r=this.rgaTreeSplit.indexToPos(t);return t===i?[r,r]:[r,this.rgaTreeSplit.indexToPos(i)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const i of this.rgaTreeSplit)i.isRemoved()||t.push(i.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 i of this.rgaTreeSplit)if(!i.isRemoved()){const r=i.getValue();t.push({attributes:ts(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 i of this.rgaTreeSplit){i.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:i});for(const r of i.getValue().getGCPairs())t.push(r)}return t}}class Xo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,i,r,s,o,a,l){return new Xo(t,i,r,s,o,a,l)}execute(t,i,r){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,l]=o.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,r);for(const h of l)t.registerGCPair(h);return{opInfos:a.map(({from:h,to:c,value:u})=>({type:"edit",from:h,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${i},${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 Uo extends Yt{constructor(t,i,r,s,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,i,r,s,o,a){return new Uo(t,i,r,s,o,a)}execute(t,i,r){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=s,[,a,l]=o.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,r);for(const h of a)t.registerGCPair(h);return{opInfos:l.map(({from:h,to:c,value:u})=>({type:"style",from:h,to:c,value:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${i},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const G1=2,J1="root",Dn="text";function Ds(n,e){let t=0;const i=n.children;for(let r=0;r0)throw new v(w.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 i=t.updateDescendantsSize();t.isRemoved||(e+=i)}return this.size+=e,this.paddedSize}get isText(){return this.type===Dn}get paddedSize(){return this.size+(this.isText?0:G1)}isAncestorOf(e){return H1(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 i=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=i;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(w.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(w.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(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(w.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const i=this.cloneElement(t);this.parent.insertAfterInternal(i,this),i.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,i._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),i.size=i._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of i._children)o.parent=i;return i}insertAfterInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1)}insertAtInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(w.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(w.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const i=this._children.indexOf(t);if(i!==-1)return i;t=t.parent}return-1}}function H1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var Qe=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(Qe||{});function sO(n,e,t,i){if(e>t)throw new v(w.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new v(w.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new v(w.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let r=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&i([s,s.isText?"Text":"Start"],h),sO(s,Math.max(0,o),Math.min(a,s.size),i),h&&i([s,"End"],h)}r+=s.paddedSize}}function oO(n,e,t=0){for(const i of n.children)oO(i,e,t+1);e(n,t)}function rh(n,e,t=0){for(const i of n._children)rh(i,e,t+1);e(n,t)}function Uc(n,e,t=!0){if(e>n.size)throw new v(w.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let i=0,r=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-r)return Uc(s,e-r,t);if(e===r)return{node:n,offset:i};if(!t&&s.paddedSize===e-r)return{node:n,offset:i+1};if(s.paddedSize>e-r)return Uc(s,e-r-1,t);r+=s.paddedSize,i+=1}return{node:n,offset:i}}function aO(n){return n.isText||n.children.length===0?n:aO(n.children[0])}function K1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(i<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 i=this.comparator(e,t.key);if(i===0)return t;i<0?t=t.left:i>0&&(t=t.right)}}putInternal(e,t,i){if(!i)return this.counter+=1,new iw(e,t,!0);const r=this.comparator(e,i.key);return r<0?i.left=this.putInternal(e,t,i.left):r>0?i.right=this.putInternal(e,t,i.right):i.value=t,this.isRed(i.right)&&!this.isRed(i.left)&&(i=this.rotateLeft(i)),this.isRed(i.left)&&this.isRed(i.left.left)&&(i=this.rotateRight(i)),this.isRed(i.left)&&this.isRed(i.right)&&this.flipColors(i),i}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 i=this.min(e.right);e.value=i.value,e.key=i.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 _t{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new _t(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:i}=e,r;return i.isText?(i.parent.children[0]===i&&t===0?r=i.parent:r=i,i=i.parent):t===0?r=i:r=i.children[t-1],_t.of(i.id,Ve.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return _t.of(Ve.of(Dt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ve.of(Dt.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(),i=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(i);if(!r||!s)throw new v(w.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${i.toTestString()})`);return!i.equals(t)&&i.getOffset()>0&&i.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 Ve{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ve(e,t)}static fromStruct(e){return Ve.of(Dt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const i=e.getCreatedAt().compare(t.getCreatedAt());return i!==0?i: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(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const i=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),i&&this.updateAncestorsSize()}cloneText(t){return new ut(Ve.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(Ve.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,i,r){const s=this.isText?this.splitText(i,this.id.getOffset()):this.splitElement(i,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,i,r){return(i?!this.getCreatedAt().after(i):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,i,r){return this.isText?!1:(i?!this.getCreatedAt().after(i):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,i){this.attrs||(this.attrs=new Vn);const r=[];for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,i));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const i of this.attrs)i.getRemovedAt()&&t.push({parent:this,child:i});return t}}function Zc(n){var t;if(n.isText){const i=n;return{type:i.type,value:i.value}}const e={type:n.type,children:n.children.map(Zc)};return n.attrs&&(e.attributes=ts((t=n.attrs)==null?void 0:t.toObject())),e}function Hu(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,i)=>t.getKey().localeCompare(i.getKey())).map(t=>{const i=JSON.parse(t.getValue());return typeof i=="string"?`${t.getKey()}="${i}"`:`${t.getKey()}="${wi(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Hu(t)).join("")}`}function hO(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(hO),size:n.size,isRemoved:n.isRemoved}}class Mt extends Vo{constructor(t,i){super(i);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new ew(t),this.nodeMapByID=new lO(Ve.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,i){return new Mt(t,i)}findFloorNode(t){const i=this.nodeMapByID.floorEntry(t);if(!(!i||!i.key.getCreatedAt().equals(t.getCreatedAt())))return i.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,i){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()),i){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const y=O.getCreatedAt().getActorID();let S,k=0n;if(o===void 0&&s===void 0?k=Ks:o.size()>0?k=o.get(y)?o.get(y):0n:S=s.has(y)?s.get(y):Gt,O.canStyle(r,S,k)&&i){const $=p.get(y),A=O.getCreatedAt();(!$||A.after($))&&p.set(y,A);const x=O.setAttrs(i,r),P=x.reduce((W,[,z])=>(z&&(W[z.getKey()]=f[z.getKey()]),W),{}),R=O.parent,X=O.prevSibling||O.parent;Object.keys(P).length>0&&u.push({type:"style",from:this.toIndex(R,X),to:this.toIndex(O,O),fromPath:this.toPath(R,X),toPath:this.toPath(O,O),actor:r.getActorID(),value:P});for(const[W]of x)W&&g.push({parent:O,child:W})}}),[p,g,u]}removeStyle(t,i,r,s,o){const[a,l]=this.findNodesAndSplitText(t[0],r),[h,c]=this.findNodesAndSplitText(t[1],r),u=[],f=new Map,p=[];return this.traverseInPosRange(a,l,h,c,([g])=>{const O=g.getCreatedAt().getActorID();let y,S=0n;if(o===void 0&&s===void 0?S=Ks:o.size()>0?S=o.get(O)?o.get(O):0n:y=s.has(O)?s.get(O):Gt,g.canStyle(r,y,S)&&i){const k=f.get(O),$=g.getCreatedAt();(!k||$.after(k))&&f.set(O,$),g.attrs||(g.attrs=new Vn);for(const P of i){const R=g.attrs.remove(P,r);for(const X of R)p.push({parent:g,child:X})}const A=g.parent,x=g.prevSibling||g.parent;u.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(A,x),to:this.toIndex(g,g),fromPath:this.toPath(A,x),toPath:this.toPath(g,g),value:i})}}),[f,p,u]}edit(t,i,r,s,o,a,l){const[h,c]=this.findNodesAndSplitText(t[0],s),[u,f]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(h,c),g=this.toPath(h,c),O=[],y=[],S=[],k=new Map;this.traverseInPosRange(h,c,u,f,([x,P],R)=>{if(P===Qe.Start&&!R)for(const H of x.children)S.push(H);const X=x.getCreatedAt().getActorID();let W,z=0n;if(l===void 0&&a===void 0?z=Ks:l.size()>0?z=l.get(X)?l.get(X):0n:W=a.has(X)?a.get(X):Gt,x.canDelete(s,W,z)||O.includes(x.parent)){const H=k.get(X),Oe=x.getCreatedAt();(!H||Oe.after(H))&&k.set(X,Oe),(P===Qe.Text||P===Qe.Start)&&O.push(x),y.push([x,P])}});const $=this.makeDeletionChanges(y,s),A=[];for(const x of O)x.remove(s),x.isRemoved&&A.push({parent:this,child:x});for(const x of S)x.removedAt||h.append(x);if(r>0){let x=0,P=h,R=c;for(;x{h.isRemoved&&(X.remove(s),A.push({parent:this,child:X})),this.nodeMapByID.put(X.id,X)}),R.isRemoved||x.push(R);if(x.length){const R=x.map(X=>Zc(X));$.length&&$[$.length-1].from===p?$[$.length-1].value=R:$.push({type:"content",from:p,to:p,fromPath:g,toPath:g,actor:s.getActorID(),value:R})}}return[$,A,k]}editT(t,i,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],i,r,s,o)}move(t,i,r){throw new v(w.ErrUnimplemented,`not implemented: ${t}, ${i}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const i=t.insPrevID,r=t.insNextID;if(i){const o=this.findFloorNode(i);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=i}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(i=>{i.getRemovedAt()&&t.push({parent:this,child:i});for(const r of i.getGCPairs())t.push(r)}),t}findPos(t,i=!0){const r=this.indexTree.findTreePos(t,i);return _t.fromTreePos(r)}pathToPosRange(t){const i=this.pathToIndex(t);return[this.findPos(i),this.findPos(i+1)]}pathToPos(t){const i=this.indexTree.pathToIndex(t);return this.findPos(i)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Hu(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(),i=(r,s=void 0,o=void 0,a=0)=>{var p,g,O,y;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=_t.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(p=r.removedAt)==null?void 0:p.toTestString(),insPrev:(g=r.insPrevID)==null?void 0:g.toTestString(),insNext:(O=r.insNextID)==null?void 0:O.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?ts((y=r.attrs)==null?void 0:y.toObject()):void 0,index:l,path:h,pos:c};for(let S=0;S0&&S===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(y,p)):r.push({type:"content",from:S,to:k,fromPath:this.toPath(O,u),toPath:this.toPath(y,p),actor:i.getActorID()}))}return r.reverse()}findRightToken([t,i]){if(i===Qe.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?Qe.Text:Qe.Start]:[t,Qe.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,Qe.End];const a=s[o+1];return[a,a.isText?Qe.Text:Qe.Start]}findLeftToken([t,i]){if(i===Qe.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?Qe.Text:Qe.End]}return[t,Qe.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,Qe.Start];const a=s[o-1];return[a,a.isText?Qe.Text:Qe.End]}}class Zo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=i,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,i,r,s,o,a,l){return new Zo(t,i,r,s,o,a,l)}execute(t,i,r){var c;const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=this.getExecutedAt(),a=s,[l,h]=a.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(u=>u.deepcopy()),this.splitLevel,o,(()=>{let u=o.getDelimiter();return this.contents!==void 0&&(u+=this.contents.length),()=>Dt.of(o.getLamport(),++u,o.getActorID())})(),this.maxCreatedAtMapByActor,r);for(const u of h)t.registerGCPair(u);return{opInfos:l.map(({from:u,to:f,value:p,splitLevel:g,fromPath:O,toPath:y})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:u,to:f,value:p,splitLevel:g,fromPath:O,toPath:y}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${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(${i},${r},${s.map(o=>Hu(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class is{constructor(e){d(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[i,r]of e){const s=this.vector.get(i),o=s&&s>r?s:r;t.set(i,o)}for(const[i,r]of this){const s=e.get(i),o=s&&s>r?s:r;t.set(i,o)}return new is(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,i]of this.vector)e.set(t,i);return new is(e)}filter(e){const t=new Map;for(const[i]of e){const r=this.vector.get(i);r!==void 0&&t.set(i,r)}return new is(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const rw=new is(new Map);class An{constructor(e,t,i,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");d(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=r,this.actor=i}static of(e,t,i,r,s){return new An(e,t,i,r,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new An(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n;let i=e.versionVector;i.size()===0&&(i=i.deepcopy(),i.set(e.actor,e.lamport));const r=this.versionVector.max(i),s=new An(this.clientSeq,t,this.actor,r);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const i=e>this.lamport?e+1n:this.lamport+1n;t.unset(nh);const r=this.versionVector.max(t);return r.set(this.actor,i),An.of(this.clientSeq,i,this.actor,r)}createTimeTicket(e){return Dt.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new An(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const sw=new An(0,0n,nh,rw);class ps{constructor({id:e,operations:t,presenceChange:i,message:r}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=i,this.message=r}static create({id:e,operations:t,presenceChange:i,message:r}){return new ps({id:e,operations:t,presenceChange:i,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,i){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,i,this.id.getVersionVector());if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?t.set(this.id.getActorID(),Wt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ke.bytesToHex(ke.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ke.bytesToHex(ke.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:i,presenceChange:r,message:s}=e;return ps.create({id:ke.bytesToChangeID(ke.hexToBytes(t)),operations:i==null?void 0:i.map(o=>ke.bytesToOperation(ke.hexToBytes(o))),presenceChange:r,message:s})}}class sh{constructor(e,t,i,r,s,o,a){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");d(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=i,this.changes=r,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,i,r,s,o,a){return new sh(e,t,i,r,s,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}getVersionVector(){return this.versionVector}}class ns{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ns(e,t)}increaseClientSeq(e){return e===0?this:new ns(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,i=Math.max(this.clientSeq,e.clientSeq);return ns.of(t,i)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const ow=new ns(0n,0);class Ti{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ti(e,t)}static fromStruct(e){return Ti.of(Dt.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 Ti(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 aw=Ti.of(Gt,0);class Jt{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Jt(e,t)}static fromStruct(e){const t=Ti.fromStruct(e.id);return Jt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ti.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 sr extends eO{constructor(t,i,r){super(i);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=r}static create(t,i){return new sr(t,i)}static createComparator(){return(t,i)=>{const r=t.getCreatedAt().compare(i.getCreatedAt());return r!==0?r:t.getOffset()>i.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 i=[];let r=e;for(;r&&r!==t;)i.push(r),r=r.getNext();return i}splitNode(e,t){if(t>e.getContentLength())throw new v(w.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const i=e.split(t);this.treeByIndex.updateWeight(i),this.insertAfter(e,i);const r=e.getInsNext();return r&&r.setInsPrev(i),i.setInsPrev(e),i}deleteNodes(e,t,i,r){if(!e.length)return[[],new Map,new Map];const[s,o]=this.filterNodes(e,t,i,r),a=new Map,l=new Map,h=this.makeChanges(o,t);for(const c of s){const u=c.getCreatedAt().getActorID();(!a.has(u)||c.getID().getCreatedAt().after(a.get(u)))&&a.set(u,c.getID().getCreatedAt()),l.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(o),[h,a,l]}filterNodes(e,t,i,r){const s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID();let u,f=0n;r===void 0&&i===void 0?f=Ks:r.size()>0?f=r.get(c)?r.get(c):0n:u=i.has(c)?i.get(c):Gt,h.canDelete(t,u,f)?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 i=[];let r,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pi=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pi||{});class pt extends Vo{constructor(t,i,r){super(r);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof i=="number"?i>Math.pow(2,31)-1||i<-Math.pow(2,31)?this.value=Y.fromNumber(i).toInt():this.value=Md(i):this.value=i.toInt();break;case 1:typeof i=="number"?this.value=Y.fromNumber(i):this.value=i;break;default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,i,r){return new pt(t,i,r)}static valueFromBytes(t,i){switch(t){case 0:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 1:return Y.fromBytesLE(Array.from(i));default:throw new v(w.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 Y?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 i=this.value.toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function i(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return i(this),i(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===$e.Long?this.value=this.value+t.getValue().toInt():this.value=Y.fromNumber(this.value+Md(t.getValue())).toInt(),this}}class ms extends Yt{constructor(t,i,r){super(t,r);d(this,"value");this.value=i}static create(t,i,r){return new ms(t,i,r)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof pt))throw new v(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=i,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()===$e.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),ge.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Nn extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,i,r,s,o,a){return new Nn(t,i,r,s,o,[],a)}static createTreeRemoveStyleOperation(t,i,r,s,o,a){return new Nn(t,i,r,s,new Map,o,a)}execute(t,i,r){const s=t.findByCreatedAt(this.getParentCreatedAt());if(!s)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(s instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=s;let a,l;if(this.attributes.size){const h={};[...this.attributes].forEach(([c,u])=>h[c]=u),[,l,a]=o.style([this.fromPos,this.toPos],h,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}else{const h=this.attributesToRemove;[,l,a]=o.removeStyle([this.fromPos,this.toPos],h,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}for(const h of l)t.registerGCPair(h);return{opInfos:a.map(({from:h,to:c,value:u,fromPath:f,toPath:p})=>({type:"tree-style",from:h,to:c,value:this.attributes.size?{attributes:u}:{attributesToRemove:u},fromPath:f,toPath:p,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${i},${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 lw(n){const e=new Gu,t=e.data;for(const[i,r]of Object.entries(n))t[i]=JSON.stringify(r);return e}function hw(n){if(n.type===cr.Put)return new fo({type:Dr.PUT,presence:lw(n.presence)});if(n.type===cr.Clear)return new fo({type:Dr.CLEAR});throw new v(w.ErrUnimplemented,"unimplemented type")}function cw(n){return new Ym({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function cO(n){return new th({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:cf(n.getActorID()),versionVector:Ku(n.getVersionVector())})}function L(n){if(n)return new M({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:cf(n.getActorID())})}function Ku(n){if(!n)return;const e=new ih;for(const[t,i]of n)e.vector[t]=BigInt(i.toString());return e}function uO(n){switch(n){case $e.Null:return F.NULL;case $e.Boolean:return F.BOOLEAN;case $e.Integer:return F.INTEGER;case $e.Long:return F.LONG;case $e.Double:return F.DOUBLE;case $e.String:return F.STRING;case $e.Bytes:return F.BYTES;case $e.Date:return F.DATE;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function fO(n){switch(n){case Pi.IntegerCnt:return F.INTEGER_CNT;case Pi.LongCnt:return F.LONG_CNT;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function Ih(n){if(n instanceof nt)return new mt({type:F.JSON_OBJECT,createdAt:L(n.getCreatedAt()),value:TO(n)});if(n instanceof dt)return new mt({type:F.JSON_ARRAY,createdAt:L(n.getCreatedAt()),value:Xw(n)});if(n instanceof qt)return new mt({type:F.TEXT,createdAt:L(n.getCreatedAt())});if(n instanceof ge)return new mt({type:uO(n.getType()),createdAt:L(n.getCreatedAt()),value:n.toBytes()});if(n instanceof pt)return new mt({type:fO(n.getType()),createdAt:L(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Mt)return new mt({type:F.TREE,createdAt:L(n.getCreatedAt()),value:Zw(n)});throw new v(w.ErrUnimplemented,"unimplemented element")}function uw(n){return new uo({createdAt:L(n.getCreatedAt()),offset:n.getOffset()})}function ia(n){return new Mn({createdAt:L(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function na(n){return new Er({parentId:eo(n.getParentID()),leftSiblingId:eo(n.getLeftSiblingID())})}function eo(n){return new nr({createdAt:L(n.getCreatedAt()),offset:n.getOffset()})}function dO(n){const e=new Fu;if(n instanceof Nr){const t=n,i=new nl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.key=t.getKey(),i.value=Ih(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="set",e.body.value=i}else if(n instanceof Lo){const t=n,i=new rl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.prevCreatedAt=L(t.getPrevCreatedAt()),i.value=Ih(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="add",e.body.value=i}else if(n instanceof Kn){const t=n,i=new sl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.prevCreatedAt=L(t.getPrevCreatedAt()),i.createdAt=L(t.getCreatedAt()),i.executedAt=L(t.getExecutedAt()),e.body.case="move",e.body.value=i}else if(n instanceof ur){const t=n,i=new ol;i.parentCreatedAt=L(t.getParentCreatedAt()),i.createdAt=L(t.getCreatedAt()),i.executedAt=L(t.getExecutedAt()),e.body.case="remove",e.body.value=i}else if(n instanceof Xo){const t=n,i=new al;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=ia(t.getFromPos()),i.to=ia(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=L(a);i.content=t.getContent();const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=L(t.getExecutedAt()),e.body.case="edit",e.body.value=i}else if(n instanceof Uo){const t=n,i=new ll;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=ia(t.getFromPos()),i.to=ia(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=L(a);const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=L(t.getExecutedAt()),e.body.case="style",e.body.value=i}else if(n instanceof ms){const t=n,i=new hl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.value=Ih(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="increase",e.body.value=i}else if(n instanceof Zo){const t=n,i=new cl,r=i.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=L(o);i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=na(t.getFromPos()),i.to=na(t.getToPos()),i.contents=yw(t.getContents()),i.splitLevel=t.getSplitLevel(),i.executedAt=L(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=i}else if(n instanceof Nn){const t=n,i=new ul;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=na(t.getFromPos()),i.to=na(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=L(a);const s=t.getAttributesToRemove();if(s.length>0)i.attributesToRemove=s;else{const o=i.attributes;for(const[a,l]of t.getAttributes())o[a]=l}i.executedAt=L(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=i}else throw new v(w.ErrUnimplemented,"unimplemented operation");return e}function fw(n){const e=[];for(const t of n)e.push(dO(t));return e}function dw(n){const e=new _m({id:cO(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=fw(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=hw(n.getPresenceChange())),e}function pw(n){const e=[];for(const t of n)e.push(dw(t));return e}function gw(n){const e=[];for(const t of n)e.push(new Gm({key:t.getStrKey(),element:tf(t.getValue())}));return e}function mw(n){const e=[];for(const t of n)e.push(new yl({element:tf(t.getValue())}));return e}function Ow(n){const e=[];for(const t of n){const i=new Jm;i.id=uw(t.getID()),i.value=t.getValue().getContent(),i.removedAt=L(t.getRemovedAt());const r=i.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new us;a.value=o.getValue(),a.updatedAt=L(o.getUpdatedAt()),r[o.getKey()]=a}e.push(i)}return e}function yw(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new bl({content:ef(t)}));return e}function bw(n){const e={};for(const t of n)e[t.getKey()]=new us({value:t.getValue(),updatedAt:L(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ef(n){if(!n)return[];const e=[];return rh(n,(t,i)=>{const r=new _u({id:eo(t.id),type:t.type,removedAt:L(t.removedAt),depth:i});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=eo(t.insPrevID)),t.insNextID&&(r.insNextId=eo(t.insNextID)),t.attrs&&(r.attributes=bw(t.attrs)),e.push(r)}),e}function Sw(n){const e=new rt;return e.body.case="jsonObject",e.body.value=new fl({nodes:gw(n.getRHT()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function pO(n){const e=new rt;return e.body.case="jsonArray",e.body.value=new dl({nodes:mw(n.getElements()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function ww(n){const e=new rt;return e.body.case="primitive",e.body.value=new pl({type:uO(n.getType()),value:n.toBytes(),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function vw(n){const e=new rt;return e.body.case="text",e.body.value=new gl({nodes:Ow(n.getRGATreeSplit()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function kw(n){const e=new rt;return e.body.case="counter",e.body.value=new ml({type:fO(n.getType()),value:n.toBytes(),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function gO(n){const e=new rt;return e.body.case="tree",e.body.value=new Ol({nodes:ef(n.getRoot()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function tf(n){if(n instanceof nt)return Sw(n);if(n instanceof dt)return pO(n);if(n instanceof ge)return ww(n);if(n instanceof qt)return vw(n);if(n instanceof pt)return kw(n);if(n instanceof Mt)return gO(n);throw new v(w.ErrUnimplemented,"unimplemented element")}function xw(n){return new Wn({documentKey:n.getDocumentKey(),checkpoint:cw(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:pw(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Ku(n.getVersionVector()),minSyncedTicket:L(n.getMinSyncedTicket())})}function js(n){if(!(n instanceof ue))return{};const e=n.findDetails(Z1);for(const t of e)return t.metadata;return{}}function Wr(n){return js(n).code??""}function mO(n){return An.of(n.clientSeq,BigInt(n.lamport),lf(n.actorId),nf(n.versionVector),BigInt(n.serverSeq))}function nf(n){if(!n)return;const e=new is;return Object.entries(n.vector).forEach(([t,i])=>{e.set(t,BigInt(i.toString()))}),e}function U(n){if(n)return Dt.of(BigInt(n.lamport),n.delimiter,lf(n.actorId))}function rf(n){const e={};return Object.entries(n.data).forEach(([t,i])=>{e[t]=JSON.parse(i)}),e}function Tw(n){const e=n.type;if(e===Dr.PUT){const t=rf(n.presence);return{type:cr.Put,presence:t}}if(e===Dr.CLEAR)return{type:cr.Clear};throw new v(w.ErrInvalidType,`unsupported type: ${e}`)}function Qw(n){const e=new Map;return Object.entries(n).forEach(([t,i])=>{e.set(t,rf(i))}),e}function OO(n){switch(n){case F.NULL:return $e.Null;case F.BOOLEAN:return $e.Boolean;case F.INTEGER:return $e.Integer;case F.LONG:return $e.Long;case F.DOUBLE:return $e.Double;case F.STRING:return $e.String;case F.BYTES:return $e.Bytes;case F.DATE:return $e.Date}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function vl(n){switch(n){case F.INTEGER_CNT:return Pi.IntegerCnt;case F.LONG_CNT:return Pi.LongCnt}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function Rh(n){switch(n.type){case F.JSON_OBJECT:return n.value?xO(n.value):nt.create(U(n.createdAt));case F.JSON_ARRAY:return n.value?Lw(n.value):dt.create(U(n.createdAt));case F.TEXT:return qt.create(gs.create(),U(n.createdAt));case F.TREE:return Uw(n.value);case F.NULL:case F.BOOLEAN:case F.INTEGER:case F.LONG:case F.DOUBLE:case F.STRING:case F.BYTES:case F.DATE:return ge.of(ge.valueFromBytes(OO(n.type),n.value),U(n.createdAt));case F.INTEGER_CNT:case F.LONG_CNT:return pt.create(vl(n.type),pt.valueFromBytes(vl(n.type),n.value),U(n.createdAt))}}function ra(n){return Jt.of(Ti.of(U(n.createdAt),n.offset),n.relativeOffset)}function yO(n){return Ti.of(U(n.createdAt),n.offset)}function Pw(n){const e=Oo.create(n.value);Object.entries(n.attributes).forEach(([i,r])=>{e.setAttr(i,r.value,U(r.updatedAt))});const t=sr.create(yO(n.id),e);return t.remove(U(n.removedAt)),t}function jr(n){return _t.of(to(n.parentId),to(n.leftSiblingId))}function to(n){return Ve.of(U(n.createdAt),n.offset)}function Aw(n){if(!n.length)return;const e=[];return n.forEach(t=>{const i=sf(t.content);e.push(i)}),e}function sf(n){if(n.length===0)return;const e=[];for(const r of n)e.push(Cw(r));const t=e[e.length-1],i=new Map;i.set(n[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)i.get(n[r].depth-1).prepend(e[r]),i.set(n[r].depth,e[r]);return t.updateDescendantsSize(),Mt.create(t,Gt).getRoot()}function $w(n){const e=Vn.create();for(const[t,i]of Object.entries(n))e.setInternal(t,i.value,U(i.updatedAt),i.isRemoved);return e}function Cw(n){const e=to(n.id),t=ut.create(e,n.type),i=Object.entries(n.attributes);return t.isText?t.value=n.value:i.length&&(t.attrs=$w(n.attributes)),n.insPrevId&&(t.insPrevID=to(n.insPrevId)),n.insNextId&&(t.insNextID=to(n.insNextId)),t.removedAt=U(n.removedAt),t}function bO(n){if(n.body.case==="set"){const e=n.body.value;return Nr.create(e.key,Rh(e.value),U(e.parentCreatedAt),U(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Lo.create(U(e.parentCreatedAt),U(e.prevCreatedAt),Rh(e.value),U(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Kn.create(U(e.parentCreatedAt),U(e.prevCreatedAt),U(e.createdAt),U(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return ur.create(U(e.parentCreatedAt),U(e.createdAt),U(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,U(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Xo.create(U(e.parentCreatedAt),ra(e.from),ra(e.to),t,e.content,i,U(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,U(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Uo.create(U(e.parentCreatedAt),ra(e.from),ra(e.to),t,i,U(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ms.create(U(e.parentCreatedAt),Rh(e.value),U(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([i,r])=>{t.set(i,U(r))}),Zo.create(U(e.parentCreatedAt),jr(e.from),jr(e.to),Aw(e.contents),e.splitLevel,t,U(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,i=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,U(o))}),(i==null?void 0:i.length)>0?Nn.createTreeRemoveStyleOperation(U(e.parentCreatedAt),jr(e.from),jr(e.to),r,i,U(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),Nn.create(U(e.parentCreatedAt),jr(e.from),jr(e.to),r,t,U(e.executedAt)))}else throw new v(w.ErrUnimplemented,"unimplemented operation")}}function Iw(n){const e=[];for(const t of n){const i=bO(t);i&&e.push(i)}return e}function SO(n){const e=[];for(const t of n)e.push(ps.create({id:mO(t.id),operations:Iw(t.operations),presenceChange:t.presenceChange?Tw(t.presenceChange):void 0,message:t.message}));return e}function Rw(n){return ns.of(BigInt(n.serverSeq),n.clientSeq)}function Ew(n){return sh.create(n.documentKey,Rw(n.checkpoint),n.isRemoved,SO(n.changes),nf(n.versionVector),n.snapshot,U(n.minSyncedTicket))}function wO(n){const e=new po;for(const i of n.nodes){const r=of(i.element);e.set(i.key,r,r.getPositionedAt())}const t=new nt(U(n.createdAt),e);return t.setMovedAt(U(n.movedAt)),t.setRemovedAt(U(n.removedAt)),t}function vO(n){const e=new mo;for(const i of n.nodes)e.insert(of(i.element));const t=new dt(U(n.createdAt),e);return t.setMovedAt(U(n.movedAt)),t.setRemovedAt(U(n.removedAt)),t}function Dw(n){const e=ge.of(ge.valueFromBytes(OO(n.type),n.value),U(n.createdAt));return e.setMovedAt(U(n.movedAt)),e.setRemovedAt(U(n.removedAt)),e}function Nw(n){const e=new gs;let t=e.getHead();for(const r of n.nodes){const s=e.insertAfter(t,Pw(r));r.insPrevId&&s.setInsPrev(e.findNode(yO(r.insPrevId))),t=s}const i=new qt(e,U(n.createdAt));return i.setMovedAt(U(n.movedAt)),i.setRemovedAt(U(n.removedAt)),i}function Bw(n){const e=pt.create(vl(n.type),pt.valueFromBytes(vl(n.type),n.value),U(n.createdAt));return e.setMovedAt(U(n.movedAt)),e.setRemovedAt(U(n.removedAt)),e}function kO(n){const e=sf(n.nodes);return Mt.create(e,U(n.createdAt))}function of(n){if(n.body.case==="jsonObject")return wO(n.body.value);if(n.body.case==="jsonArray")return vO(n.body.value);if(n.body.case==="primitive")return Dw(n.body.value);if(n.body.case==="text")return Nw(n.body.value);if(n.body.case==="counter")return Bw(n.body.value);if(n.body.case==="tree")return kO(n.body.value);throw new v(w.ErrUnimplemented,"unimplemented element")}function qw(n){if(!n)return{root:nt.create(Gt),presences:new Map};const e=yc.fromBinary(n);return{root:of(e.root),presences:Qw(e.presences)}}function Mw(n){const e=Ku(n);return af(e.toBinary())}function Vw(n){const e=hf(n),t=ih.fromBinary(e);return nf(t)}function xO(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return wO(e.body.value)}function TO(n){return tf(n).toBinary()}function Lw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return vO(e.body.value)}function Xw(n){return pO(n).toBinary()}function Uw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return kO(e.body.value)}function Zw(n){return gO(n).toBinary()}function af(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function lf(n){return af(n)}function hf(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function cf(n){return hf(n)}function Ww(n){const e=th.fromBinary(n);return mO(e)}function jw(n){const e=Fu.fromBinary(n);return bO(e)}const ke={fromPresence:rf,toChangePack:xw,fromChangePack:Ew,fromChanges:SO,toTreeNodes:ef,fromTreeNodes:sf,objectToBytes:TO,bytesToObject:xO,bytesToSnapshot:qw,bytesToHex:af,hexToBytes:hf,toHexString:lf,toUint8Array:cf,toOperation:dO,toChangeID:cO,PbChangeID:th,bytesToChangeID:Ww,bytesToOperation:jw,versionVectorToHex:Mw,hexToVersionVector:Vw};var Ge=(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))(Ge||{});let vr=3;function QO(n){vr=n}const Z={trivial:(...n)=>{vr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{vr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{vr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{vr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{vr>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=>vr<=n};function PO(){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 zw{constructor(e,t,i,r,s){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=i,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===La.RealtimeSyncOff?!1:this.syncMode===La.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==La.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 Eh=()=>{};class Fw{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,i){let r;if(!e)throw new v(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:i},r.next===void 0&&(r.next=Eh),r.error===void 0&&(r.error=Eh),r.complete===void 0&&(r.complete=Eh);const s=PO(),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){Z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(i=>i.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Yr{constructor(e,t,i,r){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=Km,this.root=t,this.operations=[],this.previousPresence=Wt(i),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,i,r){return new Yr(e,t,i,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 ps.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 i of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(i):this.reversePresenceKeys.delete(i)}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 yo{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 qt||t instanceof Mt)for(const i of t.getGCPairs())this.registerGCPair(i);return!1})}static create(){return new yo(nt.create(Gt))}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 i=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(w.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);i.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return i.unshift("$"),i}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof rr&&e.getDescendants((i,r)=>(this.registerElement(i,r),!1))}deregisterElement(e){let t=0;const i=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return i(e),e instanceof rr&&e.getDescendants(r=>(i(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 i=this.elementPairMapByCreatedAt.get(t);i.element instanceof rr&&i.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 yo(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const i of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(i),s=r.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,i]of this.gcPairMap){const r=i.child.getRemovedAt();r&&(e!=null&&e.afterOrEqual(r))&&(i.parent.purge(i.child),this.gcPairMap.delete(i.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function AO(n,e){const t=new bo(n);return new Proxy(e,t.getHandlers())}class bo{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,i,r)=>(Z.isEnabled(Ge.Trivial)&&Z.trivial(`obj[${i}]=${JSON.stringify(r)}`),bo.setInternal(e,t,i,r),!0),get:(t,i)=>(Z.isEnabled(Ge.Trivial)&&Z.trivial(`obj[${i}]`),i==="getID"?()=>t.getCreatedAt():i==="toJSON"||i==="toString"?()=>t.toJSON():i==="toJS"?()=>t.toJS():i==="toJSForTest"?()=>t.toJSForTest():kr(e,t.get(i))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,i)=>(Z.isEnabled(Ge.Trivial)&&Z.trivial(`obj[${i}]`),bo.deleteInternal(e,t,i),!0)}}static setInternal(e,t,i,r){if(i.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=kl(e,r,s),a=t.set(i,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nr.create(i,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const i={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=kl(e,s,o);i[r]=a}return i}static deleteInternal(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByKey(i,r);s&&(e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function Gw(n,e){const t=new ye(n,e);return new Proxy(e,t.getHandlers())}function Jw(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Yw(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class ye{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(i,r,s)=>r==="getID"?()=>i.getCreatedAt():r==="getElementByID"?o=>{const a=i.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=i.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,i.getLast()):r==="deleteByID"?o=>{const a=ye.deleteInternalByID(e,i,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=ye.insertAfterInternal(e,i,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=ye.insertBeforeInternal(e,i,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{ye.moveBeforeInternal(e,i,o,a)}:r==="moveAfter"?(o,a)=>{ye.moveAfterInternal(e,i,o,a)}:r==="moveFront"?o=>{ye.moveFrontInternal(e,i,o)}:r==="moveLast"?o=>{ye.moveLastInternal(e,i,o)}:Jw(r)?kr(e,i.get(Number(r))):r==="push"?o=>ye.pushInternal(e,i,o):r==="splice"?(o,a,...l)=>ye.splice(e,i,o,a,...l):r==="length"?i.length:typeof r=="symbol"&&r===Symbol.iterator?ye.iteratorInternal.bind(this,e,i):r==="includes"?(o,a)=>ye.includes(e,i,o,a):r==="indexOf"?(o,a)=>ye.indexOf(e,i,o,a):r==="lastIndexOf"?(o,a)=>ye.lastIndexOf(e,i,o,a):r==="toJSForTest"?()=>i.toJSForTest():r==="toTestString"?()=>ye.toTestString(i):typeof r=="string"&&Yw(r)?(...o)=>{const a=Array.from(i).map(l=>kr(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(i,r,s),deleteProperty:(i,r)=>(Z.isEnabled(Ge.Trivial)&&Z.trivial(`array[${r}]`),ye.deleteInternalByIndex(e,i,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const i of t)yield _n(e,i)}static buildArrayElements(e,t){const i=[];for(const r of t){const s=e.issueTimeTicket(),o=kl(e,r,s);i.push(o)}return i}static pushInternal(e,t,i){return ye.insertAfterInternal(e,t,t.getLastCreatedAt(),i),t.length}static moveBeforeInternal(e,t,i,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(i);t.moveAfter(o,r,s),e.push(Kn.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,i,r){const s=e.issueTimeTicket();t.moveAfter(i,r,s),e.push(Kn.create(t.getCreatedAt(),i,r,s))}static moveFrontInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),i,r),e.push(Kn.create(t.getCreatedAt(),s.getCreatedAt(),i,r))}static moveLastInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,i,r),e.push(Kn.create(t.getCreatedAt(),s,i,r))}static insertAfterInternal(e,t,i,r){const s=e.issueTimeTicket(),o=kl(e,r,s);return t.insertAfter(i,o),e.registerElement(o,t),e.push(Lo.create(t.getCreatedAt(),i,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,i,r){return ye.insertAfterInternal(e,t,t.getPrevCreatedAt(i),r)}static deleteInternalByIndex(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByIndex(i,r);if(s)return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,i){const r=e.issueTimeTicket(),s=t.delete(i,r);return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,i,r,...s){const o=t.length,a=i>=0?Math.min(i,o):Math.max(o+i,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(ge.isSupport(i))return Array.from(t).map(h=>kr(e,h)).includes(i,o);for(let l=o;l=s)return-1;if(ge.isSupport(i))return Array.from(t).map(h=>kr(e,h)).indexOf(i,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(ge.isSupport(i))return Array.from(t).map(h=>kr(e,h)).lastIndexOf(i,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===i.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let oh=class{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,i,r){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);Z.isEnabled(Ge.Debug)&&Z.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${i}`);const o=r?fs(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,i,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new Xo(this.text.getCreatedAt(),s[0],s[1],l,i,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,i){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);Z.isEnabled(Ge.Debug)&&Z.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(i)}`);const s=fs(i),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 Uo(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(w.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(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Jt.fromStruct(e[0]),Jt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(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 v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class ah{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 v(w.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),i=ge.of(e,t);if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`);return this.counter.increase(i),this.context.push(ms.create(this.counter.getCreatedAt(),i,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function uf(n,e,t){const{type:i}=n,r=t.issueTimeTicket();if(i===Dn){$O(n);const{value:s}=n,o=ut.create(Ve.of(r,0),i,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Hm(o)){const h=fs(o);a=new Vn;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(Ve.of(r,0),i,void 0,a);e.append(l);for(const h of s)uf(h,l,t)}}function Hw(n,e){const{type:t}=e,i=n.issueTimeTicket();let r;if(e.type===Dn){const{value:s}=e;r=ut.create(Ve.of(i,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Hm(o)){const l=fs(o);a=new Vn;for(const[h,c]of Object.entries(l))a.set(h,c,i)}r=ut.create(Ve.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)uf(l,r,n)}return r}function $O(n){if(!n.value.length)throw new v(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function Vd(n){if(!n.length)return!0;if(n[0].type===Dn)for(const t of n){const{type:i}=t;if(i!==Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together");$O(t)}else for(const t of n){const{type:i}=t;if(i===Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let lh=class{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 ut.create(Ve.of(e.issueTimeTicket(),0),J1);const t=ut.create(Ve.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const i of this.initialRoot.children)uf(i,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const[i,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([i,r],o,s);this.context.push(Nn.create(this.tree.getCreatedAt(),i,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.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=i?fs(i):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(Nn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.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],i,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Nn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,i,o))}editInternal(e,t,i,r=0){var h;if(i.length!==0&&i[0]&&(Vd(i),i[0].type!==Dn))for(const c of i){const{children:u=[]}=c;Vd(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=i[0])==null?void 0:h.type)===Dn){let c="";for(const u of i){const{value:f}=u;c+=f}o.push(ut.create(Ve.of(this.context.issueTimeTicket(),0),Dn,c))}else o=i.map(c=>c&&Hw(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(Zo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulkByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i,r)}edit(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.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,i?[i]:[],r)}editBulk(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.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,i,r)}toXML(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],i=this.tree.indexRangeToPosRange(t);return[i[0].toStruct(),i[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Ld(n,e){return AO(n,e)}function _n(n,e){if(e){if(e instanceof ge)return e;if(e instanceof nt)return AO(n,e);if(e instanceof dt)return Gw(n,e);if(e instanceof qt)return new oh(n,e);if(e instanceof pt){const t=new ah(Pi.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Mt){const t=new lh;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function kr(n,e){const t=_n(n,e);return t instanceof ge?t.getValue():t}function kl(n,e,t){let i;if(ge.isSupport(e))i=ge.of(e,t);else if(Array.isArray(e))i=dt.create(t,ye.buildArrayElements(n,e));else if(typeof e=="object")e instanceof oh?(i=qt.create(gs.create(),t),e.initialize(n,i)):e instanceof ah?(i=pt.create(e.getValueType(),e.getValue(),t),e.initialize(n,i)):e instanceof lh?(i=Mt.create(e.buildRoot(n),t),e.initialize(n,i)):i=nt.create(t,bo.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return i}const Xd=50;class Kw{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Xd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Xd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const ev="yorkie-devtools-panel",tv="yorkie-devtools-sdk";let Fr="disconnected";const Ud=new Map,Va=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Va);function sa(n,e){(e!=null&&e.force||Fr!=="disconnected")&&window.postMessage({source:tv,...n},"*")}function iv(n){if(!n.isEnableDevtools()||typeof window>"u"||Ud.has(n.getKey()))return;Va.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(i=>i.type!==Re.StatusChanged&&i.type!==Re.Snapshot&&i.type!==Re.LocalChange&&i.type!==Re.RemoteChange&&i.type!==Re.Initialized&&i.type!==Re.Watched&&i.type!==Re.Unwatched&&i.type!==Re.PresenceChanged)||(Va.get(n.getKey()).push(t),Fr==="synced"&&sa({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Ud.set(n.getKey(),[e]),sa({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==ev)return;switch(t.data.msg){case"devtools::connect":if(Fr!=="disconnected")break;Fr="connected",sa({msg:"doc::available",docKey:n.getKey()}),Z.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Fr="disconnected",Z.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Fr="synced",sa({msg:"doc::sync::full",docKey:n.getKey(),events:Va.get(n.getKey())}),Z.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Gn=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Gn||{}),Re=(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.AuthError="auth-error",n))(Re||{}),So=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(So||{}),Wc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Wc||{});class CO{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=yo.create(),this.changeID=sw,this.checkpoint=ow,this.localChanges=[],this.eventStream=_w(i=>{this.eventStreamObserver=i}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Kw,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},iv(this)}update(e,t){if(this.getStatus()==="removed")throw new v(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const i=this.changeID.getActorID(),r=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(i)||{},t);try{const s=Ld(r,this.clone.root.getObject());this.presences.has(i)||this.clone.presences.set(i,{}),this.isUpdating=!0,e(s,new Ch(r,this.clone.presences.get(i)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){Z.isEnabled(Ge.Trivial)&&Z.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,se.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:se.Local,value:{message:s.getMessage()||"",operations:o,actor:i,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:se.Local,value:{clientID:i,presence:this.getPresence(i)}}),this.publish(h),Z.isEnabled(Ge.Trivial)&&Z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,i,r){if(typeof e=="string"){if(typeof t!="function")throw new v(w.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)},i,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)},i,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)},i,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},i,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},i,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},i,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},i)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},i)}if(e==="auth-error"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="auth-error"&&a(h)},i)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,i,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}})}},i,r)}if(typeof e=="function"){const s=e,o=t,a=i;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(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const i=e.split(".");return t.split(".").every((s,o)=>s===i[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),se.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),Z.isEnabled(Ge.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:Wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return sh.create(this.key,t,!1,e,this.getVersionVector())}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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ld(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,i,r=-1){const{root:s,presences:o}=ke.bytesToSnapshot(i);this.root=new yo(s),this.presences=o,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(r),this.applyChanges(this.localChanges,se.Local),this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?ke.bytesToHex(i):void 0,snapshotVector:ke.versionVectorToHex(t)}}])}applyChanges(e,t){Z.isEnabled(Ge.Debug)&&Z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Z.isEnabled(Ge.Trivial)&&Z.trivial(e.map(i=>`${i.getID().toTestString()} ${i.toTestString()}`).join(` -`));for(const i of e)this.applyChange(i,t);Z.isEnabled(Ge.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 i=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case cr.Put:i.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:r,presence:o.presence}});break;case cr.Clear:i.push({type:"unwatched",source:se.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.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;i.push(t===se.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})}i.length>0&&this.publish(i)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,i=new Set;for(const r of t)r!==this.changeID.getActorID()&&i.add(r);this.setOnlineClients(i),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:i}=e.body.value,r=[];if(t===Rr.DOCUMENT_WATCHED){if(this.onlineClients.has(i)&&this.hasPresence(i))return;this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}})}else if(t===Rr.DOCUMENT_UNWATCHED){const s=this.getPresence(i);this.removeOnlineClient(i),s&&r.push({type:"unwatched",source:se.Remote,value:{clientID:i,presence:s}})}else if(t===Rr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:i,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(nh),this.publish([{source:e==="removed"?se.Remote:se.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:i,snapshotVector:r}=e.value;if(!t)return;this.applySnapshot(BigInt(i),ke.hexToVersionVector(r),ke.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ps.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:i,presence:r}of e.value)t.add(i),this.presences.set(i,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:i}=e.value;this.addOnlineClient(t),this.presences.set(t,i);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:i}=e.value;this.presences.set(t,i)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(w.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let i=this.getRoot();for(const r of t)if(i=i[r],i===void 0)return;return i}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 t=this.presences.get(e);return t?Wt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Wt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Wt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Wt(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,i)=>t.clientID>i.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const i=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(i)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ch(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ch(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,i){const r={type:"local-broadcast",value:{topic:e,payload:t},options:i};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function nv(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const rv="yorkie-js-sdk",sv="0.5.6",ov="Yorkie JS SDK",av="./src/yorkie.ts",lv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},hv=["dist"],cv={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"},uv={node:">=18.0.0",npm:">=7.1.0"},fv={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},dv={name:"hackerwins",email:"susukang98@gmail.com"},pv="Apache-2.0",gv={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},mv="https://github.com/yorkie-team/yorkie-js-sdk#readme",Ov={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},yv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Zd={name:rv,version:sv,description:ov,main:av,publishConfig:lv,files:hv,scripts:cv,engines:uv,repository:fv,author:dv,license:pv,bugs:gv,homepage:mv,devDependencies:Ov,dependencies:yv};function bv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Zd.name+"/"+Zd.version),await n(e))}const Sv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var La=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(La||{});const oa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Dh={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class IO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"authTokenInjector");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"setAuthToken");d(this,"taskQueue");d(this,"processing",!1);d(this,"keepalive",!1);t=t||oa,this.key=t.key?t.key:PO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??oa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??oa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??oa.retrySyncLoopDelay;const{authInterceptor:i,setToken:r}=nv(this.apiKey);this.setAuthToken=r,this.rpcClient=b1(U1,X1({baseUrl:e,interceptors:[i,bv()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(async e=>{throw Z.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),Z.info(`[DC] c"${this.getKey()}" deactivated`)}catch(i){throw Z.error(`[DC] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}};if(e.keepalive){this.keepalive=!0;const i=t();return this.keepalive=!1,i}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new v(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const i=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:ke.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ke.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Gn.Removed)return e;e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new zw(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),Z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(h=>{for(const[c,u]of Object.entries(l))if(!a.has(c)){const f=c;h[f]=u}})}return e}).catch(async s=>{throw Z.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:i.docID,changePack:ke.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=ke.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),Z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async r=>{throw Z.error(`[DD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=i.syncMode;return r===t?e:(i.changeSyncMode(t),t==="manual"?(i.cancelWatchStream(),e):(t==="realtime"&&(i.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async i=>{throw Z.error(`[SY] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}return this.enqueueTask(async()=>{const t=[];for(const[,i]of this.attachmentMap)t.push(this.syncInternal(i,i.syncMode));return Promise.all(t).catch(async i=>{throw Z.error(`[SY] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i})})}remove(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const i=ke.toChangePack(e.createChangePack());return i.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:i},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=ke.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),Z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async r=>{throw Z.error(`[RD] c:"${this.getKey()}" err :`,r),await 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,i,r){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);if(!Sv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Dh.maxRetries,a=Dh.maxBackoff;let l=0;const h=u=>Math.min(Dh.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(i))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{Z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async u=>{if(Z.error(`[BC] c:"${this.getKey()}" err:`,u),await this.handleConnectError(u))if(u instanceof ue&&Wr(u)===w.ErrUnauthenticated&&s.doc.publish([{type:Re.AuthError,value:{reason:js(u).reason,method:"Broadcast"}}]),lc(),h(l-1)),Z.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw Z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){Z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,i]of this.attachmentMap)i.needRealtimeSync()&&(i.remoteChangeEventReceived=!1,t.push(this.syncInternal(i,i.syncMode).catch(async r=>{throw r instanceof ue&&Wr(r)===w.ErrUnauthenticated&&i.doc.publish([{type:Re.AuthError,value:{reason:js(r).reason,method:"PushPull"}}]),r})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async i=>{Z.error(`[SL] c:"${this.getKey()}" sync failed:`,i),await this.handleConnectError(i)?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 v(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(i=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(w.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:Re.ConnectionChanged,value:So.Connected}]),Z.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:Re.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Re.ConnectionChanged,value:So.Disconnected}]),Z.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(h)?(h instanceof ue&&Wr(h)===w.ErrUnauthenticated&&t.doc.publish([{type:Re.AuthError,value:{reason:js(h).reason,method:"WatchDocuments"}}]),i()):this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Rr.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:i,docID:r}=e,s=i.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:ke.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=ke.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:Re.SyncStatusChanged,value:Wc.Synced}]),i.getStatus()===Gn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return Z.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(async o=>{throw i.publish([{type:Re.SyncStatusChanged,value:Wc.SyncFailed}]),Z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof ue))return!1;if(e.code===ne.Canceled||e.code===ne.Unknown||e.code===ne.ResourceExhausted||e.code===ne.Unavailable)return!0;if(Wr(e)===w.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(js(e).reason);this.setAuthToken(t)}return!0}return(Wr(e)===w.ErrClientNotActivated||Wr(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(e){return new Promise((t,i)=>{this.taskQueue.push(()=>e().then(t).catch(i)),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 Nh={Client:IO,Document:CO,Primitive:ge,Text:oh,Counter:ah,Tree:lh,LogLevel:Ge,setLogLevel:QO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:IO,Document:CO,Primitive:ge,Text:oh,Counter:ah,Tree:lh,LogLevel:Ge,setLogLevel:QO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt});class ee{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,i){[e,t]=Os(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ui.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Os(this,e,t);let i=[];return this.decompose(e,t,i,0),ui.from(i,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),i=this.length-this.scanIdentical(e,-1),r=new io(this),s=new io(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>=i)return!0}}iter(e=1){return new io(this,e)}iterRange(e,t=this.length){return new RO(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new EO(i)}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]?ee.empty:e.length<=32?new ve(e):ui.from(ve.split(e,[]))}}class ve extends ee{constructor(e,t=wv(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?i:a)>=e)return new vv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ve(Wd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=Xa(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new ve(a,o.length+s.length));else{let l=a.length>>1;i.push(new ve(a.slice(0,l)),new ve(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ve))return super.replace(e,t,i);[e,t]=Os(this,e,t);let r=Xa(this.text,Xa(i.text,Wd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ve(r,s):ui.from(ve.split(r,[]),s)}sliceString(e,t=this.length,i=` +`));for(const i of e)this.applyChange(i,t);Z.isEnabled(Ge.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 i=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case cr.Put:i.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:r,presence:o.presence}});break;case cr.Clear:i.push({type:"unwatched",source:se.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.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;i.push(t===se.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})}i.length>0&&this.publish(i)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,i=new Set;for(const r of t)r!==this.changeID.getActorID()&&i.add(r);this.setOnlineClients(i),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:i}=e.body.value,r=[];if(t===Rr.DOCUMENT_WATCHED){if(this.onlineClients.has(i)&&this.hasPresence(i))return;this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}})}else if(t===Rr.DOCUMENT_UNWATCHED){const s=this.getPresence(i);this.removeOnlineClient(i),s&&r.push({type:"unwatched",source:se.Remote,value:{clientID:i,presence:s}})}else if(t===Rr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:i,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(nh),this.publish([{source:e==="removed"?se.Remote:se.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:i,snapshotVector:r}=e.value;if(!t)return;this.applySnapshot(BigInt(i),ke.hexToVersionVector(r),ke.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ps.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:i,presence:r}of e.value)t.add(i),this.presences.set(i,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:i}=e.value;this.addOnlineClient(t),this.presences.set(t,i);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:i}=e.value;this.presences.set(t,i)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(w.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let i=this.getRoot();for(const r of t)if(i=i[r],i===void 0)return;return i}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 t=this.presences.get(e);return t?Wt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Wt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Wt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Wt(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,i)=>t.clientID>i.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const i=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(i)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ch(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ch(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,i){const r={type:"local-broadcast",value:{topic:e,payload:t},options:i};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function nv(n,e){let t=e;return{authInterceptor:s=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await s(o)),setToken:s=>{t=s}}}const rv="yorkie-js-sdk",sv="0.5.7",ov="Yorkie JS SDK",av="./src/yorkie.ts",lv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},hv=["dist"],cv={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"},uv={node:">=18.0.0",npm:">=7.1.0"},fv={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},dv={name:"hackerwins",email:"susukang98@gmail.com"},pv="Apache-2.0",gv={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},mv="https://github.com/yorkie-team/yorkie-js-sdk#readme",Ov={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},yv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Zd={name:rv,version:sv,description:ov,main:av,publishConfig:lv,files:hv,scripts:cv,engines:uv,repository:fv,author:dv,license:pv,bugs:gv,homepage:mv,devDependencies:Ov,dependencies:yv};function bv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Zd.name+"/"+Zd.version),await n(e))}const Sv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var La=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(La||{});const oa={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Dh={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class IO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"authTokenInjector");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"setAuthToken");d(this,"taskQueue");d(this,"processing",!1);d(this,"keepalive",!1);t=t||oa,this.key=t.key?t.key:PO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??oa.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??oa.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??oa.retrySyncLoopDelay;const{authInterceptor:i,setToken:r}=nv(this.apiKey);this.setAuthToken=r,this.rpcClient=b1(U1,X1({baseUrl:e,interceptors:[i,bv()],fetch:(s,o)=>{const a={...o,keepalive:this.keepalive};return fetch(s,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(async e=>{throw Z.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),Z.info(`[DC] c"${this.getKey()}" deactivated`)}catch(i){throw Z.error(`[DC] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}};if(e.keepalive){this.keepalive=!0;const i=t();return this.keepalive=!1,i}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new v(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const i=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:ke.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ke.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Gn.Removed)return e;e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new zw(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),Z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(h=>{for(const[c,u]of Object.entries(l))if(!a.has(c)){const f=c;h[f]=u}})}return e}).catch(async s=>{throw Z.error(`[AD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:i.docID,changePack:ke.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=ke.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),Z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async r=>{throw Z.error(`[DD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=i.syncMode;return r===t?e:(i.changeSyncMode(t),t==="manual"?(i.cancelWatchStream(),e):(t==="realtime"&&(i.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async i=>{throw Z.error(`[SY] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}return this.enqueueTask(async()=>{const t=[];for(const[,i]of this.attachmentMap)t.push(this.syncInternal(i,i.syncMode));return Promise.all(t).catch(async i=>{throw Z.error(`[SY] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i})})}remove(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const i=ke.toChangePack(e.createChangePack());return i.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:i},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=ke.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),Z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async r=>{throw Z.error(`[RD] c:"${this.getKey()}" err :`,r),await 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,i,r){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);if(!Sv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Dh.maxRetries,a=Dh.maxBackoff;let l=0;const h=u=>Math.min(Dh.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(i))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{Z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async u=>{if(Z.error(`[BC] c:"${this.getKey()}" err:`,u),await this.handleConnectError(u))if(u instanceof ue&&Wr(u)===w.ErrUnauthenticated&&s.doc.publish([{type:Re.AuthError,value:{reason:js(u).reason,method:"Broadcast"}}]),lc(),h(l-1)),Z.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw Z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){Z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,i]of this.attachmentMap)i.needRealtimeSync()&&(i.remoteChangeEventReceived=!1,t.push(this.syncInternal(i,i.syncMode).catch(async r=>{throw r instanceof ue&&Wr(r)===w.ErrUnauthenticated&&i.doc.publish([{type:Re.AuthError,value:{reason:js(r).reason,method:"PushPull"}}]),r})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async i=>{Z.error(`[SL] c:"${this.getKey()}" sync failed:`,i),await this.handleConnectError(i)?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 v(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(i=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(w.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:Re.ConnectionChanged,value:So.Connected}]),Z.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:Re.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Re.ConnectionChanged,value:So.Disconnected}]),Z.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(h)?(h instanceof ue&&Wr(h)===w.ErrUnauthenticated&&t.doc.publish([{type:Re.AuthError,value:{reason:js(h).reason,method:"WatchDocuments"}}]),i()):this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Rr.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:i,docID:r}=e,s=i.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:ke.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=ke.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:Re.SyncStatusChanged,value:Wc.Synced}]),i.getStatus()===Gn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return Z.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(async o=>{throw i.publish([{type:Re.SyncStatusChanged,value:Wc.SyncFailed}]),Z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof ue))return!1;if(e.code===ne.Canceled||e.code===ne.Unknown||e.code===ne.ResourceExhausted||e.code===ne.Unavailable)return!0;if(Wr(e)===w.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(js(e).reason);this.setAuthToken(t)}return!0}return(Wr(e)===w.ErrClientNotActivated||Wr(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(e){return new Promise((t,i)=>{this.taskQueue.push(()=>e().then(t).catch(i)),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 Nh={Client:IO,Document:CO,Primitive:ge,Text:oh,Counter:ah,Tree:lh,LogLevel:Ge,setLogLevel:QO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:IO,Document:CO,Primitive:ge,Text:oh,Counter:ah,Tree:lh,LogLevel:Ge,setLogLevel:QO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt});class ee{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,i){[e,t]=Os(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ui.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Os(this,e,t);let i=[];return this.decompose(e,t,i,0),ui.from(i,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),i=this.length-this.scanIdentical(e,-1),r=new io(this),s=new io(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>=i)return!0}}iter(e=1){return new io(this,e)}iterRange(e,t=this.length){return new RO(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new EO(i)}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]?ee.empty:e.length<=32?new ve(e):ui.from(ve.split(e,[]))}}class ve extends ee{constructor(e,t=wv(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?i:a)>=e)return new vv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new ve(Wd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=Xa(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new ve(a,o.length+s.length));else{let l=a.length>>1;i.push(new ve(a.slice(0,l)),new ve(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof ve))return super.replace(e,t,i);[e,t]=Os(this,e,t);let r=Xa(this.text,Xa(i.text,Wd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new ve(r,s):ui.from(ve.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=Os(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),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 i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new ve(i,r)),i=[],r=-1);return r>-1&&t.push(new ve(i,r)),t}}class ui extends ee{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],a=r+o.length,l=i+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,i,r);r=a+1,i=l+1}}decompose(e,t,i,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?i.push(a):a.decompose(e-o,t-o,i,h)}o=l+1}}replace(e,t,i){if([e,t]=Os(this,e,t),i.lines=s&&t<=a){let l=o.replace(e-s,t-s,i),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 ui(c,this.length-(t-e)+i.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` `){[e,t]=Os(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=a.sliceString(e-o,t-o,i)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof ui))return 0;let i=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 i;let l=this.children[r],h=e.children[s];if(l!=h)return i+l.scanIdentical(h,t);i+=l.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let p of e)i+=p.lines;if(i<32){let p=[];for(let g of e)g.flatten(p);return new ve(p,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function u(p){let g;if(p.lines>s&&p instanceof ui)for(let O of p.children)u(O);else p.lines>o&&(l>o||!l)?(f(),a.push(p)):p instanceof ve&&l&&(g=c[c.length-1])instanceof ve&&p.lines+g.lines<=32?(l+=p.lines,h+=p.length+1,c[c.length-1]=new ve(g.text.concat(p.text),g.length+1+p.length)):(l+p.lines>r&&f(),l+=p.lines,h+=p.length+1,c.push(p))}function f(){l!=0&&(a.push(c.length==1?c[0]:ui.from(c,h)),h=-1,l=c.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new ui(a,t)}}ee.empty=new ve([""],0);function wv(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Xa(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(l>i&&(a=a.slice(0,i-r)),r0?1:(e instanceof ve?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,a=r instanceof ve?r.text.length:r.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` `,this;e--}else if(r instanceof ve){let l=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=r.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof ve?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class RO{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new io(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class EO{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(ee.prototype[Symbol.iterator]=function(){return this.iter()},io.prototype[Symbol.iterator]=RO.prototype[Symbol.iterator]=EO.prototype[Symbol.iterator]=function(){return this});let vv=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function Os(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}let rs="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;nn)return rs[e-1]<=n;return!1}function jd(n){return n>=127462&&n<=127487}const zd=8205;function je(n,e,t=!0,i=!0){return(t?DO:xv)(n,e,i)}function DO(n,e,t){if(e==n.length)return e;e&&NO(n.charCodeAt(e))&&BO(n.charCodeAt(e-1))&&e--;let i=Be(n,e);for(e+=lt(i);e=0&&jd(Be(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function xv(n,e,t){for(;e>0;){let i=DO(n,e-2,t);if(i=56320&&n<57344}function BO(n){return n>=55296&&n<56320}function Be(n,e){let t=n.charCodeAt(e);if(!BO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return NO(i)?(t-55296<<10)+(i-56320)+65536:t}function ff(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function lt(n){return n<65536?1:2}const jc=/\r\n?|\n/;var Me=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(Me||(Me={}));class Qi{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(i!=Me.Simple&&h>=e&&(i==Me.TrackDel&&re||i==Me.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!a)return e==r||t<0?s:s+l;s+=l}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&a>=e)return rt?"cover":!0;r=a}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Qi(e)}static create(e){return new Qi(e)}}class Ce extends Qi{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return zc(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Fc(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=a,t[r+1]=o;let l=r>>1;for(;i.length0&&er(i,t,s.text),s.forward(c),a+=c}let h=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,a=null;function l(c=!1){if(!c&&!r.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let g=p?typeof p=="string"?ee.of(p.split(i||jc)):p:ee.empty,O=g.length;if(u==f&&O==0)return;uo&&Ue(r,u-o,-1),Ue(r,f-u,O),er(s,r,g),o=f}}return h(e),l(!a),a}static empty(e){return new Ce(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;ra&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function er(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(r,h,s,c,u),r=h,s=c}}}function Fc(n,e,t,i=!1){let r=[],s=i?[]:null,o=new wo(n),a=new wo(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Ue(r,h,-1),o.forward(h),a.forward(h)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let h=0,c=o.len;for(;c;)if(a.ins==-1){let u=Math.min(c,a.len);h+=u,c-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>h),s.forward2(l),o.forward(l)}}}}class wo{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?ee.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?ee.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class $r{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new $r(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return Q.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return Q.range(this.anchor,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return Q.range(e.anchor,e.head)}static create(e,t,i){return new $r(e,t,i)}}class Q{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:Q.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new Q(e.ranges.map(t=>$r.fromJSON(t)),e.main)}static single(e,t=e){return new Q([Q.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;re?8:0)|s)}static normalized(e,t=0){let i=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?Q.range(l,a):Q.range(a,l))}}return new Q(e,t)}}function MO(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let df=0;class B{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=df++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new B(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:pf),!!e.static,e.enables)}of(e){return new Ua([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ua(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ua(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function pf(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Ua{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=df++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,h=!1,c=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?h=!0:((t=e[u.id])!==null&&t!==void 0?t:1)&1||c.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||h&&(f.docChanged||f.selection)||_c(u,c)){let p=i(u);if(a?!Fd(p,u.values[o],r):!r(p,u.values[o]))return u.values[o]=p,1}return 0},reconfigure:(u,f)=>{let p,g=f.config.address[s];if(g!=null){let O=Tl(f,g);if(this.dependencies.every(y=>y instanceof B?f.facet(y)===u.facet(y):y instanceof Ee?f.field(y,!1)==u.field(y,!1):!0)||(a?Fd(p=i(u),O,r):r(p=i(u),O)))return u.values[o]=O,0}else p=i(u);return u.values[o]=p,1}}}}function Fd(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),r=t.map(l=>l.type),s=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(_d).find(i=>i.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,_d.of({field:this,create:e})]}get extension(){return this}}const Tr={lowest:4,low:3,default:2,high:1,highest:0};function Ns(n){return e=>new VO(e,n)}const mr={highest:Ns(Tr.highest),high:Ns(Tr.high),default:Ns(Tr.default),low:Ns(Tr.low),lowest:Ns(Tr.lowest)};class VO{constructor(e,t){this.inner=e,this.prec=t}}class hh{of(e){return new Gc(this,e)}reconfigure(e){return hh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Gc{constructor(e,t){this.compartment=e,this.inner=t}}class xl{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let f of Qv(e,t,o))f instanceof Ee?r.push(f):(s[f.facet.id]||(s[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],h=[];for(let f of r)a[f.id]=h.length<<1,h.push(p=>f.slot(p));let c=i==null?void 0:i.config.facets;for(let f in s){let p=s[f],g=p[0].facet,O=c&&c[f]||[];if(p.every(y=>y.type==0))if(a[g.id]=l.length<<1|1,pf(O,p))l.push(i.facet(g));else{let y=g.combine(p.map(S=>S.value));l.push(i&&g.compare(y,i.facet(g))?i.facet(g):y)}else{for(let y of p)y.type==0?(a[y.id]=l.length<<1|1,l.push(y.value)):(a[y.id]=h.length<<1,h.push(S=>y.dynamicSlot(S)));a[g.id]=h.length<<1,h.push(y=>Tv(y,g,p))}}let u=h.map(f=>f(a));return new xl(e,o,u,a,l,s)}}function Qv(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,a){let l=r.get(o);if(l!=null){if(l<=a)return;let h=i[l].indexOf(o);h>-1&&i[l].splice(h,1),o instanceof Gc&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof Gc){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,a)}else if(o instanceof VO)s(o.inner,o.prec);else if(o instanceof Ee)i[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Ua)i[a].push(o),o.facet.extensions&&s(o.facet.extensions,Tr.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,a)}}return s(n,Tr.default),i.reduce((o,a)=>o.concat(a))}function no(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function Tl(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const LO=B.define(),Jc=B.define({combine:n=>n.some(e=>e),static:!0}),XO=B.define({combine:n=>n.length?n[0]:void 0,static:!0}),UO=B.define(),ZO=B.define(),WO=B.define(),jO=B.define({combine:n=>n.length?n[0]:!1});class jn{constructor(e,t){this.type=e,this.value=t}static define(){return new Pv}}class Pv{of(e){return new jn(this,e)}}class Av{constructor(e){this.map=e}of(e){return new _(this,e)}}class _{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new _(this.type,t)}is(e){return this.type==e}static define(e={}){return new Av(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}_.reconfigure=_.define();_.appendConfig=_.define();class Se{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&MO(i,t.newLength),s.some(a=>a.type==Se.time)||(this.annotations=s.concat(Se.time.of(Date.now())))}static create(e,t,i,r,s,o){return new Se(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(Se.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}Se.time=jn.define();Se.userEvent=jn.define();Se.addToHistory=jn.define();Se.remote=jn.define();function $v(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof Se?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof Se?n=s[0]:n=FO(e,ss(s),!1)}return n}function Iv(n){let e=n.startState,t=e.facet(WO),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=zO(i,Yc(e,s,n.changes.newLength),!0))}return i==n?n:Se.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const Rv=[];function ss(n){return n==null?Rv:Array.isArray(n)?n:[n]}var de=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(de||(de={}));const Ev=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Hc;try{Hc=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Dv(n){if(Hc)return Hc.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||Ev.test(t)))return!0}return!1}function Nv(n){return e=>{if(!/\S/.test(e))return de.Space;if(Dv(e))return de.Word;for(let t=0;t-1)return de.Word;return de.Other}}class K{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;ar.set(h,l)),t=null),r.set(a.value.compartment,a.value.extension)):a.is(_.reconfigure)?(t=null,i=a.value):a.is(_.appendConfig)&&(t=null,i=ss(i).concat(a.value));let s;t?s=e.startState.values.slice():(t=xl.resolve(i,r,this),s=new K(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(Jc)?e.newSelection:e.newSelection.asSingle();new K(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:Q.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=ss(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return K.create({doc:e.doc,selection:Q.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=xl.resolve(e.extensions||[],new Map),i=e.doc instanceof ee?e.doc:ee.of((e.doc||"").split(t.staticFacet(K.lineSeparator)||jc)),r=e.selection?e.selection instanceof Q?e.selection:Q.single(e.selection.anchor,e.selection.head):Q.single(0);return MO(r,i.length),t.staticFacet(Jc)||(r=r.asSingle()),new K(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(K.tabSize)}get lineBreak(){return this.facet(K.lineSeparator)||` diff --git a/examples/vanilla-codemirror6/index.html b/examples/vanilla-codemirror6/index.html index 68549d60d..9bcf86eca 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-ZU4bONgA.js b/examples/vanilla-quill/assets/index-DGRIjSrr.js similarity index 99% rename from examples/vanilla-quill/assets/index-ZU4bONgA.js rename to examples/vanilla-quill/assets/index-DGRIjSrr.js index 6b57d552d..434108387 100644 --- a/examples/vanilla-quill/assets/index-ZU4bONgA.js +++ b/examples/vanilla-quill/assets/index-DGRIjSrr.js @@ -20,7 +20,7 @@ var Ku=Object.defineProperty;var Hu=(i,t,e)=>t in i?Ku(i,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Kt=null;try{Kt=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 Ve(i,t,e){this.low=i|0,this.high=t|0,this.unsigned=!!e}Ve.prototype.__isLong__;Object.defineProperty(Ve.prototype,"__isLong__",{value:!0});function yt(i){return(i&&i.__isLong__)===!0}function vl(i){var t=Math.clz32(i&-i);return i?31-t:t}Ve.isLong=yt;var bl={},wl={};function Pi(i,t){var e,n,r;return t?(i>>>=0,(r=0<=i&&i<256)&&(n=wl[i],n)?n:(e=Ke(i,0,!0),r&&(wl[i]=e),e)):(i|=0,(r=-128<=i&&i<128)&&(n=bl[i],n)?n:(e=Ke(i,i<0?-1:0,!1),r&&(bl[i]=e),e))}Ve.fromInt=Pi;function Ht(i,t){if(isNaN(i))return t?Wr:an;if(t){if(i<0)return Wr;if(i>=hu)return pu}else{if(i<=-Tl)return Et;if(i+1>=Tl)return gu}return i<0?Ht(-i,t).neg():Ke(i%Zi|0,i/Zi|0,t)}Ve.fromNumber=Ht;function Ke(i,t,e){return new Ve(i,t,e)}Ve.fromBits=Ke;var As=Math.pow;function xa(i,t,e){if(i.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return t?Wr:an;if(e=e||10,e<2||360)throw Error("interior hyphen");if(n===0)return xa(i.substring(1),t,e).neg();for(var r=Ht(As(e,8)),o=an,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Zi+(this.low>>>0):this.high*Zi+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,y=m.toString(t);if(s=c,s.isZero())return y+u;for(;y.length<6;)y="0"+y;u=""+y+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 t=this.high!=0?this.high:this.low,e=31;e>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 yt(t)||(t=hn(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(yt(t)||(t=hn(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?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(Et)?Et:this.not().add(Ji)};he.neg=he.negate;he.add=function(t){yt(t)||(t=hn(t));var e=this.high>>>16,n=this.high&65535,r=this.low>>>16,o=this.low&65535,s=t.high>>>16,u=t.high&65535,c=t.low>>>16,m=t.low&65535,y=0,f=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,f+=l>>>16,l&=65535,f+=n+u,y+=f>>>16,f&=65535,y+=e+s,y&=65535,Ke(l<<16|a,y<<16|f,this.unsigned)};he.subtract=function(t){return yt(t)||(t=hn(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(yt(t)||(t=hn(t)),Kt){var e=Kt.mul(this.low,this.high,t.low,t.high);return Ke(e,Kt.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wr:an;if(this.eq(Et))return t.isOdd()?Et:an;if(t.eq(Et))return this.isOdd()?Et:an;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(Sl)&&t.lt(Sl))return Ht(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,o=this.low>>>16,s=this.low&65535,u=t.high>>>16,c=t.high&65535,m=t.low>>>16,y=t.low&65535,f=0,l=0,a=0,p=0;return p+=s*y,a+=p>>>16,p&=65535,a+=o*y,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*y,f+=l>>>16,l&=65535,l+=o*m,f+=l>>>16,l&=65535,l+=s*c,f+=l>>>16,l&=65535,f+=n*y+r*m+o*c+s*u,f&=65535,Ke(a<<16|p,f<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(yt(t)||(t=hn(t)),t.isZero())throw Error("division by zero");if(Kt){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Kt.div_u:Kt.div_s)(this.low,this.high,t.low,t.high);return Ke(e,Kt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wr:an;var n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wr;if(t.gt(this.shru(1)))return du;o=Wr}else{if(this.eq(Et)){if(t.eq(Ji)||t.eq(ma))return Et;if(t.eq(Et))return Ji;var s=this.shr(1);return n=s.div(t).shl(1),n.eq(an)?t.isNegative()?Ji:ma:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o)}else if(t.eq(Et))return this.unsigned?Wr:an;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=an}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:As(2,u-48),m=Ht(n),y=m.mul(t);y.isNegative()||y.gt(r);)n-=c,m=Ht(n,this.unsigned),y=m.mul(t);m.isZero()&&(m=Ji),o=o.add(m),r=r.sub(y)}return o};he.div=he.divide;he.modulo=function(t){if(yt(t)||(t=hn(t)),Kt){var e=(this.unsigned?Kt.rem_u:Kt.rem_s)(this.low,this.high,t.low,t.high);return Ke(e,Kt.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return Ke(~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?vl(this.low):vl(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return yt(t)||(t=hn(t)),Ke(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return yt(t)||(t=hn(t)),Ke(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return yt(t)||(t=hn(t)),Ke(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low<>>32-t,this.unsigned):Ke(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):Ke(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?Ke(this.high,0,this.unsigned):Ke(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,Ke(this.high<>>e,this.low<>>e,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,Ke(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?Ke(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:Ke(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};Ve.fromBytes=function(t,e,n){return n?Ve.fromBytesLE(t,e):Ve.fromBytesBE(t,e)};Ve.fromBytesLE=function(t,e){return new Ve(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ve.fromBytesBE=function(t,e){return new Ve(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var ht=(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))(ht||{});class tt extends ko{constructor(e,n){super(n);T(this,"valueType");T(this,"value");this.valueType=tt.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,n){return new tt(e,n)}static valueFromBytes(e,n){switch(e){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 Ve.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Ve.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Fn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=tt.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":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof Ve)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return tt.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===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 e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!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 e=this.value,n=Ve.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class Ts extends fu{constructor(e){super(e);T(this,"prev");T(this,"next");this.value=e}static createAfter(e,n){const r=new Ts(n),o=e.next;return e.next=r,r.prev=e,r.next=o,o&&(o.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()}}class Ao{constructor(){T(this,"dummyHead");T(this,"last");T(this,"nodeMapByIndex");T(this,"nodeMapByCreatedAt");const t=tt.of(0,un);t.setRemovedAt(un),this.dummyHead=new Ts(t),this.last=this.dummyHead,this.nodeMapByIndex=new wo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ao}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let n=this.nodeMapByCreatedAt.get(t.toIDString());if(!n)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(e);)n=n.getNext();return n}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,n=e.getCreatedAt()){const r=this.findNextBeforeExecutedAt(t,n),o=Ts.createAfter(r,e);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,e,n){const r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(e.toIDString());if(!o)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${e.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(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new ne(te.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,n]=this.nodeMapByIndex.find(t);let r=e;if(t===0&&e===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const n=this.nodeMapByCreatedAt.get(t.toIDString()),r=n.isRemoved();return n.remove(e)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(t,e){const n=this.getByIndex(t);if(n)return n.remove(e)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const n=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${n}}`):t.push(`[${n}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Lt extends hi{constructor(e,n){super(e);T(this,"elements");this.elements=n}static create(e,n){if(!n)return new Lt(e,Ao.create());const r=Ao.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Lt(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,n){this.elements.insertAfter(e,n)}moveAfter(e,n,r){this.elements.moveAfter(e,n,r)}get(e){const n=this.elements.getByIndex(e);return n==null?void 0:n.getValue()}getByID(e){const n=this.elements.getByID(e);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,n){return this.elements.delete(e,n)}deleteByIndex(e,n){return this.elements.deleteByIndex(e,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const n of this.elements){const r=n.getValue();if(e(r,this))return;r instanceof hi&&r.getDescendants(e)}}toJSON(){const e=[];for(const n of this)e.push(n.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let n=0;n({...p,value:p.value?{attributes:zi(p.value.getAttributes()),content:p.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[y,a,f,[m,m]]}setStyle(e,n,r,o,s){const[,u]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,c]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),m=[],y=this.rgaTreeSplit.findBetween(c,u),f=new Map,l=[];for(const p of y){const b=p.getCreatedAt().getActorID();let w,v=0n;if(s===void 0&&o===void 0?v=fo:s.size()>0?v=s.get(b)?s.get(b):0n:w=o.has(b)?o.get(b):un,p.canStyle(r,w,v)){const h=f.get(b),g=p.getCreatedAt();(!h||g.after(h))&&f.set(b,g),l.push(p)}}const a=[];for(const p of l){if(p.isRemoved())continue;const[b,w]=this.rgaTreeSplit.findIndexesFromRange(p.createPosRange());m.push({type:"style",actor:r.getActorID(),from:b,to:w,value:{attributes:zi(n)}});for(const[v,h]of Object.entries(n)){const[g]=p.getValue().setAttr(v,h,r);g!==void 0&&a.push({parent:p.getValue(),child:g})}}return[f,a,m]}indexRangeToPosRange(e,n){const r=this.rgaTreeSplit.indexToPos(e);return e===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 e=[];for(const n of this.rgaTreeSplit)n.isRemoved()||e.push(n.getValue().toJSON());return`[${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(){const e=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();e.push({attributes:zi(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())e.push(r)}return e}}class Io extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"content");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(e,n,r,o,s,u,c){return new Io(e,n,r,o,s,u,c)}execute(e,n,r){const o=e.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=o,[,u,c]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,r);for(const m of c)e.registerGCPair(m);return{opInfos:u.map(({from:m,to:y,value:f})=>({type:"edit",from:m,to:y,value:f,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${e}.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 No extends fn{constructor(e,n,r,o,s,u){super(e,u);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(e,n,r,o,s,u){return new No(e,n,r,o,s,u)}execute(e,n,r){const o=e.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=o,[,u,c]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,r);for(const m of u)e.registerGCPair(m);return{opInfos:c.map(({from:m,to:y,value:f})=>({type:"style",from:m,to:y,value:f,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${e}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Sf=2,Ef="root",Gr="text";function so(i,t){let e=0;const n=i.children;for(let r=0;r0)throw new ne(te.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const n=e.updateDescendantsSize();e.isRemoved||(t+=n)}return this.size+=t,this.paddedSize}get isText(){return this.type===Gr}get paddedSize(){return this.size+(this.isText?0:Sf)}isAncestorOf(t){return kf(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const n=this.value.slice(0,t),r=this.value.slice(t);if(!r.length)return;this.value=n;const o=this.cloneText(t+e);return o.value=r,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 ne(te.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new ne(te.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const n=this.cloneElement(e);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,t),o=this.children.slice(t);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(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1)}insertAtInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(r=>!r.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const n=this._children.indexOf(e);if(n!==-1)return n;e=e.parent}return-1}}function kf(i,t){if(i===t)return!1;for(;t.parent;){if(t.parent===i)return!0;t=t.parent}return!1}var ct=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(ct||{});function mu(i,t,e,n){if(t>e)throw new ne(te.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>i.size)throw new ne(te.ErrInvalidArgument,`from is out of range: ${t} > ${i.size}`);if(e>i.size)throw new ne(te.ErrInvalidArgument,`to is out of range: ${e} > ${i.size}`);if(t===e)return;let r=0;for(const o of i.children){if(t-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),mu(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function yu(i,t,e=0){for(const n of i.children)yu(n,t,e+1);t(i,e)}function Ns(i,t,e=0){for(const n of i._children)Ns(n,t,e+1);t(i,e)}function ya(i,t,e=!0){if(t>i.size)throw new ne(te.ErrInvalidArgument,`index is out of range: ${t} > ${i.size}`);if(i.isText)return{node:i,offset:t};let n=0,r=0;for(const o of i.children){if(e&&o.isText&&o.size>=t-r)return ya(o,t-r,e);if(t===r)return{node:i,offset:n};if(!e&&o.paddedSize===t-r)return{node:i,offset:n+1};if(o.paddedSize>t-r)return ya(o,t-r-1,e);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function vu(i){return i.isText||i.children.length===0?i:vu(i.children[0])}function Of(i,t){if(i.sizei===t?0:i0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(n<0)if(e.left)e.left.parent=e,e=e.left;else{let r=e.parent,o=e;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return e}}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,e){for(;e;){const n=this.comparator(t,e.key);if(n===0)return e;n<0?e=e.left:n>0&&(e=e.right)}}putInternal(t,e,n){if(!n)return this.counter+=1,new _f(t,e,!0);const r=this.comparator(t,n.key);return r<0?n.left=this.putInternal(t,e,n.left):r>0?n.right=this.putInternal(t,e,n.right):n.value=e,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(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,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(e,t.key)===0){this.counter-=1;const n=this.min(t.right);t.value=n.value,t.key=n.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}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 e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ln{constructor(t,e){T(this,"parentID");T(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ln(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:n}=t,r;return n.isText?(n.parent.children[0]===n&&e===0?r=n.parent:r=n,n=n.parent):e===0?r=n:r=n.children[e-1],ln.of(n.id,pt.of(r.getCreatedAt(),r.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ln.of(pt.of(Wt.fromStruct(t.parentID.createdAt),t.parentID.offset),pt.of(Wt.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 e=this.getParentID(),n=this.getLeftSiblingID(),r=t.findFloorNode(e);let o=t.findFloorNode(n);if(!r||!o)throw new ne(te.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${n.toTestString()})`);return!n.equals(e)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[r,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 pt{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new pt(t,e)}static fromStruct(t){return pt.of(Wt.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const n=t.getCreatedAt().compare(e.getCreatedAt());return n!==0?n:t.getOffset()>e.getOffset()?1:t.getOffset(){const o=r.deepcopy();return o.parent=e,o}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),n&&this.updateAncestorsSize()}cloneText(e){return new Ct(pt.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new Ct(pt.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,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=e.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,e.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,n,r){return(n?!this.getCreatedAt().after(n):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,n,r){return this.isText?!1:(n?!this.getCreatedAt().after(n):this.getCreatedAt().getLamport()<=r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,n){this.attrs||(this.attrs=new Xr);const r=[];for(const[o,s]of Object.entries(e))r.push(this.attrs.set(o,s,n));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const n of this.attrs)n.getRemovedAt()&&e.push({parent:this,child:n});return e}}function va(i){var e;if(i.isText){const n=i;return{type:n.type,value:n.value}}const t={type:i.type,children:i.children.map(va)};return i.attrs&&(t.attributes=zi((e=i.attrs)==null?void 0:e.toObject())),t}function ka(i){if(i.isText)return i.value;let t="";return i.attrs&&i.attrs.size()&&(t=" "+Array.from(i.attrs).filter(e=>!e.isRemoved()).sort((e,n)=>e.getKey().localeCompare(n.getKey())).map(e=>{const n=JSON.parse(e.getValue());return typeof n=="string"?`${e.getKey()}="${n}"`:`${e.getKey()}="${Fn(e.getValue())}"`}).join(" ")),`<${i.type}${t}>${i.children.map(e=>ka(e)).join("")}`}function wu(i){if(i.isText){const t=i;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:i.type,children:i.children.map(wu),size:i.size,isRemoved:i.isRemoved}}class Yt extends ko{constructor(e,n){super(n);T(this,"indexTree");T(this,"nodeMapByID");this.indexTree=new If(e),this.nodeMapByID=new bu(pt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(e,n){return new Yt(e,n)}findFloorNode(e){const n=this.nodeMapByID.floorEntry(e);if(!(!n||!n.key.getCreatedAt().equals(e.getCreatedAt())))return n.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,n){const[r,o]=e.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,e.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,y=u?0:m.indexOf(s)+1;for(let f=y;f{const w=b.getCreatedAt().getActorID();let v,h=0n;if(s===void 0&&o===void 0?h=fo:s.size()>0?h=s.get(w)?s.get(w):0n:v=o.has(w)?o.get(w):un,b.canStyle(r,v,h)&&n){const g=a.get(w),d=b.getCreatedAt();(!g||d.after(g))&&a.set(w,d);const A=b.setAttrs(n,r),S=A.reduce((_,[,k])=>(k&&(_[k.getKey()]=l[k.getKey()]),_),{}),E=b.parent,O=b.prevSibling||b.parent;Object.keys(S).length>0&&f.push({type:"style",from:this.toIndex(E,O),to:this.toIndex(b,b),fromPath:this.toPath(E,O),toPath:this.toPath(b,b),actor:r.getActorID(),value:S});for(const[_]of A)_&&p.push({parent:b,child:_})}}),[a,p,f]}removeStyle(e,n,r,o,s){const[u,c]=this.findNodesAndSplitText(e[0],r),[m,y]=this.findNodesAndSplitText(e[1],r),f=[],l=new Map,a=[];return this.traverseInPosRange(u,c,m,y,([p])=>{const b=p.getCreatedAt().getActorID();let w,v=0n;if(s===void 0&&o===void 0?v=fo:s.size()>0?v=s.get(b)?s.get(b):0n:w=o.has(b)?o.get(b):un,p.canStyle(r,w,v)&&n){const h=l.get(b),g=p.getCreatedAt();(!h||g.after(h))&&l.set(b,g),p.attrs||(p.attrs=new Xr);for(const S of n){const E=p.attrs.remove(S,r);for(const O of E)a.push({parent:p,child:O})}const d=p.parent,A=p.prevSibling||p.parent;f.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(d,A),to:this.toIndex(p,p),fromPath:this.toPath(d,A),toPath:this.toPath(p,p),value:n})}}),[l,a,f]}edit(e,n,r,o,s,u,c){const[m,y]=this.findNodesAndSplitText(e[0],o),[f,l]=this.findNodesAndSplitText(e[1],o),a=this.toIndex(m,y),p=this.toPath(m,y),b=[],w=[],v=[],h=new Map;this.traverseInPosRange(m,y,f,l,([A,S],E)=>{if(S===ct.Start&&!E)for(const x of A.children)v.push(x);const O=A.getCreatedAt().getActorID();let _,k=0n;if(c===void 0&&u===void 0?k=fo:c.size()>0?k=c.get(O)?c.get(O):0n:_=u.has(O)?u.get(O):un,A.canDelete(o,_,k)||b.includes(A.parent)){const x=h.get(O),I=A.getCreatedAt();(!x||I.after(x))&&h.set(O,I),(S===ct.Text||S===ct.Start)&&b.push(A),w.push([A,S])}});const g=this.makeDeletionChanges(w,o),d=[];for(const A of b)A.remove(o),A.isRemoved&&d.push({parent:this,child:A});for(const A of v)A.removedAt||m.append(A);if(r>0){let A=0,S=m,E=y;for(;A{m.isRemoved&&(O.remove(o),d.push({parent:this,child:O})),this.nodeMapByID.put(O.id,O)}),E.isRemoved||A.push(E);if(A.length){const E=A.map(O=>va(O));g.length&&g[g.length-1].from===a?g[g.length-1].value=E:g.push({type:"content",from:a,to:a,fromPath:p,toPath:p,actor:o.getActorID(),value:E})}}return[g,d,h]}editT(e,n,r,o,s){const u=this.findPos(e[0]),c=this.findPos(e[1]);this.edit([u,c],n,r,o,s)}move(e,n,r){throw new ne(te.ErrUnimplemented,`not implemented: ${e}, ${n}, ${r}`)}purge(e){var o;(o=e.parent)==null||o.removeChild(e),this.nodeMapByID.remove(e.id);const n=e.insPrevID,r=e.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&e.push({parent:this,child:n});for(const r of n.getGCPairs())e.push(r)}),e}findPos(e,n=!0){const r=this.indexTree.findTreePos(e,n);return ln.fromTreePos(r)}pathToPosRange(e){const n=this.pathToIndex(e);return[this.findPos(n),this.findPos(n+1)]}pathToPos(e){const n=this.indexTree.pathToIndex(e);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 ka(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 e=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,y;const f=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;f&&(c=this.indexTree.indexOf(f),m=this.indexTree.treePosToPath(f),y=ln.fromTreePos(f).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?zi((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:y};for(let v=0;v0&&v===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:v,to:h,fromPath:this.toPath(b,f),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([e,n]){if(n===ct.Start){const c=e.allChildren;return c.length>0?[c[0],c[0].isText?ct.Text:ct.Start]:[e,ct.End]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===o.length-1)return[r,ct.End];const u=o[s+1];return[u,u.isText?ct.Text:ct.Start]}findLeftToken([e,n]){if(n===ct.End){const c=e.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?ct.Text:ct.End]}return[e,ct.Start]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===0)return[r,ct.Start];const u=o[s-1];return[u,u.isText?ct.Text:ct.End]}}class _o extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"contents");T(this,"splitLevel");T(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(e,n,r,o,s,u,c){return new _o(e,n,r,o,s,u,c)}execute(e,n,r){var y;const o=e.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),u=o,[c,m]=u.edit([this.fromPos,this.toPos],(y=this.contents)==null?void 0:y.map(f=>f.deepcopy()),this.splitLevel,s,(()=>{let f=s.getDelimiter();return this.contents!==void 0&&(f+=this.contents.length),()=>Wt.of(s.getLamport(),++f,s.getActorID())})(),this.maxCreatedAtMapByActor,r);for(const f of m)e.registerGCPair(f);return{opInfos:c.map(({from:f,to:l,value:a,splitLevel:p,fromPath:b,toPath:w})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:f,to:l,value:a,splitLevel:p,fromPath:b,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=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`${e}.EDIT(${n},${r},${o.map(s=>ka(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Vi{constructor(t){T(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}unset(t){this.vector.delete(t)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[n,r]of t){const o=this.vector.get(n),s=o&&o>r?o:r;e.set(n,s)}for(const[n,r]of this){const o=t.get(n),s=o&&o>r?o:r;e.set(n,s)}return new Vi(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,n]of this.vector)t.set(e,n);return new Vi(t)}filter(t){const e=new Map;for(const[n]of t){const r=this.vector.get(n);r!==void 0&&e.set(n,r)}return new Vi(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Cf=new Vi(new Map);class zr{constructor(t,e,n,r,o){T(this,"clientSeq");T(this,"serverSeq");T(this,"lamport");T(this,"actor");T(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=e,this.versionVector=r,this.actor=n}static of(t,e,n,r,o){return new zr(t,e,n,r,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zr(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n;let n=t.versionVector;n.size()===0&&(n=n.deepcopy(),n.set(t.actor,t.lamport));const r=this.versionVector.max(n),o=new zr(this.clientSeq,e,this.actor,r);return o.versionVector.set(this.actor,e),o}setClocks(t,e){const n=t>this.lamport?t+1n:this.lamport+1n;e.unset(Is);const r=this.versionVector.max(e);return r.set(this.actor,n),zr.of(this.clientSeq,n,this.actor,r)}createTimeTicket(t){return Wt.of(this.lamport,t,this.actor)}setActor(t){return new zr(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zr(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Lf=new zr(0,0n,Is,Cf);class Xi{constructor({id:t,operations:e,presenceChange:n,message:r}){T(this,"id");T(this,"operations");T(this,"presenceChange");T(this,"message");this.id=t,this.operations=e||[],this.presenceChange=n,this.message=r}static create({id:t,operations:e,presenceChange:n,message:r}){return new Xi({id:t,operations:e,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(t,n,this.id.getVersionVector());if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===pi.Put?e.set(this.id.getActorID(),sn(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:lt.bytesToHex(lt.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>lt.bytesToHex(lt.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:n,presenceChange:r,message:o}=t;return Xi.create({id:lt.bytesToChangeID(lt.hexToBytes(e)),operations:n==null?void 0:n.map(s=>lt.bytesToOperation(lt.hexToBytes(s))),presenceChange:r,message:o})}}class _s{constructor(t,e,n,r,o,s,u){T(this,"documentKey");T(this,"checkpoint");T(this,"isRemoved");T(this,"changes");T(this,"snapshot");T(this,"minSyncedTicket");T(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=u,this.versionVector=o}static create(t,e,n,r,o,s,u){return new _s(t,e,n,r,o,s,u)}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}getVersionVector(){return this.versionVector}}class Ki{constructor(t,e){T(this,"serverSeq");T(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Ki(t,e)}increaseClientSeq(t){return t===0?this:new Ki(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,n=Math.max(this.clientSeq,t.clientSeq);return Ki.of(e,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Rf=new Ki(0n,0);class jn{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new jn(t,e)}static fromStruct(t){return jn.of(Wt.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 jn(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 Df=jn.of(un,0);class cn{constructor(t,e){T(this,"id");T(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new cn(t,e)}static fromStruct(t){const e=jn.fromStruct(t.id);return cn.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return jn.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 di extends fu{constructor(e,n,r){super(n);T(this,"id");T(this,"removedAt");T(this,"prev");T(this,"next");T(this,"insPrev");T(this,"insNext");this.id=e,this.removedAt=r}static create(e,n){return new di(e,n)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const n=[];let r=t;for(;r&&r!==e;)n.push(r),r=r.getNext();return n}splitNode(t,e){if(e>t.getContentLength())throw new ne(te.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const n=t.split(e);this.treeByIndex.updateWeight(n),this.insertAfter(t,n);const r=t.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(t),n}deleteNodes(t,e,n,r){if(!t.length)return[[],new Map,new Map];const[o,s]=this.filterNodes(t,e,n,r),u=new Map,c=new Map,m=this.makeChanges(s,e);for(const y of o){const f=y.getCreatedAt().getActorID();(!u.has(f)||y.getID().getCreatedAt().after(u.get(f)))&&u.set(f,y.getID().getCreatedAt()),c.set(y.getID().toIDString(),y),y.remove(e)}return this.deleteIndexNodes(s),[m,u,c]}filterNodes(t,e,n,r){const o=[],s=[],[u,c]=this.findEdgesOfCandidates(t);s.push(u);for(const m of t){const y=m.getCreatedAt().getActorID();let f,l=0n;r===void 0&&n===void 0?l=fo:r.size()>0?l=r.get(y)?r.get(y):0n:f=n.has(y)?n.get(y):un,m.canDelete(e,f,l)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var Un=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(Un||{});class Rt extends ko{constructor(e,n,r){super(r);T(this,"valueType");T(this,"value");switch(this.valueType=e,e){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Ve.fromNumber(n).toInt():this.value=El(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Ve.fromNumber(n):this.value=n;break;default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,n,r){return new Rt(e,n,r)}static valueFromBytes(e,n){switch(e){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Ve.fromBytesLE(Array.from(n));default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=Rt.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":return e instanceof Ve?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!Rt.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===ht.Long?this.value=this.value+e.getValue().toInt():this.value=Ve.fromNumber(this.value+El(e.getValue())).toInt(),this}}class eo extends fn{constructor(e,n,r){super(e,r);T(this,"value");this.value=n}static create(e,n,r){return new eo(e,n,r)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Rt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),r=e.getType()===ht.Long?e.getValue().multiply(-1):e.getValue()*-1;return eo.create(this.getParentCreatedAt(),tt.of(r,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yr extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");T(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(e,n,r,o,s,u){return new Yr(e,n,r,o,s,[],u)}static createTreeRemoveStyleOperation(e,n,r,o,s,u){return new Yr(e,n,r,o,new Map,s,u)}execute(e,n,r){const o=e.findByCreatedAt(this.getParentCreatedAt());if(!o)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(o instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=o;let u,c;if(this.attributes.size){const m={};[...this.attributes].forEach(([y,f])=>m[y]=f),[,c,u]=s.style([this.fromPos,this.toPos],m,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}else{const m=this.attributesToRemove;[,c,u]=s.removeStyle([this.fromPos,this.toPos],m,this.getExecutedAt(),this.maxCreatedAtMapByActor,r)}for(const m of c)e.registerGCPair(m);return{opInfos:u.map(({from:m,to:y,value:f,fromPath:l,toPath:a})=>({type:"tree-style",from:m,to:y,value:this.attributes.size?{attributes:f}:{attributesToRemove:f},fromPath:l,toPath:a,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.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 Bf(i){const t=new Sa,e=t.data;for(const[n,r]of Object.entries(i))e[n]=JSON.stringify(r);return t}function Mf(i){if(i.type===pi.Put)return new vo({type:Ni.PUT,presence:Bf(i.presence)});if(i.type===pi.Clear)return new vo({type:Ni.CLEAR});throw new ne(te.ErrUnimplemented,"unimplemented type")}function qf(i){return new lu({serverSeq:i.getServerSeq(),clientSeq:i.getClientSeq()})}function Au(i){return new ks({clientSeq:i.getClientSeq(),lamport:i.getLamport(),actorId:Ma(i.getActorID()),versionVector:Oa(i.getVersionVector())})}function ke(i){if(i)return new xe({lamport:i.getLamport(),delimiter:i.getDelimiter(),actorId:Ma(i.getActorID())})}function Oa(i){if(!i)return;const t=new Os;for(const[e,n]of i)t.vector[e]=BigInt(n.toString());return t}function Tu(i){switch(i){case ht.Null:return Re.NULL;case ht.Boolean:return Re.BOOLEAN;case ht.Integer:return Re.INTEGER;case ht.Long:return Re.LONG;case ht.Double:return Re.DOUBLE;case ht.String:return Re.STRING;case ht.Bytes:return Re.BYTES;case ht.Date:return Re.DATE;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Su(i){switch(i){case Un.IntegerCnt:return Re.INTEGER_CNT;case Un.LongCnt:return Re.LONG_CNT;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function js(i){if(i instanceof xt)return new Bt({type:Re.JSON_OBJECT,createdAt:ke(i.getCreatedAt()),value:Bu(i)});if(i instanceof Lt)return new Bt({type:Re.JSON_ARRAY,createdAt:ke(i.getCreatedAt()),value:ph(i)});if(i instanceof Gt)return new Bt({type:Re.TEXT,createdAt:ke(i.getCreatedAt())});if(i instanceof tt)return new Bt({type:Tu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Rt)return new Bt({type:Su(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Yt)return new Bt({type:Re.TREE,createdAt:ke(i.getCreatedAt()),value:yh(i)});throw new ne(te.ErrUnimplemented,"unimplemented element")}function Ff(i){return new mo({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Uo(i){return new Zr({createdAt:ke(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function Jo(i){return new Ii({parentId:ho(i.getParentID()),leftSiblingId:ho(i.getLeftSiblingID())})}function ho(i){return new fi({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Eu(i){const t=new Ta;if(i instanceof _i){const e=i,n=new rs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.key=e.getKey(),n.value=js(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="set",t.body.value=n}else if(i instanceof Oo){const e=i,n=new is;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.value=js(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="add",t.body.value=n}else if(i instanceof ci){const e=i,n=new os;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="move",t.body.value=n}else if(i instanceof mi){const e=i,n=new ss;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="remove",t.body.value=n}else if(i instanceof Io){const e=i,n=new as;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Uo(e.getFromPos()),n.to=Uo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);n.content=e.getContent();const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="edit",t.body.value=n}else if(i instanceof No){const e=i,n=new ls;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Uo(e.getFromPos()),n.to=Uo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="style",t.body.value=n}else if(i instanceof eo){const e=i,n=new us;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.value=js(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="increase",t.body.value=n}else if(i instanceof _o){const e=i,n=new cs,r=n.createdAtMapByActor;for(const[o,s]of e.getMaxCreatedAtMapByActor())r[o]=ke(s);n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Jo(e.getFromPos()),n.to=Jo(e.getToPos()),n.contents=Kf(e.getContents()),n.splitLevel=e.getSplitLevel(),n.executedAt=ke(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=n}else if(i instanceof Yr){const e=i,n=new fs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Jo(e.getFromPos()),n.to=Jo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=e.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of e.getAttributes())s[u]=c}n.executedAt=ke(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=n}else throw new ne(te.ErrUnimplemented,"unimplemented operation");return t}function jf(i){const t=[];for(const e of i)t.push(Eu(e));return t}function Uf(i){const t=new su({id:Au(i.getID()),message:i.getMessage()});return i.hasOperations()&&(t.operations=jf(i.getOperations())),i.hasPresenceChange()&&(t.presenceChange=Mf(i.getPresenceChange())),t}function Jf(i){const t=[];for(const e of i)t.push(Uf(e));return t}function $f(i){const t=[];for(const e of i)t.push(new au({key:e.getStrKey(),element:Na(e.getValue())}));return t}function zf(i){const t=[];for(const e of i)t.push(new vs({element:Na(e.getValue())}));return t}function Vf(i){const t=[];for(const e of i){const n=new bs;n.id=Ff(e.getID()),n.value=e.getValue().getContent(),n.removedAt=ke(e.getRemovedAt());const r=n.attributes,o=e.getValue().getAttrs();for(const s of o){const u=new Gi;u.value=s.getValue(),u.updatedAt=ke(s.getUpdatedAt()),r[s.getKey()]=u}t.push(n)}return t}function Kf(i){const t=[];if(!i||!i.length)return t;for(const e of i)t.push(new ws({content:Ia(e)}));return t}function Hf(i){const t={};for(const e of i)t[e.getKey()]=new Gi({value:e.getValue(),updatedAt:ke(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ia(i){if(!i)return[];const t=[];return Ns(i,(e,n)=>{const r=new yo({id:ho(e.id),type:e.type,removedAt:ke(e.removedAt),depth:n});e.isText&&(r.value=e.value),e.insPrevID&&(r.insPrevId=ho(e.insPrevID)),e.insNextID&&(r.insNextId=ho(e.insNextID)),e.attrs&&(r.attributes=Hf(e.attrs)),t.push(r)}),t}function Wf(i){const t=new kt;return t.body.case="jsonObject",t.body.value=new hs({nodes:$f(i.getRHT()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function xu(i){const t=new kt;return t.body.case="jsonArray",t.body.value=new ds({nodes:zf(i.getElements()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Gf(i){const t=new kt;return t.body.case="primitive",t.body.value=new gs({type:Tu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Yf(i){const t=new kt;return t.body.case="text",t.body.value=new ps({nodes:Vf(i.getRGATreeSplit()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Zf(i){const t=new kt;return t.body.case="counter",t.body.value=new ms({type:Su(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function ku(i){const t=new kt;return t.body.case="tree",t.body.value=new ys({nodes:Ia(i.getRoot()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Na(i){if(i instanceof xt)return Wf(i);if(i instanceof Lt)return xu(i);if(i instanceof tt)return Gf(i);if(i instanceof Gt)return Yf(i);if(i instanceof Rt)return Zf(i);if(i instanceof Yt)return ku(i);throw new ne(te.ErrUnimplemented,"unimplemented element")}function Xf(i){return new Qr({documentKey:i.getDocumentKey(),checkpoint:qf(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:Jf(i.getChanges()),snapshot:i.getSnapshot(),versionVector:Oa(i.getVersionVector()),minSyncedTicket:ke(i.getMinSyncedTicket())})}function ao(i){if(!(i instanceof Ze))return{};const t=i.findDetails(yf);for(const e of t)return e.metadata;return{}}function Mi(i){return ao(i).code??""}function Ou(i){return zr.of(i.clientSeq,BigInt(i.lamport),Da(i.actorId),_a(i.versionVector),BigInt(i.serverSeq))}function _a(i){if(!i)return;const t=new Vi;return Object.entries(i.vector).forEach(([e,n])=>{t.set(e,BigInt(n.toString()))}),t}function Ie(i){if(i)return Wt.of(BigInt(i.lamport),i.delimiter,Da(i.actorId))}function Pa(i){const t={};return Object.entries(i.data).forEach(([e,n])=>{t[e]=JSON.parse(n)}),t}function Qf(i){const t=i.type;if(t===Ni.PUT){const e=Pa(i.presence);return{type:pi.Put,presence:e}}if(t===Ni.CLEAR)return{type:pi.Clear};throw new ne(te.ErrInvalidType,`unsupported type: ${t}`)}function eh(i){const t=new Map;return Object.entries(i).forEach(([e,n])=>{t.set(e,Pa(n))}),t}function Iu(i){switch(i){case Re.NULL:return ht.Null;case Re.BOOLEAN:return ht.Boolean;case Re.INTEGER:return ht.Integer;case Re.LONG:return ht.Long;case Re.DOUBLE:return ht.Double;case Re.STRING:return ht.String;case Re.BYTES:return ht.Bytes;case Re.DATE:return ht.Date}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function Ss(i){switch(i){case Re.INTEGER_CNT:return Un.IntegerCnt;case Re.LONG_CNT:return Un.LongCnt}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function Us(i){switch(i.type){case Re.JSON_OBJECT:return i.value?Du(i.value):xt.create(Ie(i.createdAt));case Re.JSON_ARRAY:return i.value?gh(i.value):Lt.create(Ie(i.createdAt));case Re.TEXT:return Gt.create(Qi.create(),Ie(i.createdAt));case Re.TREE:return mh(i.value);case Re.NULL:case Re.BOOLEAN:case Re.INTEGER:case Re.LONG:case Re.DOUBLE:case Re.STRING:case Re.BYTES:case Re.DATE:return tt.of(tt.valueFromBytes(Iu(i.type),i.value),Ie(i.createdAt));case Re.INTEGER_CNT:case Re.LONG_CNT:return Rt.create(Ss(i.type),Rt.valueFromBytes(Ss(i.type),i.value),Ie(i.createdAt))}}function $o(i){return cn.of(jn.of(Ie(i.createdAt),i.offset),i.relativeOffset)}function Nu(i){return jn.of(Ie(i.createdAt),i.offset)}function th(i){const t=To.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{t.setAttr(n,r.value,Ie(r.updatedAt))});const e=di.create(Nu(i.id),t);return e.remove(Ie(i.removedAt)),e}function qi(i){return ln.of(go(i.parentId),go(i.leftSiblingId))}function go(i){return pt.of(Ie(i.createdAt),i.offset)}function nh(i){if(!i.length)return;const t=[];return i.forEach(e=>{const n=Ca(e.content);t.push(n)}),t}function Ca(i){if(i.length===0)return;const t=[];for(const r of i)t.push(ih(r));const e=t[t.length-1],n=new Map;n.set(i[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(t[r]),n.set(i[r].depth,t[r]);return e.updateDescendantsSize(),Yt.create(e,un).getRoot()}function rh(i){const t=Xr.create();for(const[e,n]of Object.entries(i))t.setInternal(e,n.value,Ie(n.updatedAt),n.isRemoved);return t}function ih(i){const t=go(i.id),e=Ct.create(t,i.type),n=Object.entries(i.attributes);return e.isText?e.value=i.value:n.length&&(e.attrs=rh(i.attributes)),i.insPrevId&&(e.insPrevID=go(i.insPrevId)),i.insNextId&&(e.insNextID=go(i.insNextId)),e.removedAt=Ie(i.removedAt),e}function _u(i){if(i.body.case==="set"){const t=i.body.value;return _i.create(t.key,Us(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(i.body.case==="add"){const t=i.body.value;return Oo.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Us(t.value),Ie(t.executedAt))}else if(i.body.case==="move"){const t=i.body.value;return ci.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="remove"){const t=i.body.value;return mi.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="edit"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),Io.create(Ie(t.parentCreatedAt),$o(t.from),$o(t.to),e,t.content,n,Ie(t.executedAt))}else if(i.body.case==="style"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),No.create(Ie(t.parentCreatedAt),$o(t.from),$o(t.to),e,n,Ie(t.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const t=i.body.value;return eo.create(Ie(t.parentCreatedAt),Us(t.value),Ie(t.executedAt))}else if(i.body.case==="treeEdit"){const t=i.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([n,r])=>{e.set(n,Ie(r))}),_o.create(Ie(t.parentCreatedAt),qi(t.from),qi(t.to),nh(t.contents),t.splitLevel,e,Ie(t.executedAt))}else if(i.body.case==="treeStyle"){const t=i.body.value,e=new Map,n=t.attributesToRemove,r=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Ie(s))}),(n==null?void 0:n.length)>0?Yr.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),qi(t.from),qi(t.to),r,n,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,s])=>{e.set(o,s)}),Yr.create(Ie(t.parentCreatedAt),qi(t.from),qi(t.to),r,e,Ie(t.executedAt)))}else throw new ne(te.ErrUnimplemented,"unimplemented operation")}}function oh(i){const t=[];for(const e of i){const n=_u(e);n&&t.push(n)}return t}function Pu(i){const t=[];for(const e of i)t.push(Xi.create({id:Ou(e.id),operations:oh(e.operations),presenceChange:e.presenceChange?Qf(e.presenceChange):void 0,message:e.message}));return t}function sh(i){return Ki.of(BigInt(i.serverSeq),i.clientSeq)}function ah(i){return _s.create(i.documentKey,sh(i.checkpoint),i.isRemoved,Pu(i.changes),_a(i.versionVector),i.snapshot,Ie(i.minSyncedTicket))}function Cu(i){const t=new bo;for(const n of i.nodes){const r=La(n.element);t.set(n.key,r,r.getPositionedAt())}const e=new xt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function Lu(i){const t=new Ao;for(const n of i.nodes)t.insert(La(n.element));const e=new Lt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function lh(i){const t=tt.of(tt.valueFromBytes(Iu(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function uh(i){const t=new Qi;let e=t.getHead();for(const r of i.nodes){const o=t.insertAfter(e,th(r));r.insPrevId&&o.setInsPrev(t.findNode(Nu(r.insPrevId))),e=o}const n=new Gt(t,Ie(i.createdAt));return n.setMovedAt(Ie(i.movedAt)),n.setRemovedAt(Ie(i.removedAt)),n}function ch(i){const t=Rt.create(Ss(i.type),Rt.valueFromBytes(Ss(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function Ru(i){const t=Ca(i.nodes);return Yt.create(t,Ie(i.createdAt))}function La(i){if(i.body.case==="jsonObject")return Cu(i.body.value);if(i.body.case==="jsonArray")return Lu(i.body.value);if(i.body.case==="primitive")return lh(i.body.value);if(i.body.case==="text")return uh(i.body.value);if(i.body.case==="counter")return ch(i.body.value);if(i.body.case==="tree")return Ru(i.body.value);throw new ne(te.ErrUnimplemented,"unimplemented element")}function fh(i){if(!i)return{root:xt.create(un),presences:new Map};const t=Hs.fromBinary(i);return{root:La(t.root),presences:eh(t.presences)}}function hh(i){const t=Oa(i);return Ra(t.toBinary())}function dh(i){const t=Ba(i),e=Os.fromBinary(t);return _a(e)}function Du(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Cu(t.body.value)}function Bu(i){return Na(i).toBinary()}function gh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Lu(t.body.value)}function ph(i){return xu(i).toBinary()}function mh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Ru(t.body.value)}function yh(i){return ku(i).toBinary()}function Ra(i){return i?Array.from(i).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function Da(i){return Ra(i)}function Ba(i){return new Uint8Array(i.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Ma(i){return Ba(i)}function vh(i){const t=ks.fromBinary(i);return Ou(t)}function bh(i){const t=Ta.fromBinary(i);return _u(t)}const lt={fromPresence:Pa,toChangePack:Xf,fromChangePack:ah,fromChanges:Pu,toTreeNodes:Ia,fromTreeNodes:Ca,objectToBytes:Bu,bytesToObject:Du,bytesToSnapshot:fh,bytesToHex:Ra,hexToBytes:Ba,toHexString:Da,toUint8Array:Ma,toOperation:Eu,toChangeID:Au,PbChangeID:ks,bytesToChangeID:vh,bytesToOperation:bh,versionVectorToHex:hh,hexToVersionVector:dh};var wt=(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))(wt||{});let bi=3;function Mu(i){bi=i}const Ne={trivial:(...i)=>{bi>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{bi>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{bi>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{bi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{bi>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=>bi<=i};function qu(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const t=Math.random()*16|0;return(i==="x"?t:t&3|8).toString(16)})}class wh{constructor(t,e,n,r,o){T(this,"reconnectStreamDelay");T(this,"doc");T(this,"docID");T(this,"syncMode");T(this,"remoteChangeEventReceived");T(this,"watchStream");T(this,"watchLoopTimerID");T(this,"watchAbortController");T(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Qo.RealtimeSyncOff?!1:this.syncMode===Qo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Qo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=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(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Js=()=>{};class Ah{constructor(t){T(this,"finalized",!1);T(this,"observers",[]);T(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,n){let r;if(!t)throw new ne(te.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(te.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?r=t:r={next:t,error:e,complete:n},r.next===void 0&&(r.next=Js),r.error===void 0&&(r.error=Js),r.complete===void 0&&(r.complete=Js);const o=qu(),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){Ne.warn(u)}return s}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(n=>n.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class $i{constructor(t,e,n,r){T(this,"id");T(this,"delimiter");T(this,"message");T(this,"root");T(this,"operations");T(this,"presenceChange");T(this,"previousPresence");T(this,"reversePresenceKeys");this.id=t,this.delimiter=cu,this.root=e,this.operations=[],this.previousPresence=sn(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(t,e,n,r){return new $i(t,e,n,r)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Xi.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,e){for(const n of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class So{constructor(t){T(this,"rootObject");T(this,"elementPairMapByCreatedAt");T(this,"gcElementSetByCreatedAt");T(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Gt||e instanceof Yt)for(const n of e.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new So(xt.create(un))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const n=[];for(;e.parent;){const r=e.element.getCreatedAt(),o=e.parent.subPathOf(r);if(o===void 0)throw new ne(te.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof hi&&t.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(t){let e=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),e++};return n(t),t instanceof hi&&t.getDescendants(r=>(n(r),!1)),e}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 e of this.gcElementSetByCreatedAt){t.add(e);const n=this.elementPairMapByCreatedAt.get(e);n.element instanceof hi&&n.element.getDescendants(r=>(t.add(r.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new So(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n),o=r.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(r.parent.purge(r.element),e+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r&&(t!=null&&t.afterOrEqual(r))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Fu(i,t){const e=new Eo(i);return new Proxy(t,e.getHandlers())}class Eo{constructor(t){T(this,"context");T(this,"handlers");this.context=t,this.handlers={set:(e,n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]=${JSON.stringify(r)}`),Eo.setInternal(t,e,n,r),!0),get:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),n==="getID"?()=>e.getCreatedAt():n==="toJSON"||n==="toString"?()=>e.toJSON():n==="toJS"?()=>e.toJS():n==="toJSForTest"?()=>e.toJSForTest():wi(t,e.get(n))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),Eo.deleteInternal(t,e,n),!0)}}static setInternal(t,e,n,r){if(n.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),s=Es(t,r,o),u=e.set(n,s,o);t.registerElement(s,e),u&&t.registerRemovedElement(u),t.push(_i.create(n,s.deepcopy(),e.getCreatedAt(),o))}static buildObjectMembers(t,e){const n={};for(const[r,o]of Object.entries(e)){if(r.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const s=t.issueTimeTicket(),u=Es(t,o,s);n[r]=u}return n}static deleteInternal(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByKey(n,r);o&&(t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function Sh(i,t){const e=new rt(i,t);return new Proxy(t,e.getHandlers())}function Eh(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function xh(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class rt{constructor(t,e){T(this,"context");T(this,"handlers");T(this,"array");this.context=t,this.array=e,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return oi(t,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return oi(t,u)}:r==="getLast"?()=>oi(t,n.getLast()):r==="deleteByID"?s=>{const u=rt.deleteInternalByID(t,n,s);return oi(t,u)}:r==="insertAfter"?(s,u)=>{const c=rt.insertAfterInternal(t,n,s,u);return oi(t,c)}:r==="insertBefore"?(s,u)=>{const c=rt.insertBeforeInternal(t,n,s,u);return oi(t,c)}:r==="moveBefore"?(s,u)=>{rt.moveBeforeInternal(t,n,s,u)}:r==="moveAfter"?(s,u)=>{rt.moveAfterInternal(t,n,s,u)}:r==="moveFront"?s=>{rt.moveFrontInternal(t,n,s)}:r==="moveLast"?s=>{rt.moveLastInternal(t,n,s)}:Eh(r)?wi(t,n.get(Number(r))):r==="push"?s=>rt.pushInternal(t,n,s):r==="splice"?(s,u,...c)=>rt.splice(t,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?rt.iteratorInternal.bind(this,t,n):r==="includes"?(s,u)=>rt.includes(t,n,s,u):r==="indexOf"?(s,u)=>rt.indexOf(t,n,s,u):r==="lastIndexOf"?(s,u)=>rt.lastIndexOf(t,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>rt.toTestString(n):typeof r=="string"&&xh(r)?(...s)=>{const u=Array.from(n).map(c=>wi(t,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`array[${r}]`),rt.deleteInternalByIndex(t,n,Number.parseInt(r)),!0)}}static*iteratorInternal(t,e){for(const n of e)yield oi(t,n)}static buildArrayElements(t,e){const n=[];for(const r of e){const o=t.issueTimeTicket(),s=Es(t,r,o);n.push(s)}return n}static pushInternal(t,e,n){return rt.insertAfterInternal(t,e,e.getLastCreatedAt(),n),e.length}static moveBeforeInternal(t,e,n,r){const o=t.issueTimeTicket(),s=e.getPrevCreatedAt(n);e.moveAfter(s,r,o),t.push(ci.create(e.getCreatedAt(),s,r,o))}static moveAfterInternal(t,e,n,r){const o=t.issueTimeTicket();e.moveAfter(n,r,o),t.push(ci.create(e.getCreatedAt(),n,r,o))}static moveFrontInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getHead();e.moveAfter(o.getCreatedAt(),n,r),t.push(ci.create(e.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getLastCreatedAt();e.moveAfter(o,n,r),t.push(ci.create(e.getCreatedAt(),o,n,r))}static insertAfterInternal(t,e,n,r){const o=t.issueTimeTicket(),s=Es(t,r,o);return e.insertAfter(n,s),t.registerElement(s,e),t.push(Oo.create(e.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(t,e,n,r){return rt.insertAfterInternal(t,e,e.getPrevCreatedAt(n),r)}static deleteInternalByIndex(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByIndex(n,r);if(o)return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static deleteInternalByID(t,e,n){const r=t.issueTimeTicket(),o=e.delete(n,r);return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static splice(t,e,n,r,...o){const s=e.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 y=u;y=o)return!1;if(tt.isSupport(n))return Array.from(e).map(m=>wi(t,m)).includes(n,s);for(let c=s;c=o)return-1;if(tt.isSupport(n))return Array.from(e).map(m=>wi(t,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(tt.isSupport(n))return Array.from(e).map(m=>wi(t,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=e.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}let Ps=class{constructor(t,e){T(this,"context");T(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,n,r){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${e}->${o[1].toTestString()} c:${n}`);const s=r?Yi(r):void 0,u=this.context.issueTimeTicket(),[c,,m,y]=this.text.edit(o,n,u,s);for(const f of m)this.context.registerGCPair(f);return this.context.push(new Io(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(y)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,n){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`STYL: f:${t}->${r[0].toTestString()}, t:${e}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Yi(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 No(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([cn.fromStruct(t[0]),cn.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(te.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(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}};class Cs{constructor(t,e){T(this,"valueType");T(this,"value");T(this,"context");T(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),n=tt.of(t,e);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(eo.create(this.counter.getCreatedAt(),n,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function qa(i,t,e){const{type:n}=i,r=e.issueTimeTicket();if(n===Gr){ju(i);const{value:o}=i,s=Ct.create(pt.of(r,0),n,o);t.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!uu(s)){const m=Yi(s);u=new Xr;for(const[y,f]of Object.entries(m))u.set(y,f,r)}const c=Ct.create(pt.of(r,0),n,void 0,u);t.append(c);for(const m of o)qa(m,c,e)}}function kh(i,t){const{type:e}=t,n=i.issueTimeTicket();let r;if(t.type===Gr){const{value:o}=t;r=Ct.create(pt.of(n,0),e,o)}else if(t){const{children:o=[]}=t,{attributes:s}=t;let u;if(typeof s=="object"&&!uu(s)){const c=Yi(s);u=new Xr;for(const[m,y]of Object.entries(c))u.set(m,y,n)}r=Ct.create(pt.of(i.issueTimeTicket(),0),e,void 0,u);for(const c of o)qa(c,r,i)}return r}function ju(i){if(!i.value.length)throw new ne(te.ErrInvalidArgument,"text node cannot have empty value");return!0}function xl(i){if(!i.length)return!0;if(i[0].type===Gr)for(const e of i){const{type:n}=e;if(n!==Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together");ju(e)}else for(const e of i){const{type:n}=e;if(n===Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Ls{constructor(t){T(this,"initialRoot");T(this,"context");T(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Ct.create(pt.of(t.issueTimeTicket(),0),Ef);const e=Ct.create(pt.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)qa(n,e,t);return e}getSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),s=e?Yi(e):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(Yr.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),u=n?Yi(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const y of m)this.context.registerGCPair(y);this.context.push(Yr.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),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(Yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(t,e,n,r=0){var m;if(n.length!==0&&n[0]&&(xl(n),n[0].type!==Gr))for(const y of n){const{children:f=[]}=y;xl(f)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Gr){let y="";for(const f of n){const{value:l}=f;y+=l}s.push(Ct.create(pt.of(this.context.issueTimeTicket(),0),Gr,y))}else s=n.map(y=>y&&kh(this.context,y)).filter(y=>y);const[,u,c]=this.tree.edit([t,e],s.length?s.map(y=>y==null?void 0:y.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const y of u)this.context.registerGCPair(y);return this.context.push(_o.create(this.tree.getCreatedAt(),t,e,s.length?s:void 0,r,c,o)),!0}editByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n,r)}edit(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulk(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],n=this.tree.indexRangeToPosRange(e);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function kl(i,t){return Fu(i,t)}function oi(i,t){if(t){if(t instanceof tt)return t;if(t instanceof xt)return Fu(i,t);if(t instanceof Lt)return Sh(i,t);if(t instanceof Gt)return new Ps(i,t);if(t instanceof Rt){const e=new Cs(Un.IntegerCnt,0);return e.initialize(i,t),e}else if(t instanceof Yt){const e=new Ls;return e.initialize(i,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function wi(i,t){const e=oi(i,t);return e instanceof tt?e.getValue():e}function Es(i,t,e){let n;if(tt.isSupport(t))n=tt.of(t,e);else if(Array.isArray(t))n=Lt.create(e,rt.buildArrayElements(i,t));else if(typeof t=="object")t instanceof Ps?(n=Gt.create(Qi.create(),e),t.initialize(i,n)):t instanceof Cs?(n=Rt.create(t.getValueType(),t.getValue(),e),t.initialize(i,n)):t instanceof Ls?(n=Yt.create(t.buildRoot(i),e),t.initialize(i,n)):n=xt.create(e,Eo.buildObjectMembers(i,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return n}const Ol=50;class Oh{constructor(){T(this,"undoStack",[]);T(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Ol&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Ol&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Ih="yorkie-devtools-panel",Nh="yorkie-devtools-sdk";let Fi="disconnected";const Il=new Map,Xo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Xo);function zo(i,t){(t!=null&&t.force||Fi!=="disconnected")&&window.postMessage({source:Nh,...i},"*")}function _h(i){if(!i.isEnableDevtools()||typeof window>"u"||Il.has(i.getKey()))return;Xo.set(i.getKey(),[]);const t=i.subscribe("all",e=>{e.some(n=>n.type!==ft.StatusChanged&&n.type!==ft.Snapshot&&n.type!==ft.LocalChange&&n.type!==ft.RemoteChange&&n.type!==ft.Initialized&&n.type!==ft.Watched&&n.type!==ft.Unwatched&&n.type!==ft.PresenceChanged)||(Xo.get(i.getKey()).push(e),Fi==="synced"&&zo({msg:"doc::sync::partial",docKey:i.getKey(),event:e}))});Il.set(i.getKey(),[t]),zo({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.source)!==Ih)return;switch(e.data.msg){case"devtools::connect":if(Fi!=="disconnected")break;Fi="connected",zo({msg:"doc::available",docKey:i.getKey()}),Ne.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Fi="disconnected",Ne.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Fi="synced",zo({msg:"doc::sync::full",docKey:i.getKey(),events:Xo.get(i.getKey())}),Ne.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var si=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(si||{}),ft=(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.AuthError="auth-error",i))(ft||{}),xo=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(xo||{}),ba=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(ba||{});class Uu{constructor(t,e){T(this,"key");T(this,"status");T(this,"opts");T(this,"changeID");T(this,"checkpoint");T(this,"localChanges");T(this,"root");T(this,"clone");T(this,"eventStream");T(this,"eventStreamObserver");T(this,"onlineClients");T(this,"presences");T(this,"history");T(this,"internalHistory");T(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=So.create(),this.changeID=Lf,this.checkpoint=Rf,this.localChanges=[],this.eventStream=Th(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Oh,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},_h(this)}update(t,e){if(this.getStatus()==="removed")throw new ne(te.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)||{},e);try{const o=kl(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,t(o,new Fs(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){Ne.isEnabled(wt.Trivial)&&Ne.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ye.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:Ye.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:Ye.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,n,r){if(typeof t=="string"){if(typeof e!="function")throw new ne(te.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const u=e;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(t==="my-presence"){const u=e;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(t==="others"){const u=e;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(t==="connection"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(t==="status"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(t==="sync"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(t==="local-broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(t==="broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(t==="auth-error"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="auth-error"&&u(m)},n)}if(t==="all"){const u=e;return this.eventStream.subscribe(u,n,r)}const o=t,s=e;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const y of c.value.operations)this.isSameElementOrChildOf(y.path,o)&&m.push(y);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof t=="function"){const o=t,s=e,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(te.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const n=t.split(".");return e.split(".").every((o,s)=>o===n[s])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const e=t.hasSnapshot();e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),Ye.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),Ne.isEnabled(wt.Trivial)&&Ne.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:sn(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return _s.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.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=$i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return kl(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,n,r=-1){const{root:o,presences:s}=lt.bytesToSnapshot(n);this.root=new So(o),this.presences=s,this.changeID=this.changeID.setClocks(e.maxLamport(),e),this.clone=void 0,this.removePushedLocalChanges(r),this.applyChanges(this.localChanges,Ye.Local),this.publish([{type:"snapshot",source:Ye.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?lt.bytesToHex(n):void 0,snapshotVector:lt.versionVectorToHex(e)}}])}applyChanges(t,e){Ne.isEnabled(wt.Debug)&&Ne.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Ne.isEnabled(wt.Trivial)&&Ne.trivial(t.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` -`));for(const n of t)this.applyChange(n,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const n=[],r=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(r)){const s=t.getPresenceChange();switch(s.type){case pi.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:e,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ye.Remote,value:{clientID:r,presence:s.presence}});break;case pi.Clear:n.push({type:"unwatched",source:Ye.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const s=this.isEnableDevtools()?t.toStruct():void 0;n.push(e===Ye.Remote?{type:"remote-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,n=new Set;for(const r of e)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ye.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:n}=t.body.value,r=[];if(e===Oi.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(e===Oi.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ye.Remote,value:{clientID:n,presence:o}})}else if(e===Oi.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:s}=t.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(t){this.status=t,t==="detached"&&this.setActor(Is),this.publish([{source:t==="removed"?Ye.Remote:Ye.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:e,serverSeq:n,snapshotVector:r}=t.value;if(!e)return;this.applySnapshot(BigInt(n),lt.hexToVersionVector(r),lt.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Xi.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:n,presence:r}of t.value)e.add(n),this.presences.set(n,r);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:n}=t.value;this.addOnlineClient(e),this.presences.set(e,n);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:n}=t.value;this.presences.set(e,n)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new ne(te.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let n=this.getRoot();for(const r of e)if(n=n[r],n===void 0)return;return n}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?sn(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?sn(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?sn(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:sn(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:sn(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,n)=>e.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const n=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=$i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Fs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.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:Ye.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:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=$i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Fs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.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:Ye.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:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,n){const r={type:"local-broadcast",value:{topic:t,payload:e},options:n};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function Ph(i,t){let e=t;return{authInterceptor:o=>async s=>(i&&s.header.set("x-api-key",i),e&&s.header.set("authorization",e),await o(s)),setToken:o=>{e=o}}}const Ch="yorkie-js-sdk",Lh="0.5.6",Rh="Yorkie JS SDK",Dh="./src/yorkie.ts",Bh={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Mh=["dist"],qh={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"},Fh={node:">=18.0.0",npm:">=7.1.0"},jh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Uh={name:"hackerwins",email:"susukang98@gmail.com"},Jh="Apache-2.0",$h={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},zh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Vh={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},Kh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Nl={name:Ch,version:Lh,description:Rh,main:Dh,publishConfig:Bh,files:Mh,scripts:qh,engines:Fh,repository:jh,author:Uh,license:Jh,bugs:$h,homepage:zh,devDependencies:Vh,dependencies:Kh};function Hh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Nl.name+"/"+Nl.version),await i(t))}const Wh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Qo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Qo||{});const Vo={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},$s={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ju{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"authTokenInjector");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"setAuthToken");T(this,"taskQueue");T(this,"processing",!1);T(this,"keepalive",!1);e=e||Vo,this.key=e.key?e.key:qu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.authTokenInjector=e.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration??Vo.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay??Vo.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay??Vo.retrySyncLoopDelay;const{authInterceptor:n,setToken:r}=Ph(this.apiKey);this.setAuthToken=r,this.rpcClient=Kc(mf,pf({baseUrl:t,interceptors:[n,Hh()],fetch:(o,s)=>{const u={...s,keepalive:this.keepalive};return fetch(o,u)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),Ne.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw Ne.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const e=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),Ne.info(`[DC] c"${this.getKey()}" deactivated`)}catch(n){throw Ne.error(`[DC] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n}};if(t.keepalive){this.keepalive=!0;const n=e();return this.keepalive=!1,n}return this.enqueueTask(e)}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==si.Detached)throw new ne(te.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,s)=>s.set(e.initialPresence||{}));const n=t.subscribe("local-broadcast",async o=>{var y;const{topic:s,payload:u}=o.value,c=(y=o.options)==null?void 0:y.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(f){f instanceof Error&&(c==null||c(f))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:lt.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=lt.fromChangePack(o.changePack);if(t.applyChangePack(s),t.getStatus()===si.Removed)return t;t.applyStatus(si.Attached),this.attachmentMap.set(t.getKey(),new wh(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ne.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const u=t.getRootObject();if(e.initialRoot){const c=e.initialRoot;t.update(m=>{for(const[y,f]of Object.entries(c))if(!u.has(y)){const l=y;m[l]=f}})}return t}).catch(async o=>{throw Ne.error(`[AD] c:"${this.getKey()}" err :`,o),await this.handleConnectError(o),o}))}detach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:lt.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=lt.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==si.Removed&&t.applyStatus(si.Detached),this.detachInternal(t.getKey()),Ne.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async r=>{throw Ne.error(`[DD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}async changeSyncMode(t,e){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const r=n.syncMode;return r===e?t:(n.changeSyncMode(e),e==="manual"?(n.cancelWatchStream(),t):(e==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(async n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const e=[];for(const[,n]of this.attachmentMap)e.push(this.syncInternal(n,n.syncMode));return Promise.all(e).catch(async n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n})})}remove(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const n=lt.toChangePack(t.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=lt.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ne.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async r=>{throw Ne.error(`[RD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}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,e,n,r){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);if(!Wh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??$s.maxRetries,u=$s.maxBackoff;let c=0;const m=f=>Math.min($s.initialRetryInterval*2**f,u),y=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Ne.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(async f=>{if(Ne.error(`[BC] c:"${this.getKey()}" err:`,f),await this.handleConnectError(f))if(f instanceof Ze&&Mi(f)===te.ErrUnauthenticated&&o.doc.publish([{type:ft.AuthError,value:{reason:ao(f).reason,method:"Broadcast"}}]),cy(),m(c-1)),Ne.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ne.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),f;else throw f}));return y()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ne.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,e.push(this.syncInternal(n,n.syncMode).catch(async r=>{throw r instanceof Ze&&Mi(r)===te.ErrUnauthenticated&&n.doc.publish([{type:ft.AuthError,value:{reason:ao(r).reason,method:"PushPull"}}]),r})));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async n=>{Ne.error(`[SL] c:"${this.getKey()}" sync failed:`,n),await this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ne.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(te.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:r.signal});return e.doc.publish([{type:ft.ConnectionChanged,value:xo.Connected}]),Ne.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(e,m),m.body.case==="initialization"&&s([o,r])}catch(m){e.doc.resetOnlineClients(),e.doc.publish([{type:ft.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:ft.ConnectionChanged,value:xo.Disconnected}]),Ne.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(m)?(m instanceof Ze&&Mi(m)===te.ErrUnauthenticated&&e.doc.publish([{type:ft.AuthError,value:{reason:ao(m).reason,method:"WatchDocuments"}}]),n()):this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===Oi.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(si.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:n,docID:r}=t,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:lt.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=lt.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:ft.SyncStatusChanged,value:ba.Synced}]),n.getStatus()===si.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ne.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(async s=>{throw n.publish([{type:ft.SyncStatusChanged,value:ba.SyncFailed}]),Ne.error(`[PP] c:"${this.getKey()}" err :`,s),s})}async handleConnectError(t){if(!(t instanceof Ze))return!1;if(t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable)return!0;if(Mi(t)===te.ErrUnauthenticated){if(this.authTokenInjector){const e=await this.authTokenInjector(ao(t).reason);this.setAuthToken(e)}return!0}return(Mi(t)===te.ErrClientNotActivated||Mi(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(t){return new Promise((e,n)=>{this.taskQueue.push(()=>t().then(e).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{Ne.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const zs={Client:Ju,Document:Uu,Primitive:tt,Text:Ps,Counter:Cs,Tree:Ls,LogLevel:wt,setLogLevel:Mu,IntType:Un.IntegerCnt,LongType:Un.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ju,Document:Uu,Primitive:tt,Text:Ps,Counter:Cs,Tree:Ls,LogLevel:wt,setLogLevel:Mu,IntType:Un.IntegerCnt,LongType:Un.LongCnt});var Gh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $u(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var zu={exports:{}};/*! +`));for(const n of t)this.applyChange(n,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const n=[],r=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(r)){const s=t.getPresenceChange();switch(s.type){case pi.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:e,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ye.Remote,value:{clientID:r,presence:s.presence}});break;case pi.Clear:n.push({type:"unwatched",source:Ye.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const s=this.isEnableDevtools()?t.toStruct():void 0;n.push(e===Ye.Remote?{type:"remote-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,n=new Set;for(const r of e)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ye.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:n}=t.body.value,r=[];if(e===Oi.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(e===Oi.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ye.Remote,value:{clientID:n,presence:o}})}else if(e===Oi.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:s}=t.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(t){this.status=t,t==="detached"&&this.setActor(Is),this.publish([{source:t==="removed"?Ye.Remote:Ye.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:e,serverSeq:n,snapshotVector:r}=t.value;if(!e)return;this.applySnapshot(BigInt(n),lt.hexToVersionVector(r),lt.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Xi.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:n,presence:r}of t.value)e.add(n),this.presences.set(n,r);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:n}=t.value;this.addOnlineClient(e),this.presences.set(e,n);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:n}=t.value;this.presences.set(e,n)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new ne(te.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let n=this.getRoot();for(const r of e)if(n=n[r],n===void 0)return;return n}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?sn(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?sn(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?sn(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:sn(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:sn(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,n)=>e.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const n=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=$i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Fs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.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:Ye.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:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=$i.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Fs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.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:Ye.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:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,n){const r={type:"local-broadcast",value:{topic:t,payload:e},options:n};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function Ph(i,t){let e=t;return{authInterceptor:o=>async s=>(i&&s.header.set("x-api-key",i),e&&s.header.set("authorization",e),await o(s)),setToken:o=>{e=o}}}const Ch="yorkie-js-sdk",Lh="0.5.7",Rh="Yorkie JS SDK",Dh="./src/yorkie.ts",Bh={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Mh=["dist"],qh={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"},Fh={node:">=18.0.0",npm:">=7.1.0"},jh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Uh={name:"hackerwins",email:"susukang98@gmail.com"},Jh="Apache-2.0",$h={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},zh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Vh={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},Kh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Nl={name:Ch,version:Lh,description:Rh,main:Dh,publishConfig:Bh,files:Mh,scripts:qh,engines:Fh,repository:jh,author:Uh,license:Jh,bugs:$h,homepage:zh,devDependencies:Vh,dependencies:Kh};function Hh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Nl.name+"/"+Nl.version),await i(t))}const Wh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Qo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Qo||{});const Vo={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},$s={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ju{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"authTokenInjector");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"setAuthToken");T(this,"taskQueue");T(this,"processing",!1);T(this,"keepalive",!1);e=e||Vo,this.key=e.key?e.key:qu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.authTokenInjector=e.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration??Vo.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay??Vo.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay??Vo.retrySyncLoopDelay;const{authInterceptor:n,setToken:r}=Ph(this.apiKey);this.setAuthToken=r,this.rpcClient=Kc(mf,pf({baseUrl:t,interceptors:[n,Hh()],fetch:(o,s)=>{const u={...s,keepalive:this.keepalive};return fetch(o,u)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const t=await this.authTokenInjector();this.setAuthToken(t)}return 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(),Ne.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(async t=>{throw Ne.error(`[AC] c:"${this.getKey()}" err :`,t),await this.handleConnectError(t),t}))}deactivate(t={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const e=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),Ne.info(`[DC] c"${this.getKey()}" deactivated`)}catch(n){throw Ne.error(`[DC] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n}};if(t.keepalive){this.keepalive=!0;const n=e();return this.keepalive=!1,n}return this.enqueueTask(e)}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==si.Detached)throw new ne(te.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,s)=>s.set(e.initialPresence||{}));const n=t.subscribe("local-broadcast",async o=>{var y;const{topic:s,payload:u}=o.value,c=(y=o.options)==null?void 0:y.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(f){f instanceof Error&&(c==null||c(f))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:lt.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=lt.fromChangePack(o.changePack);if(t.applyChangePack(s),t.getStatus()===si.Removed)return t;t.applyStatus(si.Attached),this.attachmentMap.set(t.getKey(),new wh(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ne.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const u=t.getRootObject();if(e.initialRoot){const c=e.initialRoot;t.update(m=>{for(const[y,f]of Object.entries(c))if(!u.has(y)){const l=y;m[l]=f}})}return t}).catch(async o=>{throw Ne.error(`[AD] c:"${this.getKey()}" err :`,o),await this.handleConnectError(o),o}))}detach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:lt.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=lt.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==si.Removed&&t.applyStatus(si.Detached),this.detachInternal(t.getKey()),Ne.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(async r=>{throw Ne.error(`[DD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}async changeSyncMode(t,e){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const r=n.syncMode;return r===e?t:(n.changeSyncMode(e),e==="manual"?(n.cancelWatchStream(),t):(e==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(async n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const e=[];for(const[,n]of this.attachmentMap)e.push(this.syncInternal(n,n.syncMode));return Promise.all(e).catch(async n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),await this.handleConnectError(n),n})})}remove(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const n=lt.toChangePack(t.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=lt.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ne.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(async r=>{throw Ne.error(`[RD] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}))}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,e,n,r){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);if(!Wh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??$s.maxRetries,u=$s.maxBackoff;let c=0;const m=f=>Math.min($s.initialRetryInterval*2**f,u),y=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Ne.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(async f=>{if(Ne.error(`[BC] c:"${this.getKey()}" err:`,f),await this.handleConnectError(f))if(f instanceof Ze&&Mi(f)===te.ErrUnauthenticated&&o.doc.publish([{type:ft.AuthError,value:{reason:ao(f).reason,method:"Broadcast"}}]),cy(),m(c-1)),Ne.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ne.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),f;else throw f}));return y()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ne.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,e.push(this.syncInternal(n,n.syncMode).catch(async r=>{throw r instanceof Ze&&Mi(r)===te.ErrUnauthenticated&&n.doc.publish([{type:ft.AuthError,value:{reason:ao(r).reason,method:"PushPull"}}]),r})));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(async n=>{Ne.error(`[SL] c:"${this.getKey()}" sync failed:`,n),await this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ne.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(te.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:r.signal});return e.doc.publish([{type:ft.ConnectionChanged,value:xo.Connected}]),Ne.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(e,m),m.body.case==="initialization"&&s([o,r])}catch(m){e.doc.resetOnlineClients(),e.doc.publish([{type:ft.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:ft.ConnectionChanged,value:xo.Disconnected}]),Ne.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(m)?(m instanceof Ze&&Mi(m)===te.ErrUnauthenticated&&e.doc.publish([{type:ft.AuthError,value:{reason:ao(m).reason,method:"WatchDocuments"}}]),n()):this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===Oi.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(si.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:n,docID:r}=t,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:lt.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=lt.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:ft.SyncStatusChanged,value:ba.Synced}]),n.getStatus()===si.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ne.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(async s=>{throw n.publish([{type:ft.SyncStatusChanged,value:ba.SyncFailed}]),Ne.error(`[PP] c:"${this.getKey()}" err :`,s),s})}async handleConnectError(t){if(!(t instanceof Ze))return!1;if(t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable)return!0;if(Mi(t)===te.ErrUnauthenticated){if(this.authTokenInjector){const e=await this.authTokenInjector(ao(t).reason);this.setAuthToken(e)}return!0}return(Mi(t)===te.ErrClientNotActivated||Mi(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1}enqueueTask(t){return new Promise((e,n)=>{this.taskQueue.push(()=>t().then(e).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{Ne.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const zs={Client:Ju,Document:Uu,Primitive:tt,Text:Ps,Counter:Cs,Tree:Ls,LogLevel:wt,setLogLevel:Mu,IntType:Un.IntegerCnt,LongType:Un.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ju,Document:Uu,Primitive:tt,Text:Ps,Counter:Cs,Tree:Ls,LogLevel:wt,setLogLevel:Mu,IntType:Un.IntegerCnt,LongType:Un.LongCnt});var Gh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function $u(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var zu={exports:{}};/*! * Quill Editor v1.3.7 * https://quilljs.com/ * Copyright (c) 2014, Jason Chen diff --git a/examples/vanilla-quill/index.html b/examples/vanilla-quill/index.html index 726213481..450df15f6 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-C3LyZcN6.js b/examples/vuejs-kanban/assets/index-DAhQftBf.js similarity index 99% rename from examples/vuejs-kanban/assets/index-C3LyZcN6.js rename to examples/vuejs-kanban/assets/index-DAhQftBf.js index cb1af13f1..1c2f8aed7 100644 --- a/examples/vuejs-kanban/assets/index-C3LyZcN6.js +++ b/examples/vuejs-kanban/assets/index-DAhQftBf.js @@ -20,4 +20,4 @@ var Qf=Object.defineProperty;var eh=(n,e,t)=>e in n?Qf(n,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 X(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}X.prototype.__isLong__;Object.defineProperty(X.prototype,"__isLong__",{value:!0});function Oe(n){return(n&&n.__isLong__)===!0}function Mu(n){var e=Math.clz32(n&-n);return n?31-e:e}X.isLong=Oe;var $u={},Uu={};function Vr(n,e){var t,r,s;return e?(n>>>=0,(s=0<=n&&n<256)&&(r=Uu[n],r)?r:(t=Q(n,0,!0),s&&(Uu[n]=t),t)):(n|=0,(s=-128<=n&&n<128)&&(r=$u[n],r)?r:(t=Q(n,n<0?-1:0,!1),s&&($u[n]=t),t))}X.fromInt=Vr;function at(n,e){if(isNaN(n))return e?Qn:yt;if(e){if(n<0)return Qn;if(n>=wf)return Af}else{if(n<=-zu)return $e;if(n+1>=zu)return Tf}return n<0?at(-n,e).neg():Q(n%gs|0,n/gs|0,e)}X.fromNumber=at;function Q(n,e,t){return new X(n,e,t)}X.fromBits=Q;var to=Math.pow;function sc(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?Qn:yt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return sc(n.substring(1),e,t).neg();for(var s=at(to(t,8)),i=yt,o=0;o>>0:this.low};E.toNumber=function(){return this.unsigned?(this.high>>>0)*gs+(this.low>>>0):this.high*gs+(this.low>>>0)};E.toString=function(e){if(e=e||10,e<2||36>>0,h=l.toString(e);if(o=u,o.isZero())return h+a;for(;h.length<6;)h="0"+h;a=""+h+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($e)?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 Oe(e)||(e=It(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(Oe(e)||(e=It(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($e)?$e:this.not().add(Zr)};E.neg=E.negate;E.add=function(e){Oe(e)||(e=It(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,u=e.low>>>16,l=e.low&65535,h=0,d=0,v=0,p=0;return p+=i+l,v+=p>>>16,p&=65535,v+=s+u,d+=v>>>16,v&=65535,d+=r+a,h+=d>>>16,d&=65535,h+=t+o,h&=65535,Q(v<<16|p,h<<16|d,this.unsigned)};E.subtract=function(e){return Oe(e)||(e=It(e)),this.add(e.neg())};E.sub=E.subtract;E.multiply=function(e){if(this.isZero())return this;if(Oe(e)||(e=It(e)),ot){var t=ot.mul(this.low,this.high,e.low,e.high);return Q(t,ot.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Qn:yt;if(this.eq($e))return e.isOdd()?$e:yt;if(e.eq($e))return this.isOdd()?$e: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(Ku)&&e.lt(Ku))return at(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,u=e.high&65535,l=e.low>>>16,h=e.low&65535,d=0,v=0,p=0,A=0;return A+=o*h,p+=A>>>16,A&=65535,p+=i*h,v+=p>>>16,p&=65535,p+=o*l,v+=p>>>16,p&=65535,v+=s*h,d+=v>>>16,v&=65535,v+=i*l,d+=v>>>16,v&=65535,v+=o*u,d+=v>>>16,v&=65535,d+=r*h+s*l+i*u+o*a,d&=65535,Q(p<<16|A,d<<16|v,this.unsigned)};E.mul=E.multiply;E.divide=function(e){if(Oe(e)||(e=It(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 Q(t,ot.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Qn:yt;var r,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Qn;if(e.gt(this.shru(1)))return bf;i=Qn}else{if(this.eq($e)){if(e.eq(Zr)||e.eq(ka))return $e;if(e.eq($e))return Zr;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(yt)?e.isNegative()?Zr:ka:(s=this.sub(e.mul(r)),i=r.add(s.div(e)),i)}else if(e.eq($e))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();i=yt}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),u=a<=48?1:to(2,a-48),l=at(r),h=l.mul(e);h.isNegative()||h.gt(s);)r-=u,l=at(r,this.unsigned),h=l.mul(e);l.isZero()&&(l=Zr),i=i.add(l),s=s.sub(h)}return i};E.div=E.divide;E.modulo=function(e){if(Oe(e)||(e=It(e)),ot){var t=(this.unsigned?ot.rem_u:ot.rem_s)(this.low,this.high,e.low,e.high);return Q(t,ot.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};E.mod=E.modulo;E.rem=E.modulo;E.not=function(){return Q(~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?Mu(this.low):Mu(this.high)+32};E.ctz=E.countTrailingZeros;E.and=function(e){return Oe(e)||(e=It(e)),Q(this.low&e.low,this.high&e.high,this.unsigned)};E.or=function(e){return Oe(e)||(e=It(e)),Q(this.low|e.low,this.high|e.high,this.unsigned)};E.xor=function(e){return Oe(e)||(e=It(e)),Q(this.low^e.low,this.high^e.high,this.unsigned)};E.shiftLeft=function(e){return Oe(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low<>>32-e,this.unsigned):Q(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Q(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};E.shr=E.shiftRight;E.shiftRightUnsigned=function(e){return Oe(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Q(this.high,0,this.unsigned):Q(this.high>>>e-32,0,this.unsigned)};E.shru=E.shiftRightUnsigned;E.shr_u=E.shiftRightUnsigned;E.rotateLeft=function(e){var t;return Oe(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Q(this.high<>>t,this.low<>>t,this.unsigned))};E.rotl=E.rotateLeft;E.rotateRight=function(e){var t;return Oe(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Q(this.low<>>e,this.high<>>e,this.unsigned))};E.rotr=E.rotateRight;E.toSigned=function(){return this.unsigned?Q(this.low,this.high,!1):this};E.toUnsigned=function(){return this.unsigned?this:Q(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]};X.fromBytes=function(e,t,r){return r?X.fromBytesLE(e,t):X.fromBytesBE(e,t)};X.fromBytesLE=function(e,t){return new X(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};X.fromBytesBE=function(e,t){return new X(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var Te=(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))(Te||{});class he extends Xs{constructor(t,r){super(r);c(this,"valueType");c(this,"value");this.valueType=he.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new he(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 X.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(X.fromBytesLE(Array.from(r),!0).toNumber());default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${Ut(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=he.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 X)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return he.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=X.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class no extends vf{constructor(t){super(t);c(this,"prev");c(this,"next");this.value=t}static createAfter(t,r){const s=new no(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 Hs{constructor(){c(this,"dummyHead");c(this,"last");c(this,"nodeMapByIndex");c(this,"nodeMapByCreatedAt");const e=he.of(0,bt);e.setRemovedAt(bt),this.dummyHead=new no(e),this.last=this.dummyHead,this.nodeMapByIndex=new Ws,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Hs}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new w(y.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=no.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 w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new w(y.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 w(y.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 We extends yr{constructor(t,r){super(t);c(this,"elements");this.elements=r}static create(t,r){if(!r)return new We(t,Hs.create());const s=Hs.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new We(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 yr&&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({...A,value:A.value?{attributes:ss(A.value.getAttributes()),content:A.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,p,d,[l,l]]}setStyle(t,r,s,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,u]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),l=[],h=this.rgaTreeSplit.findBetween(u,a),d=new Map,v=[];for(const A of h){const I=A.getCreatedAt().getActorID();let D,L=0n;if(o===void 0&&i===void 0?L=Ds:o.size()>0?L=o.get(I)?o.get(I):0n:D=i.has(I)?i.get(I):bt,A.canStyle(s,D,L)){const $=d.get(I),V=A.getCreatedAt();(!$||V.after($))&&d.set(I,V),v.push(A)}}const p=[];for(const A of v){if(A.isRemoved())continue;const[I,D]=this.rgaTreeSplit.findIndexesFromRange(A.createPosRange());l.push({type:"style",actor:s.getActorID(),from:I,to:D,value:{attributes:ss(r)}});for(const[L,$]of Object.entries(r)){const[V]=A.getValue().setAttr(L,$,s);V!==void 0&&p.push({parent:A.getValue(),child:V})}}return[d,p,l]}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:ss(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new ut(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 Qs extends At{constructor(t,r,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"content");c(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,u){return new Qs(t,r,s,i,o,a,u)}execute(t,r,s){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof ut))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=i,[,a,u]=o.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor,s);for(const l of u)t.registerGCPair(l);return{opInfos:a.map(({from:l,to:h,value:d})=>({type:"edit",from:l,to:h,value:d,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 ei extends At{constructor(t,r,s,i,o,a){super(t,a);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,r,s,i,o,a){return new ei(t,r,s,i,o,a)}execute(t,r,s){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof ut))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const o=i,[,a,u]=o.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor,s);for(const l of a)t.registerGCPair(l);return{opInfos:u.map(({from:l,to:h,value:d})=>({type:"style",from:l,to:h,value:d,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 tp=2,np="root",er="text";function Ss(n,e){let t=0;const r=n.children;for(let s=0;s0)throw new w(y.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===er}get paddedSize(){return this.size+(this.isText?0:tp)}isAncestorOf(e){return sp(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 w(y.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 w(y.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 w(y.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new w(y.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 w(y.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new w(y.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 w(y.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 sp(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var be=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(be||{});function If(n,e,t,r){if(e>t)throw new w(y.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new w(y.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new w(y.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||u)&&r([i,i.isText?"Text":"Start"],l),If(i,Math.max(0,o),Math.min(a,i.size),r),l&&r([i,"End"],l)}s+=i.paddedSize}}function Sf(n,e,t=0){for(const r of n.children)Sf(r,e,t+1);e(n,t)}function bo(n,e,t=0){for(const r of n._children)bo(r,e,t+1);e(n,t)}function Ea(n,e,t=!0){if(e>n.size)throw new w(y.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 Ea(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 Ea(i,e-s-1,t);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function xf(n){return n.isText||n.children.length===0?n:xf(n.children[0])}function ip(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 cp(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 vt{constructor(e,t){c(this,"parentID");c(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new vt(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],vt.of(r.id,xe.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return vt.of(xe.of(ct.fromStruct(e.parentID.createdAt),e.parentID.offset),xe.of(ct.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 w(y.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 xe{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new xe(e,t)}static fromStruct(e){return xe.of(ct.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 w(y.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new w(y.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 je(xe.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new je(xe.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,s){return(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=s)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r,s){return this.isText?!1:(r?!this.getCreatedAt().after(r):this.getCreatedAt().getLamport()<=s)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new sr);const s=[];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 Ca(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(Ca)};return n.attrs&&(e.attributes=ss((t=n.attrs)==null?void 0:t.toObject())),e}function ic(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()}="${Ut(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>ic(t)).join("")}`}function Ef(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(Ef),size:n.size,isRemoved:n.isRemoved}}class lt extends Xs{constructor(t,r){super(r);c(this,"indexTree");c(this,"nodeMapByID");this.indexTree=new op(t),this.nodeMapByID=new kf(xe.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,r){return new lt(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,u=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const l=u.allChildren,h=a?0:l.indexOf(o)+1;for(let d=h;d{const D=I.getCreatedAt().getActorID();let L,$=0n;if(o===void 0&&i===void 0?$=Ds:o.size()>0?$=o.get(D)?o.get(D):0n:L=i.has(D)?i.get(D):bt,I.canStyle(s,L,$)&&r){const V=p.get(D),U=I.getCreatedAt();(!V||U.after(V))&&p.set(D,U);const W=I.setAttrs(r,s),ee=W.reduce((Ee,[,Ie])=>(Ie&&(Ee[Ie.getKey()]=v[Ie.getKey()]),Ee),{}),oe=I.parent,te=I.prevSibling||I.parent;Object.keys(ee).length>0&&d.push({type:"style",from:this.toIndex(oe,te),to:this.toIndex(I,I),fromPath:this.toPath(oe,te),toPath:this.toPath(I,I),actor:s.getActorID(),value:ee});for(const[Ee]of W)Ee&&A.push({parent:I,child:Ee})}}),[p,A,d]}removeStyle(t,r,s,i,o){const[a,u]=this.findNodesAndSplitText(t[0],s),[l,h]=this.findNodesAndSplitText(t[1],s),d=[],v=new Map,p=[];return this.traverseInPosRange(a,u,l,h,([A])=>{const I=A.getCreatedAt().getActorID();let D,L=0n;if(o===void 0&&i===void 0?L=Ds:o.size()>0?L=o.get(I)?o.get(I):0n:D=i.has(I)?i.get(I):bt,A.canStyle(s,D,L)&&r){const $=v.get(I),V=A.getCreatedAt();(!$||V.after($))&&v.set(I,V),A.attrs||(A.attrs=new sr);for(const ee of r){const oe=A.attrs.remove(ee,s);for(const te of oe)p.push({parent:A,child:te})}const U=A.parent,W=A.prevSibling||A.parent;d.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(U,W),to:this.toIndex(A,A),fromPath:this.toPath(U,W),toPath:this.toPath(A,A),value:r})}}),[v,p,d]}edit(t,r,s,i,o,a,u){const[l,h]=this.findNodesAndSplitText(t[0],i),[d,v]=this.findNodesAndSplitText(t[1],i),p=this.toIndex(l,h),A=this.toPath(l,h),I=[],D=[],L=[],$=new Map;this.traverseInPosRange(l,h,d,v,([W,ee],oe)=>{if(ee===be.Start&&!oe)for(const Ge of W.children)L.push(Ge);const te=W.getCreatedAt().getActorID();let Ee,Ie=0n;if(u===void 0&&a===void 0?Ie=Ds:u.size()>0?Ie=u.get(te)?u.get(te):0n:Ee=a.has(te)?a.get(te):bt,W.canDelete(i,Ee,Ie)||I.includes(W.parent)){const Ge=$.get(te),Ir=W.getCreatedAt();(!Ge||Ir.after(Ge))&&$.set(te,Ir),(ee===be.Text||ee===be.Start)&&I.push(W),D.push([W,ee])}});const V=this.makeDeletionChanges(D,i),U=[];for(const W of I)W.remove(i),W.isRemoved&&U.push({parent:this,child:W});for(const W of L)W.removedAt||l.append(W);if(s>0){let W=0,ee=l,oe=h;for(;W{l.isRemoved&&(te.remove(i),U.push({parent:this,child:te})),this.nodeMapByID.put(te.id,te)}),oe.isRemoved||W.push(oe);if(W.length){const oe=W.map(te=>Ca(te));V.length&&V[V.length-1].from===p?V[V.length-1].value=oe:V.push({type:"content",from:p,to:p,fromPath:A,toPath:A,actor:i.getActorID(),value:oe})}}return[V,U,$]}editT(t,r,s,i,o){const a=this.findPos(t[0]),u=this.findPos(t[1]);this.edit([a,u],r,s,i,o)}move(t,r,s){throw new w(y.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 vt.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 ic(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 p,A,I,D;let u,l,h;const d=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;d&&(u=this.indexTree.indexOf(d),l=this.indexTree.treePosToPath(d),h=vt.fromTreePos(d).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(p=s.removedAt)==null?void 0:p.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(I=s.insNextID)==null?void 0:I.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?ss((D=s.attrs)==null?void 0:D.toObject()):void 0,index:u,path:l,pos:h};for(let L=0;L0&&L===s[s.length-1].to?(s[s.length-1].to=$,s[s.length-1].toPath=this.toPath(D,p)):s.push({type:"content",from:L,to:$,fromPath:this.toPath(I,d),toPath:this.toPath(D,p),actor:r.getActorID()}))}return s.reverse()}findRightToken([t,r]){if(r===be.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?be.Text:be.Start]:[t,be.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,be.End];const a=i[o+1];return[a,a.isText?be.Text:be.Start]}findLeftToken([t,r]){if(r===be.End){const u=t.allChildren;if(u.length>0){const l=u[u.length-1];return[l,l.isText?be.Text:be.End]}return[t,be.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,be.Start];const a=i[o-1];return[a,a.isText?be.Text:be.End]}}class ti extends At{constructor(t,r,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"contents");c(this,"splitLevel");c(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,u){return new ti(t,r,s,i,o,a,u)}execute(t,r,s){var h;const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof lt))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=this.getExecutedAt(),a=i,[u,l]=a.edit([this.fromPos,this.toPos],(h=this.contents)==null?void 0:h.map(d=>d.deepcopy()),this.splitLevel,o,(()=>{let d=o.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>ct.of(o.getLamport(),++d,o.getActorID())})(),this.maxCreatedAtMapByActor,s);for(const d of l)t.registerGCPair(d);return{opInfos:u.map(({from:d,to:v,value:p,splitLevel:A,fromPath:I,toPath:D})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:d,to:v,value:p,splitLevel:A,fromPath:I,toPath:D}))}}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=>ic(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class is{constructor(e){c(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}unset(e){this.vector.delete(e)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,s]of e){const i=this.vector.get(r),o=i&&i>s?i:s;t.set(r,o)}for(const[r,s]of this){const i=e.get(r),o=i&&i>s?i:s;t.set(r,o)}return new is(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new is(e)}filter(e){const t=new Map;for(const[r]of e){const s=this.vector.get(r);s!==void 0&&t.set(r,s)}return new is(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const lp=new is(new Map);class _n{constructor(e,t,r,s,i){c(this,"clientSeq");c(this,"serverSeq");c(this,"lamport");c(this,"actor");c(this,"versionVector");this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=s,this.actor=r}static of(e,t,r,s,i){return new _n(e,t,r,s,i)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new _n(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n;let r=e.versionVector;r.size()===0&&(r=r.deepcopy(),r.set(e.actor,e.lamport));const s=this.versionVector.max(r),i=new _n(this.clientSeq,t,this.actor,s);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e+1n:this.lamport+1n;t.unset(wo);const s=this.versionVector.max(t);return s.set(this.actor,r),_n.of(this.clientSeq,r,this.actor,s)}createTimeTicket(e){return ct.of(this.lamport,e,this.actor)}setActor(e){return new _n(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new _n(this.clientSeq,this.lamport,this.actor,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}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const fp=new _n(0,0n,wo,lp);class ms{constructor({id:e,operations:t,presenceChange:r,message:s}){c(this,"id");c(this,"operations");c(this,"presenceChange");c(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 ms({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,this.id.getVersionVector());if(!a)continue;const{opInfos:u,reverseOp:l}=a;s.push(...u),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===Tr.Put?t.set(this.id.getActorID(),dt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}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:t,operations:r,presenceChange:s,message:i}=e;return ms.create({id:ye.bytesToChangeID(ye.hexToBytes(t)),operations:r==null?void 0:r.map(o=>ye.bytesToOperation(ye.hexToBytes(o))),presenceChange:s,message:i})}}class To{constructor(e,t,r,s,i,o,a){c(this,"documentKey");c(this,"checkpoint");c(this,"isRemoved");c(this,"changes");c(this,"snapshot");c(this,"minSyncedTicket");c(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=s,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=i}static create(e,t,r,s,i,o,a){return new To(e,t,r,s,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}getVersionVector(){return this.versionVector}}class os{constructor(e,t){c(this,"serverSeq");c(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new os(e,t)}increaseClientSeq(e){return e===0?this:new os(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return os.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==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const hp=new os(0n,0);class zt{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new zt(e,t)}static fromStruct(e){return zt.of(ct.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 zt(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 dp=zt.of(bt,0);class Tt{constructor(e,t){c(this,"id");c(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Tt(e,t)}static fromStruct(e){const t=zt.fromStruct(e.id);return Tt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return zt.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 vr extends vf{constructor(t,r,s){super(r);c(this,"id");c(this,"removedAt");c(this,"prev");c(this,"next");c(this,"insPrev");c(this,"insNext");this.id=t,this.removedAt=s}static create(t,r){return new vr(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 w(y.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,s){if(!e.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(e,t,r,s),a=new Map,u=new Map,l=this.makeChanges(o,t);for(const h of i){const d=h.getCreatedAt().getActorID();(!a.has(d)||h.getID().getCreatedAt().after(a.get(d)))&&a.set(d,h.getID().getCreatedAt()),u.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(o),[l,a,u]}filterNodes(e,t,r,s){const i=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const h=l.getCreatedAt().getActorID();let d,v=0n;s===void 0&&r===void 0?v=Ds:s.size()>0?v=s.get(h)?s.get(h):0n:d=r.has(h)?r.get(h):bt,l.canDelete(t,d,v)?i.push(l):o.push(l)}return o.push(u),[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 Kt=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Kt||{});class He extends Xs{constructor(t,r,s){super(s);c(this,"valueType");c(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=X.fromNumber(r).toInt():this.value=Vu(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=X.fromNumber(r):this.value=r;break;default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,s){return new He(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 X.fromBytesLE(Array.from(r));default:throw new w(y.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=He.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 X?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!!He.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 w(y.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()===Te.Long?this.value=this.value+t.getValue().toInt():this.value=X.fromNumber(this.value+Vu(t.getValue())).toInt(),this}}class ys extends At{constructor(t,r,s){super(t,s);c(this,"value");this.value=r}static create(t,r,s){return new ys(t,r,s)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof He))throw new w(y.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()===Te.Long?t.getValue().multiply(-1):t.getValue()*-1;return ys.create(this.getParentCreatedAt(),he.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class tr extends At{constructor(t,r,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");c(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 tr(t,r,s,i,o,[],a)}static createTreeRemoveStyleOperation(t,r,s,i,o,a){return new tr(t,r,s,i,new Map,o,a)}execute(t,r,s){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof lt))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const o=i;let a,u;if(this.attributes.size){const l={};[...this.attributes].forEach(([h,d])=>l[h]=d),[,u,a]=o.style([this.fromPos,this.toPos],l,this.getExecutedAt(),this.maxCreatedAtMapByActor,s)}else{const l=this.attributesToRemove;[,u,a]=o.removeStyle([this.fromPos,this.toPos],l,this.getExecutedAt(),this.maxCreatedAtMapByActor,s)}for(const l of u)t.registerGCPair(l);return{opInfos:a.map(({from:l,to:h,value:d,fromPath:v,toPath:p})=>({type:"tree-style",from:l,to:h,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:v,toPath:p,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 gp(n){const e=new nc,t=e.data;for(const[r,s]of Object.entries(n))t[r]=JSON.stringify(s);return e}function mp(n){if(n.type===Tr.Put)return new Vs({type:qr.PUT,presence:gp(n.presence)});if(n.type===Tr.Clear)return new Vs({type:qr.CLEAR});throw new w(y.ErrUnimplemented,"unimplemented type")}function pp(n){return new mf({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function Cf(n){return new yo({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:pc(n.getActorID()),versionVector:oc(n.getVersionVector())})}function J(n){if(n)return new F({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:pc(n.getActorID())})}function oc(n){if(!n)return;const e=new vo;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function Nf(n){switch(n){case Te.Null:return G.NULL;case Te.Boolean:return G.BOOLEAN;case Te.Integer:return G.INTEGER;case Te.Long:return G.LONG;case Te.Double:return G.DOUBLE;case Te.String:return G.STRING;case Te.Bytes:return G.BYTES;case Te.Date:return G.DATE;default:throw new w(y.ErrInvalidType,`unsupported type: ${n}`)}}function Pf(n){switch(n){case Kt.IntegerCnt:return G.INTEGER_CNT;case Kt.LongCnt:return G.LONG_CNT;default:throw new w(y.ErrInvalidType,`unsupported type: ${n}`)}}function Mo(n){if(n instanceof Ue)return new Ye({type:G.JSON_OBJECT,createdAt:J(n.getCreatedAt()),value:Kf(n)});if(n instanceof We)return new Ye({type:G.JSON_ARRAY,createdAt:J(n.getCreatedAt()),value:Hp(n)});if(n instanceof ut)return new Ye({type:G.TEXT,createdAt:J(n.getCreatedAt())});if(n instanceof he)return new Ye({type:Nf(n.getType()),createdAt:J(n.getCreatedAt()),value:n.toBytes()});if(n instanceof He)return new Ye({type:Pf(n.getType()),createdAt:J(n.getCreatedAt()),value:n.toBytes()});if(n instanceof lt)return new Ye({type:G.TREE,createdAt:J(n.getCreatedAt()),value:_p(n)});throw new w(y.ErrUnimplemented,"unimplemented element")}function yp(n){return new zs({createdAt:J(n.getCreatedAt()),offset:n.getOffset()})}function di(n){return new rr({createdAt:J(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function gi(n){return new Ur({parentId:Bs(n.getParentID()),leftSiblingId:Bs(n.getLeftSiblingID())})}function Bs(n){return new pr({createdAt:J(n.getCreatedAt()),offset:n.getOffset()})}function Of(n){const e=new tc;if(n instanceof zr){const t=n,r=new Ji;r.parentCreatedAt=J(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Mo(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Zs){const t=n,r=new Mi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.prevCreatedAt=J(t.getPrevCreatedAt()),r.value=Mo(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof dr){const t=n,r=new $i;r.parentCreatedAt=J(t.getParentCreatedAt()),r.prevCreatedAt=J(t.getPrevCreatedAt()),r.createdAt=J(t.getCreatedAt()),r.executedAt=J(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Ar){const t=n,r=new Ui;r.parentCreatedAt=J(t.getParentCreatedAt()),r.createdAt=J(t.getCreatedAt()),r.executedAt=J(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Qs){const t=n,r=new qi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=di(t.getFromPos()),r.to=di(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);r.content=t.getContent();const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=J(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof ei){const t=n,r=new zi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=di(t.getFromPos()),r.to=di(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=r.attributes;for(const[o,a]of t.getAttributes())i[o]=a;r.executedAt=J(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ys){const t=n,r=new Ki;r.parentCreatedAt=J(t.getParentCreatedAt()),r.value=Mo(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof ti){const t=n,r=new Vi,s=r.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=J(o);r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=gi(t.getFromPos()),r.to=gi(t.getToPos()),r.contents=Sp(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=J(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof tr){const t=n,r=new ji;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=gi(t.getFromPos()),r.to=gi(t.getToPos());const s=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=t.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[a,u]of t.getAttributes())o[a]=u}r.executedAt=J(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new w(y.ErrUnimplemented,"unimplemented operation");return e}function vp(n){const e=[];for(const t of n)e.push(Of(t));return e}function wp(n){const e=new df({id:Cf(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=vp(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=mp(n.getPresenceChange())),e}function bp(n){const e=[];for(const t of n)e.push(wp(t));return e}function Tp(n){const e=[];for(const t of n)e.push(new gf({key:t.getStrKey(),element:cc(t.getValue())}));return e}function Ap(n){const e=[];for(const t of n)e.push(new Zi({element:cc(t.getValue())}));return e}function Ip(n){const e=[];for(const t of n){const r=new Qi;r.id=yp(t.getID()),r.value=t.getValue().getContent(),r.removedAt=J(t.getRemovedAt());const s=r.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new hs;a.value=o.getValue(),a.updatedAt=J(o.getUpdatedAt()),s[o.getKey()]=a}e.push(r)}return e}function Sp(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new eo({content:ac(t)}));return e}function xp(n){const e={};for(const t of n)e[t.getKey()]=new hs({value:t.getValue(),updatedAt:J(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ac(n){if(!n)return[];const e=[];return bo(n,(t,r)=>{const s=new Ks({id:Bs(t.id),type:t.type,removedAt:J(t.removedAt),depth:r});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=Bs(t.insPrevID)),t.insNextID&&(s.insNextId=Bs(t.insNextID)),t.attrs&&(s.attributes=xp(t.attrs)),e.push(s)}),e}function kp(n){const e=new ze;return e.body.case="jsonObject",e.body.value=new Wi({nodes:Tp(n.getRHT()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Df(n){const e=new ze;return e.body.case="jsonArray",e.body.value=new Hi({nodes:Ap(n.getElements()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Ep(n){const e=new ze;return e.body.case="primitive",e.body.value=new Gi({type:Nf(n.getType()),value:n.toBytes(),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Cp(n){const e=new ze;return e.body.case="text",e.body.value=new _i({nodes:Ip(n.getRGATreeSplit()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Np(n){const e=new ze;return e.body.case="counter",e.body.value=new Yi({type:Pf(n.getType()),value:n.toBytes(),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Bf(n){const e=new ze;return e.body.case="tree",e.body.value=new Xi({nodes:ac(n.getRoot()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function cc(n){if(n instanceof Ue)return kp(n);if(n instanceof We)return Df(n);if(n instanceof he)return Ep(n);if(n instanceof ut)return Cp(n);if(n instanceof He)return Np(n);if(n instanceof lt)return Bf(n);throw new w(y.ErrUnimplemented,"unimplemented element")}function Pp(n){return new or({documentKey:n.getDocumentKey(),checkpoint:pp(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:bp(n.getChanges()),snapshot:n.getSnapshot(),versionVector:oc(n.getVersionVector()),minSyncedTicket:J(n.getMinSyncedTicket())})}function Es(n){if(!(n instanceof le))return{};const e=n.findDetails(_m);for(const t of e)return t.metadata;return{}}function Gr(n){return Es(n).code??""}function Rf(n){return _n.of(n.clientSeq,BigInt(n.lamport),gc(n.actorId),uc(n.versionVector),BigInt(n.serverSeq))}function uc(n){if(!n)return;const e=new is;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return ct.of(BigInt(n.lamport),n.delimiter,gc(n.actorId))}function lc(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function Op(n){const e=n.type;if(e===qr.PUT){const t=lc(n.presence);return{type:Tr.Put,presence:t}}if(e===qr.CLEAR)return{type:Tr.Clear};throw new w(y.ErrInvalidType,`unsupported type: ${e}`)}function Dp(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,lc(r))}),e}function Ff(n){switch(n){case G.NULL:return Te.Null;case G.BOOLEAN:return Te.Boolean;case G.INTEGER:return Te.Integer;case G.LONG:return Te.Long;case G.DOUBLE:return Te.Double;case G.STRING:return Te.String;case G.BYTES:return Te.Bytes;case G.DATE:return Te.Date}throw new w(y.ErrUnimplemented,`unimplemented value type: ${n}`)}function ro(n){switch(n){case G.INTEGER_CNT:return Kt.IntegerCnt;case G.LONG_CNT:return Kt.LongCnt}throw new w(y.ErrUnimplemented,`unimplemented value type: ${n}`)}function $o(n){switch(n.type){case G.JSON_OBJECT:return n.value?zf(n.value):Ue.create(M(n.createdAt));case G.JSON_ARRAY:return n.value?Wp(n.value):We.create(M(n.createdAt));case G.TEXT:return ut.create(ps.create(),M(n.createdAt));case G.TREE:return Gp(n.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 he.of(he.valueFromBytes(Ff(n.type),n.value),M(n.createdAt));case G.INTEGER_CNT:case G.LONG_CNT:return He.create(ro(n.type),He.valueFromBytes(ro(n.type),n.value),M(n.createdAt))}}function mi(n){return Tt.of(zt.of(M(n.createdAt),n.offset),n.relativeOffset)}function Lf(n){return zt.of(M(n.createdAt),n.offset)}function Bp(n){const e=Gs.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{e.setAttr(r,s.value,M(s.updatedAt))});const t=vr.create(Lf(n.id),e);return t.remove(M(n.removedAt)),t}function _r(n){return vt.of(Rs(n.parentId),Rs(n.leftSiblingId))}function Rs(n){return xe.of(M(n.createdAt),n.offset)}function Rp(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=fc(t.content);e.push(r)}),e}function fc(n){if(n.length===0)return;const e=[];for(const s of n)e.push(Lp(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(),lt.create(t,bt).getRoot()}function Fp(n){const e=sr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function Lp(n){const e=Rs(n.id),t=je.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=Fp(n.attributes)),n.insPrevId&&(t.insPrevID=Rs(n.insPrevId)),n.insNextId&&(t.insNextID=Rs(n.insNextId)),t.removedAt=M(n.removedAt),t}function Jf(n){if(n.body.case==="set"){const e=n.body.value;return zr.create(e.key,$o(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Zs.create(M(e.parentCreatedAt),M(e.prevCreatedAt),$o(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return dr.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 Ar.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)}),Qs.create(M(e.parentCreatedAt),mi(e.from),mi(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)}),ei.create(M(e.parentCreatedAt),mi(e.from),mi(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 ys.create(M(e.parentCreatedAt),$o(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))}),ti.create(M(e.parentCreatedAt),_r(e.from),_r(e.to),Rp(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?tr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),_r(e.from),_r(e.to),s,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),tr.create(M(e.parentCreatedAt),_r(e.from),_r(e.to),s,t,M(e.executedAt)))}else throw new w(y.ErrUnimplemented,"unimplemented operation")}}function Jp(n){const e=[];for(const t of n){const r=Jf(t);r&&e.push(r)}return e}function Mf(n){const e=[];for(const t of n)e.push(ms.create({id:Rf(t.id),operations:Jp(t.operations),presenceChange:t.presenceChange?Op(t.presenceChange):void 0,message:t.message}));return e}function Mp(n){return os.of(BigInt(n.serverSeq),n.clientSeq)}function $p(n){return To.create(n.documentKey,Mp(n.checkpoint),n.isRemoved,Mf(n.changes),uc(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function $f(n){const e=new js;for(const r of n.nodes){const s=hc(r.element);e.set(r.key,s,s.getPositionedAt())}const t=new Ue(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Uf(n){const e=new Hs;for(const r of n.nodes)e.insert(hc(r.element));const t=new We(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Up(n){const e=he.of(he.valueFromBytes(Ff(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function qp(n){const e=new ps;let t=e.getHead();for(const s of n.nodes){const i=e.insertAfter(t,Bp(s));s.insPrevId&&i.setInsPrev(e.findNode(Lf(s.insPrevId))),t=i}const r=new ut(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function zp(n){const e=He.create(ro(n.type),He.valueFromBytes(ro(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function qf(n){const e=fc(n.nodes);return lt.create(e,M(n.createdAt))}function hc(n){if(n.body.case==="jsonObject")return $f(n.body.value);if(n.body.case==="jsonArray")return Uf(n.body.value);if(n.body.case==="primitive")return Up(n.body.value);if(n.body.case==="text")return qp(n.body.value);if(n.body.case==="counter")return zp(n.body.value);if(n.body.case==="tree")return qf(n.body.value);throw new w(y.ErrUnimplemented,"unimplemented element")}function Kp(n){if(!n)return{root:Ue.create(bt),presences:new Map};const e=ra.fromBinary(n);return{root:hc(e.root),presences:Dp(e.presences)}}function Vp(n){const e=oc(n);return dc(e.toBinary())}function jp(n){const e=mc(n),t=vo.fromBinary(e);return uc(t)}function zf(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=ze.fromBinary(n);return $f(e.body.value)}function Kf(n){return cc(n).toBinary()}function Wp(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=ze.fromBinary(n);return Uf(e.body.value)}function Hp(n){return Df(n).toBinary()}function Gp(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=ze.fromBinary(n);return qf(e.body.value)}function _p(n){return Bf(n).toBinary()}function dc(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function gc(n){return dc(n)}function mc(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function pc(n){return mc(n)}function Yp(n){const e=yo.fromBinary(n);return Rf(e)}function Xp(n){const e=tc.fromBinary(n);return Jf(e)}const ye={fromPresence:lc,toChangePack:Pp,fromChangePack:$p,fromChanges:Mf,toTreeNodes:ac,fromTreeNodes:fc,objectToBytes:Kf,bytesToObject:zf,bytesToSnapshot:Kp,bytesToHex:dc,hexToBytes:mc,toHexString:gc,toUint8Array:pc,toOperation:Of,toChangeID:Cf,PbChangeID:yo,bytesToChangeID:Yp,bytesToOperation:Xp,versionVectorToHex:Vp,hexToVersionVector:jp};var Le=(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))(Le||{});let Cr=3;function Vf(n){Cr=n}const K={trivial:(...n)=>{Cr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{Cr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{Cr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{Cr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{Cr>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=>Cr<=n};function jf(){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 Zp{constructor(e,t,r,s,i){c(this,"reconnectStreamDelay");c(this,"doc");c(this,"docID");c(this,"syncMode");c(this,"remoteChangeEventReceived");c(this,"watchStream");c(this,"watchLoopTimerID");c(this,"watchAbortController");c(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===Ni.RealtimeSyncOff?!1:this.syncMode===Ni.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ni.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 Uo=()=>{};class Qp{constructor(e){c(this,"finalized",!1);c(this,"observers",[]);c(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 w(y.ErrInvalidArgument,"missing observer");if(this.finalized)throw new w(y.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=Uo),s.error===void 0&&(s.error=Uo),s.complete===void 0&&(s.complete=Uo);const i=jf(),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(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Qr{constructor(e,t,r,s){c(this,"id");c(this,"delimiter");c(this,"message");c(this,"root");c(this,"operations");c(this,"presenceChange");c(this,"previousPresence");c(this,"reversePresenceKeys");this.id=e,this.delimiter=yf,this.root=t,this.operations=[],this.previousPresence=dt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,r,s){return new Qr(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 ms.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 _s{constructor(e){c(this,"rootObject");c(this,"elementPairMapByCreatedAt");c(this,"gcElementSetByCreatedAt");c(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 ut||t instanceof lt)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new _s(Ue.create(bt))}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 w(y.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 yr&&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 yr&&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 yr&&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 _s(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r),i=s.element.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(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()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Wf(n,e){const t=new Ys(n);return new Proxy(e,t.getHandlers())}class Ys{constructor(e){c(this,"context");c(this,"handlers");this.context=e,this.handlers={set:(t,r,s)=>(K.isEnabled(Le.Trivial)&&K.trivial(`obj[${r}]=${JSON.stringify(s)}`),Ys.setInternal(e,t,r,s),!0),get:(t,r)=>(K.isEnabled(Le.Trivial)&&K.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():Nr(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(K.isEnabled(Le.Trivial)&&K.trivial(`obj[${r}]`),Ys.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,s){if(r.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=so(e,s,i),a=t.set(r,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(zr.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 w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=so(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(Ar.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function ty(n,e){const t=new me(n,e);return new Proxy(e,t.getHandlers())}function ny(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function ry(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class me{constructor(e,t){c(this,"context");c(this,"handlers");c(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 lr(e,a)}:s==="getElementByIndex"?o=>{const a=r.get(o);return lr(e,a)}:s==="getLast"?()=>lr(e,r.getLast()):s==="deleteByID"?o=>{const a=me.deleteInternalByID(e,r,o);return lr(e,a)}:s==="insertAfter"?(o,a)=>{const u=me.insertAfterInternal(e,r,o,a);return lr(e,u)}:s==="insertBefore"?(o,a)=>{const u=me.insertBeforeInternal(e,r,o,a);return lr(e,u)}:s==="moveBefore"?(o,a)=>{me.moveBeforeInternal(e,r,o,a)}:s==="moveAfter"?(o,a)=>{me.moveAfterInternal(e,r,o,a)}:s==="moveFront"?o=>{me.moveFrontInternal(e,r,o)}:s==="moveLast"?o=>{me.moveLastInternal(e,r,o)}:ny(s)?Nr(e,r.get(Number(s))):s==="push"?o=>me.pushInternal(e,r,o):s==="splice"?(o,a,...u)=>me.splice(e,r,o,a,...u):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?me.iteratorInternal.bind(this,e,r):s==="includes"?(o,a)=>me.includes(e,r,o,a):s==="indexOf"?(o,a)=>me.indexOf(e,r,o,a):s==="lastIndexOf"?(o,a)=>me.lastIndexOf(e,r,o,a):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>me.toTestString(r):typeof s=="string"&&ry(s)?(...o)=>{const a=Array.from(r).map(u=>Nr(e,u));return Array.prototype[s].apply(a,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(K.isEnabled(Le.Trivial)&&K.trivial(`array[${s}]`),me.deleteInternalByIndex(e,r,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield lr(e,r)}static buildArrayElements(e,t){const r=[];for(const s of t){const i=e.issueTimeTicket(),o=so(e,s,i);r.push(o)}return r}static pushInternal(e,t,r){return me.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(dr.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,r,s){const i=e.issueTimeTicket();t.moveAfter(r,s,i),e.push(dr.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(dr.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(dr.create(t.getCreatedAt(),i,r,s))}static insertAfterInternal(e,t,r,s){const i=e.issueTimeTicket(),o=so(e,s,i);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Zs.create(t.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,r,s){return me.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(Ar.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(Ar.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),u=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let h=a;h=i)return!1;if(he.isSupport(r))return Array.from(t).map(l=>Nr(e,l)).includes(r,o);for(let u=o;u=i)return-1;if(he.isSupport(r))return Array.from(t).map(l=>Nr(e,l)).indexOf(r,o);for(let u=o;u=i?i-1:s<0?s+i:s;if(o<0)return-1;if(he.isSupport(r))return Array.from(t).map(l=>Nr(e,l)).lastIndexOf(r,o);for(let u=o;u>0;u--)if(((a=t.get(u))==null?void 0:a.getID())===r.getID())return u;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Ao{constructor(e,t){c(this,"context");c(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 w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);K.isEnabled(Le.Debug)&&K.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${r}`);const o=s?ds(s):void 0,a=this.context.issueTimeTicket(),[u,,l,h]=this.text.edit(i,r,a,o);for(const d of l)this.context.registerGCPair(d);return this.context.push(new Qs(this.text.getCreatedAt(),i[0],i[1],u,r,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,r){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);K.isEnabled(Le.Debug)&&K.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=ds(r),o=this.context.issueTimeTicket(),[a,u]=this.text.setStyle(s,i,o);for(const l of u)this.context.registerGCPair(l);return this.context.push(new ei(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new w(y.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 w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Tt.fromStruct(e[0]),Tt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new w(y.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 w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class Io{constructor(e,t){c(this,"valueType");c(this,"value");c(this,"context");c(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 w(y.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=he.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ys.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function yc(n,e,t){const{type:r}=n,s=t.issueTimeTicket();if(r===er){Hf(n);const{value:i}=n,o=je.create(xe.of(s,0),r,i);e.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!pf(o)){const l=ds(o);a=new sr;for(const[h,d]of Object.entries(l))a.set(h,d,s)}const u=je.create(xe.of(s,0),r,void 0,a);e.append(u);for(const l of i)yc(l,u,t)}}function sy(n,e){const{type:t}=e,r=n.issueTimeTicket();let s;if(e.type===er){const{value:i}=e;s=je.create(xe.of(r,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!pf(o)){const u=ds(o);a=new sr;for(const[l,h]of Object.entries(u))a.set(l,h,r)}s=je.create(xe.of(n.issueTimeTicket(),0),t,void 0,a);for(const u of i)yc(u,s,n)}return s}function Hf(n){if(!n.value.length)throw new w(y.ErrInvalidArgument,"text node cannot have empty value");return!0}function ju(n){if(!n.length)return!0;if(n[0].type===er)for(const t of n){const{type:r}=t;if(r!==er)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together");Hf(t)}else for(const t of n){const{type:r}=t;if(r===er)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class So{constructor(e){c(this,"initialRoot");c(this,"context");c(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 je.create(xe.of(e.issueTimeTicket(),0),np);const t=je.create(xe.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)yc(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?ds(t):void 0,[a]=this.tree.style([r,s],o,i);this.context.push(tr.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 w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.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?ds(r):void 0,[u,l]=this.tree.style([s,i],a,o);for(const h of l)this.context.registerGCPair(h);this.context.push(tr.create(this.tree.getCreatedAt(),s,i,u,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.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,u]=this.tree.removeStyle([s,i],r,o);for(const l of u)this.context.registerGCPair(l);this.context.push(tr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,r,o))}editInternal(e,t,r,s=0){var l;if(r.length!==0&&r[0]&&(ju(r),r[0].type!==er))for(const h of r){const{children:d=[]}=h;ju(d)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=r[0])==null?void 0:l.type)===er){let h="";for(const d of r){const{value:v}=d;h+=v}o.push(je.create(xe.of(this.context.issueTimeTicket(),0),er,h))}else o=r.map(h=>h&&sy(this.context,h)).filter(h=>h);const[,a,u]=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(ti.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,u,i)),!0}editByPath(e,t,r,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.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 w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.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 w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.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 w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.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 w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.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 w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[vt.fromStruct(e[0]),vt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[vt.fromStruct(e[0]),vt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Wu(n,e){return Wf(n,e)}function lr(n,e){if(e){if(e instanceof he)return e;if(e instanceof Ue)return Wf(n,e);if(e instanceof We)return ty(n,e);if(e instanceof ut)return new Ao(n,e);if(e instanceof He){const t=new Io(Kt.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof lt){const t=new So;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Nr(n,e){const t=lr(n,e);return t instanceof he?t.getValue():t}function so(n,e,t){let r;if(he.isSupport(e))r=he.of(e,t);else if(Array.isArray(e))r=We.create(t,me.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Ao?(r=ut.create(ps.create(),t),e.initialize(n,r)):e instanceof Io?(r=He.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof So?(r=lt.create(e.buildRoot(n),t),e.initialize(n,r)):r=Ue.create(t,Ys.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const Hu=50;class iy{constructor(){c(this,"undoStack",[]);c(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Hu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Hu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const oy="yorkie-devtools-panel",ay="yorkie-devtools-sdk";let Xr="disconnected";const Gu=new Map,Ci=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Ci);function pi(n,e){(e!=null&&e.force||Xr!=="disconnected")&&window.postMessage({source:ay,...n},"*")}function cy(n){if(!n.isEnableDevtools()||typeof window>"u"||Gu.has(n.getKey()))return;Ci.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Se.StatusChanged&&r.type!==Se.Snapshot&&r.type!==Se.LocalChange&&r.type!==Se.RemoteChange&&r.type!==Se.Initialized&&r.type!==Se.Watched&&r.type!==Se.Unwatched&&r.type!==Se.PresenceChanged)||(Ci.get(n.getKey()).push(t),Xr==="synced"&&pi({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Gu.set(n.getKey(),[e]),pi({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==oy)return;switch(t.data.msg){case"devtools::connect":if(Xr!=="disconnected")break;Xr="connected",pi({msg:"doc::available",docKey:n.getKey()}),K.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Xr="disconnected",K.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Xr="synced",pi({msg:"doc::sync::full",docKey:n.getKey(),events:Ci.get(n.getKey())}),K.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var fr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(fr||{}),Se=(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.AuthError="auth-error",n))(Se||{}),Na=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Na||{}),Pa=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Pa||{});class Gf{constructor(e,t){c(this,"key");c(this,"status");c(this,"opts");c(this,"changeID");c(this,"checkpoint");c(this,"localChanges");c(this,"root");c(this,"clone");c(this,"eventStream");c(this,"eventStreamObserver");c(this,"onlineClients");c(this,"presences");c(this,"history");c(this,"internalHistory");c(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=_s.create(),this.changeID=fp,this.checkpoint=hp,this.localChanges=[],this.eventStream=ey(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new iy,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},cy(this)}update(e,t){if(this.getStatus()==="removed")throw new w(y.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const i=Wu(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(i,new Jo(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){K.isEnabled(Le.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,ie.Local),u=s.getReversePresence();u&&a.push({type:"presence",value:u}),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:ie.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:ie.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(l),K.isEnabled(Le.Trivial)&&K.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,s){if(typeof e=="string"){if(typeof t!="function")throw new w(y.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)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(u=>{for(const l of u)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(u=>{for(const l of u)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(u=>{for(const l of u)l.type==="connection-changed"&&a(l)},r,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="status-changed"&&a(l)},r,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="sync-status-changed"&&a(l)},r,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="local-broadcast"&&a(l)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="broadcast"&&a(l)},r)}if(e==="auth-error"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="auth-error"&&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 u of a){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const l=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,i)&&l.push(h);l.length&&o({...u,value:{...u.value,operations:l}})}},r,s)}if(typeof e=="function"){const i=e,o=t,a=r;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new w(y.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])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),ie.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),K.isEnabled(Le.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:dt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return To.create(this.key,t,!1,e,this.getVersionVector())}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=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Wu(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()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r,s=-1){const{root:i,presences:o}=ye.bytesToSnapshot(r);this.root=new _s(i),this.presences=o,this.changeID=this.changeID.setClocks(t.maxLamport(),t),this.clone=void 0,this.removePushedLocalChanges(s),this.applyChanges(this.localChanges,ie.Local),this.publish([{type:"snapshot",source:ie.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?ye.bytesToHex(r):void 0,snapshotVector:ye.versionVectorToHex(t)}}])}applyChanges(e,t){K.isEnabled(Le.Debug)&&K.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),K.isEnabled(Le.Trivial)&&K.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);K.isEnabled(Le.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 r=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case Tr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:ie.Remote,value:{clientID:s,presence:o.presence}});break;case Tr.Clear:r.push({type:"unwatched",source:ie.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.syncClocks(e.getID()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===ie.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:ie.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,s=[];if(t===$r.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:ie.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===$r.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:ie.Remote,value:{clientID:r,presence:i}})}else if(t===$r.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(wo),this.publish([{source:e==="removed"?ie.Remote:ie.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,snapshotVector:s}=e.value;if(!t)return;this.applySnapshot(BigInt(r),ye.hexToVersionVector(s),ye.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ms.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 w(y.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?dt(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?dt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?dt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:dt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:dt(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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new w(y.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof At)){new Jo(t,dt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,ie.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,ie.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(),u=[];s.length>0&&u.push({type:"local-change",source:ie.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()&&u.push({type:"presence-changed",source:ie.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new w(y.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof At)){new Jo(t,dt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,ie.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,ie.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(),u=[];s.length>0&&u.push({type:"local-change",source:ie.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()&&u.push({type:"presence-changed",source:ie.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}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])}getVersionVector(){return this.changeID.getVersionVector()}}function uy(n,e){let t=e;return{authInterceptor:i=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await i(o)),setToken:i=>{t=i}}}const ly="yorkie-js-sdk",fy="0.5.6",hy="Yorkie JS SDK",dy="./src/yorkie.ts",gy={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},my=["dist"],py={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"},yy={node:">=18.0.0",npm:">=7.1.0"},vy={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},wy={name:"hackerwins",email:"susukang98@gmail.com"},by="Apache-2.0",Ty={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Ay="https://github.com/yorkie-team/yorkie-js-sdk#readme",Iy={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},Sy={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},_u={name:ly,version:fy,description:hy,main:dy,publishConfig:gy,files:my,scripts:py,engines:yy,repository:vy,author:wy,license:by,bugs:Ty,homepage:Ay,devDependencies:Iy,dependencies:Sy};function xy(){return n=>async e=>(e.header.set("x-yorkie-user-agent",_u.name+"/"+_u.version),await n(e))}const ky=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ni=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ni||{});const yi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},qo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class _f{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"authTokenInjector");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"setAuthToken");c(this,"taskQueue");c(this,"processing",!1);c(this,"keepalive",!1);t=t||yi,this.key=t.key?t.key:jf(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??yi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??yi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??yi.retrySyncLoopDelay;const{authInterceptor:r,setToken:s}=uy(this.apiKey);this.setAuthToken=s,this.rpcClient=xm(Gm,Hm({baseUrl:e,interceptors:[r,xy()],fetch:(i,o)=>{const a={...o,keepalive:this.keepalive};return fetch(i,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(async e=>{throw K.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),K.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw K.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==fr.Detached)throw new w(y.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 h;const{topic:o,payload:a}=i.value,u=(h=i.options)==null?void 0:h.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(d){d instanceof Error&&(u==null||u(d))}}),s=t.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 i=>{const o=ye.fromChangePack(i.changePack);if(e.applyChangePack(o),e.getStatus()===fr.Removed)return e;e.applyStatus(fr.Attached),this.attachmentMap.set(e.getKey(),new Zp(this.reconnectStreamDelay,e,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(e.getKey()),K.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(l=>{for(const[h,d]of Object.entries(u))if(!a.has(h)){const v=h;l[v]=d}})}return e}).catch(async i=>{throw K.error(`[AD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new w(y.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:ye.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=ye.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==fr.Removed&&e.applyStatus(fr.Detached),this.detachInternal(e.getKey()),K.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async s=>{throw K.error(`[DD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new w(y.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 w(y.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.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:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=ye.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),K.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async s=>{throw K.error(`[RD] c:"${this.getKey()}" err :`,s),await 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 w(y.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);if(!ky(r))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??qo.maxRetries,a=qo.maxBackoff;let u=0;const l=d=>Math.min(qo.initialRetryInterval*2**d,a),h=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(()=>{K.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async d=>{if(K.error(`[BC] c:"${this.getKey()}" err:`,d),await this.handleConnectError(d))if(d instanceof le&&Gr(d)===y.ErrUnauthenticated&&i.doc.publish([{type:Se.AuthError,value:{reason:Es(d).reason,method:"Broadcast"}}]),uh(),l(u-1)),K.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw K.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));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[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode).catch(async s=>{throw s instanceof le&&Gr(s)===y.ErrUnauthenticated&&r.doc.publish([{type:Se.AuthError,value:{reason:Es(s).reason,method:"PushPull"}}]),s})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{K.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?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 w(y.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new w(y.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:Se.ConnectionChanged,value:Na.Connected}]),K.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:Se.Initialized,source:ie.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Se.ConnectionChanged,value:Na.Disconnected}]),K.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(l)?(l instanceof le&&Gr(l)===y.ErrUnauthenticated&&t.doc.publish([{type:Se.AuthError,value:{reason:Es(l).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(l)}})()})})}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(fr.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:ye.toChangePack(i),pushOnly:t==="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:Se.SyncStatusChanged,value:Pa.Synced}]),r.getStatus()===fr.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),l=a.getChangeSize();return K.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Se.SyncStatusChanged,value:Pa.SyncFailed}]),K.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof le))return!1;if(e.code===ne.Canceled||e.code===ne.Unknown||e.code===ne.ResourceExhausted||e.code===ne.Unavailable)return!0;if(Gr(e)===y.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Es(e).reason);this.setAuthToken(t)}return!0}return(Gr(e)===y.ErrClientNotActivated||Gr(e)===y.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(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 Yf={Client:_f,Document:Gf,Primitive:he,Text:Ao,Counter:Io,Tree:So,LogLevel:Le,setLogLevel:Vf,IntType:Kt.IntegerCnt,LongType:Kt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:_f,Document:Gf,Primitive:he,Text:Ao,Counter:Io,Tree:So,LogLevel:Le,setLogLevel:Vf,IntType:Kt.IntegerCnt,LongType:Kt.LongCnt});const Ey=(n,e)=>{const t=n.__vccOpts||n;for(const[r,s]of e)t[r]=s;return t},Cy=[{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"}]}],ur=new Yf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Ht=new Yf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Ny={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 ur.activate(),await ur.attach(Ht),Ht.update(n=>{n.lists||(n.lists=Cy)},"create default list if not exists"),Ht.subscribe(n=>{this.lists=Ht.getRoot().lists}),await ur.sync(),this.lists=Ht.getRoot().lists},async disconnect(){await ur.deactivate()},isOpened(n){return this.opened===n},openForm(n){this.opened=n},closeForm(){this.opened=null},addCard(n){this.title!==""&&Ht.update(e=>{e.lists.getElementByID(n.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${ur.getID()}`)},deleteCard(n,e){Ht.update(t=>{t.lists.getElementByID(n.getID()).cards.deleteByID(e.getID())},`delete a card by ${ur.getID()}`)},addList(){this.title!==""&&Ht.update(n=>{n.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${ur.getID()}`)},deleteList(n){Ht.update(e=>{e.lists.deleteByID(n.getID())},`delete a list by ${ur.getID()}`)}}},Py={class:"list"},Oy=["onClick"],Dy={class:"title"},By={class:"card"},Ry=["onClick"],Fy={key:0,class:"add-form"},Ly=["onKeyup"],Jy={class:"buttons"},My=["onClick"],$y=["onClick"],Uy={class:"add-list",ref:"addListForm"},qy={key:0,class:"add-form"},zy={class:"buttons"};function Ky(n,e,t,r,s,i){return jt(),Wt(_e,null,[(jt(!0),Wt(_e,null,Mc(s.lists,(o,a)=>(jt(),Wt("div",Py,[Re("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,Oy),Re("div",Dy,Ec(o.title),1),(jt(!0),Wt(_e,null,Mc(o.cards,u=>(jt(),Wt("div",By,[Re("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Ry),Jl(" "+Ec(u.title),1)]))),256)),Re("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(jt(),Wt("div",Fy,[Jc(Re("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[fi(u=>i.addCard(o),["enter"]),e[1]||(e[1]=fi(u=>i.closeForm(),["esc"]))]},null,40,Ly),[[iu,s.title]]),Re("div",Jy,[Re("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,My),Re("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(jt(),Wt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,$y))],512)]))),256)),Re("div",Uy,[i.isOpened(0)?(jt(),Wt("div",qy,[Jc(Re("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=fi(o=>i.addList(),["enter"])),e[5]||(e[5]=fi(o=>i.closeForm(),["esc"]))]},null,544),[[iu,s.title]]),Re("div",zy,[Re("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Re("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(jt(),Wt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const Vy=Ey(Ny,[["render",Ky]]);xg(Vy).mount("#app"); +`));for(const r of e)this.applyChange(r,t);K.isEnabled(Le.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 r=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case Tr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:ie.Remote,value:{clientID:s,presence:o.presence}});break;case Tr.Clear:r.push({type:"unwatched",source:ie.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.syncClocks(e.getID()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===ie.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:ie.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,s=[];if(t===$r.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:ie.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===$r.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:ie.Remote,value:{clientID:r,presence:i}})}else if(t===$r.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(wo),this.publish([{source:e==="removed"?ie.Remote:ie.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,snapshotVector:s}=e.value;if(!t)return;this.applySnapshot(BigInt(r),ye.hexToVersionVector(s),ye.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ms.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 w(y.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?dt(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?dt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?dt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:dt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:dt(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}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new w(y.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof At)){new Jo(t,dt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,ie.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,ie.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(),u=[];s.length>0&&u.push({type:"local-change",source:ie.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()&&u.push({type:"presence-changed",source:ie.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new w(y.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Qr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof At)){new Jo(t,dt(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,ie.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,ie.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(),u=[];s.length>0&&u.push({type:"local-change",source:ie.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()&&u.push({type:"presence-changed",source:ie.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}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])}getVersionVector(){return this.changeID.getVersionVector()}}function uy(n,e){let t=e;return{authInterceptor:i=>async o=>(n&&o.header.set("x-api-key",n),t&&o.header.set("authorization",t),await i(o)),setToken:i=>{t=i}}}const ly="yorkie-js-sdk",fy="0.5.7",hy="Yorkie JS SDK",dy="./src/yorkie.ts",gy={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},my=["dist"],py={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"},yy={node:">=18.0.0",npm:">=7.1.0"},vy={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},wy={name:"hackerwins",email:"susukang98@gmail.com"},by="Apache-2.0",Ty={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Ay="https://github.com/yorkie-team/yorkie-js-sdk#readme",Iy={"@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/express":"^4.17.21","@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",axios:"^1.7.7","eslint-plugin-tsdoc":"^0.2.16",express:"^4.21.1",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.3.1",vitest:"^0.34.5"},Sy={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},_u={name:ly,version:fy,description:hy,main:dy,publishConfig:gy,files:my,scripts:py,engines:yy,repository:vy,author:wy,license:by,bugs:Ty,homepage:Ay,devDependencies:Iy,dependencies:Sy};function xy(){return n=>async e=>(e.header.set("x-yorkie-user-agent",_u.name+"/"+_u.version),await n(e))}const ky=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ni=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ni||{});const yi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},qo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class _f{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"authTokenInjector");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"setAuthToken");c(this,"taskQueue");c(this,"processing",!1);c(this,"keepalive",!1);t=t||yi,this.key=t.key?t.key:jf(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.authTokenInjector=t.authTokenInjector,this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration??yi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay??yi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay??yi.retrySyncLoopDelay;const{authInterceptor:r,setToken:s}=uy(this.apiKey);this.setAuthToken=s,this.rpcClient=xm(Gm,Hm({baseUrl:e,interceptors:[r,xy()],fetch:(i,o)=>{const a={...o,keepalive:this.keepalive};return fetch(i,a)}})),this.taskQueue=[]}async activate(){if(this.isActive())return Promise.resolve();if(this.authTokenInjector){const e=await this.authTokenInjector();this.setAuthToken(e)}return 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(async e=>{throw K.error(`[AC] c:"${this.getKey()}" err :`,e),await this.handleConnectError(e),e}))}deactivate(e={keepalive:!1}){if(this.status==="deactivated")return Promise.resolve();const t=async()=>{try{await this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}),this.deactivateInternal(),K.info(`[DC] c"${this.getKey()}" deactivated`)}catch(r){throw K.error(`[DC] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r}};if(e.keepalive){this.keepalive=!0;const r=t();return this.keepalive=!1,r}return this.enqueueTask(t)}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==fr.Detached)throw new w(y.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 h;const{topic:o,payload:a}=i.value,u=(h=i.options)==null?void 0:h.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(d){d instanceof Error&&(u==null||u(d))}}),s=t.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 i=>{const o=ye.fromChangePack(i.changePack);if(e.applyChangePack(o),e.getStatus()===fr.Removed)return e;e.applyStatus(fr.Attached),this.attachmentMap.set(e.getKey(),new Zp(this.reconnectStreamDelay,e,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(e.getKey()),K.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(l=>{for(const[h,d]of Object.entries(u))if(!a.has(h)){const v=h;l[v]=d}})}return e}).catch(async i=>{throw K.error(`[AD] c:"${this.getKey()}" err :`,i),await this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new w(y.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:ye.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=ye.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==fr.Removed&&e.applyStatus(fr.Detached),this.detachInternal(e.getKey()),K.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(async s=>{throw K.error(`[DD] c:"${this.getKey()}" err :`,s),await this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new w(y.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 w(y.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(async r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),await 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(async r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),await this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.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:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=ye.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),K.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(async s=>{throw K.error(`[RD] c:"${this.getKey()}" err :`,s),await 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 w(y.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);if(!ky(r))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??qo.maxRetries,a=qo.maxBackoff;let u=0;const l=d=>Math.min(qo.initialRetryInterval*2**d,a),h=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(()=>{K.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(async d=>{if(K.error(`[BC] c:"${this.getKey()}" err:`,d),await this.handleConnectError(d))if(d instanceof le&&Gr(d)===y.ErrUnauthenticated&&i.doc.publish([{type:Se.AuthError,value:{reason:Es(d).reason,method:"Broadcast"}}]),uh(),l(u-1)),K.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw K.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));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[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode).catch(async s=>{throw s instanceof le&&Gr(s)===y.ErrUnauthenticated&&r.doc.publish([{type:Se.AuthError,value:{reason:Es(s).reason,method:"PushPull"}}]),s})));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(async r=>{K.error(`[SL] c:"${this.getKey()}" sync failed:`,r),await this.handleConnectError(r)?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 w(y.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new w(y.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:Se.ConnectionChanged,value:Na.Connected}]),K.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:Se.Initialized,source:ie.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Se.ConnectionChanged,value:Na.Disconnected}]),K.debug(`[WD] c:"${this.getKey()}" unwatches`),await this.handleConnectError(l)?(l instanceof le&&Gr(l)===y.ErrUnauthenticated&&t.doc.publish([{type:Se.AuthError,value:{reason:Es(l).reason,method:"WatchDocuments"}}]),r()):this.conditions.WatchLoop=!1,a(l)}})()})})}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(fr.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:ye.toChangePack(i),pushOnly:t==="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:Se.SyncStatusChanged,value:Pa.Synced}]),r.getStatus()===fr.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),l=a.getChangeSize();return K.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),r}).catch(async o=>{throw r.publish([{type:Se.SyncStatusChanged,value:Pa.SyncFailed}]),K.error(`[PP] c:"${this.getKey()}" err :`,o),o})}async handleConnectError(e){if(!(e instanceof le))return!1;if(e.code===ne.Canceled||e.code===ne.Unknown||e.code===ne.ResourceExhausted||e.code===ne.Unavailable)return!0;if(Gr(e)===y.ErrUnauthenticated){if(this.authTokenInjector){const t=await this.authTokenInjector(Es(e).reason);this.setAuthToken(t)}return!0}return(Gr(e)===y.ErrClientNotActivated||Gr(e)===y.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(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 Yf={Client:_f,Document:Gf,Primitive:he,Text:Ao,Counter:Io,Tree:So,LogLevel:Le,setLogLevel:Vf,IntType:Kt.IntegerCnt,LongType:Kt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:_f,Document:Gf,Primitive:he,Text:Ao,Counter:Io,Tree:So,LogLevel:Le,setLogLevel:Vf,IntType:Kt.IntegerCnt,LongType:Kt.LongCnt});const Ey=(n,e)=>{const t=n.__vccOpts||n;for(const[r,s]of e)t[r]=s;return t},Cy=[{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"}]}],ur=new Yf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Ht=new Yf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Ny={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 ur.activate(),await ur.attach(Ht),Ht.update(n=>{n.lists||(n.lists=Cy)},"create default list if not exists"),Ht.subscribe(n=>{this.lists=Ht.getRoot().lists}),await ur.sync(),this.lists=Ht.getRoot().lists},async disconnect(){await ur.deactivate()},isOpened(n){return this.opened===n},openForm(n){this.opened=n},closeForm(){this.opened=null},addCard(n){this.title!==""&&Ht.update(e=>{e.lists.getElementByID(n.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${ur.getID()}`)},deleteCard(n,e){Ht.update(t=>{t.lists.getElementByID(n.getID()).cards.deleteByID(e.getID())},`delete a card by ${ur.getID()}`)},addList(){this.title!==""&&Ht.update(n=>{n.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${ur.getID()}`)},deleteList(n){Ht.update(e=>{e.lists.deleteByID(n.getID())},`delete a list by ${ur.getID()}`)}}},Py={class:"list"},Oy=["onClick"],Dy={class:"title"},By={class:"card"},Ry=["onClick"],Fy={key:0,class:"add-form"},Ly=["onKeyup"],Jy={class:"buttons"},My=["onClick"],$y=["onClick"],Uy={class:"add-list",ref:"addListForm"},qy={key:0,class:"add-form"},zy={class:"buttons"};function Ky(n,e,t,r,s,i){return jt(),Wt(_e,null,[(jt(!0),Wt(_e,null,Mc(s.lists,(o,a)=>(jt(),Wt("div",Py,[Re("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,Oy),Re("div",Dy,Ec(o.title),1),(jt(!0),Wt(_e,null,Mc(o.cards,u=>(jt(),Wt("div",By,[Re("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Ry),Jl(" "+Ec(u.title),1)]))),256)),Re("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(jt(),Wt("div",Fy,[Jc(Re("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[fi(u=>i.addCard(o),["enter"]),e[1]||(e[1]=fi(u=>i.closeForm(),["esc"]))]},null,40,Ly),[[iu,s.title]]),Re("div",Jy,[Re("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,My),Re("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(jt(),Wt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,$y))],512)]))),256)),Re("div",Uy,[i.isOpened(0)?(jt(),Wt("div",qy,[Jc(Re("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=fi(o=>i.addList(),["enter"])),e[5]||(e[5]=fi(o=>i.closeForm(),["esc"]))]},null,544),[[iu,s.title]]),Re("div",zy,[Re("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Re("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(jt(),Wt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const Vy=Ey(Ny,[["render",Ky]]);xg(Vy).mount("#app"); diff --git a/examples/vuejs-kanban/index.html b/examples/vuejs-kanban/index.html index 04f0bf014..e0d64b950 100644 --- a/examples/vuejs-kanban/index.html +++ b/examples/vuejs-kanban/index.html @@ -6,7 +6,7 @@ Vite App - +