From 59078405e77f1c768ca2444deb0a5f37f9eefbec Mon Sep 17 00:00:00 2001 From: hackerwins Date: Tue, 22 Oct 2024 05:18:23 +0000 Subject: [PATCH] deploy: 5d4ded96992dc7ee92fceb6799d73137ef84cf5d --- api-reference/classes/Change.html | 28 ++-- api-reference/classes/Client.html | 42 +++--- api-reference/classes/Counter.html | 16 +-- api-reference/classes/Document.html | 130 +++++++++--------- api-reference/classes/Primitive.html | 48 +++---- api-reference/classes/Text.html | 38 ++--- api-reference/classes/TimeTicket.html | 30 ++-- api-reference/classes/Tree.html | 52 +++---- api-reference/enums/ClientCondition.html | 6 +- api-reference/enums/ClientStatus.html | 6 +- api-reference/enums/DocEventType.html | 26 ++-- api-reference/enums/DocumentStatus.html | 8 +- api-reference/enums/DocumentSyncStatus.html | 6 +- api-reference/enums/LogLevel.html | 4 +- api-reference/enums/OpSource.html | 4 +- .../enums/StreamConnectionStatus.html | 6 +- api-reference/enums/SyncMode.html | 10 +- api-reference/enums/TreeChangeType.html | 4 +- api-reference/interfaces/ChangeInfo.html | 4 +- api-reference/interfaces/ClientOptions.html | 14 +- .../interfaces/ConnectionChangedEvent.html | 4 +- .../interfaces/InitializedEvent.html | 4 +- .../interfaces/LocalChangeEvent.html | 6 +- api-reference/interfaces/Observable.html | 4 +- api-reference/interfaces/Observer.html | 4 +- .../interfaces/PresenceChangedEvent.html | 4 +- .../interfaces/RemoteChangeEvent.html | 6 +- api-reference/interfaces/SnapshotEvent.html | 6 +- .../interfaces/SyncStatusChangedEvent.html | 4 +- api-reference/interfaces/UnwatchedEvent.html | 4 +- api-reference/interfaces/WatchedEvent.html | 4 +- api-reference/modules/Devtools.html | 2 +- api-reference/types/ActorID.html | 2 +- api-reference/types/AddOpInfo.html | 2 +- api-reference/types/ArrayOperationInfo.html | 2 +- api-reference/types/CRDTTreeNodeIDStruct.html | 2 +- api-reference/types/CompleteFn.html | 2 +- api-reference/types/CounterOperationInfo.html | 2 +- api-reference/types/CounterValue.html | 2 +- api-reference/types/Devtools.Client.html | 2 +- .../types/Devtools.ContainerValue.html | 2 +- api-reference/types/Devtools.JSONElement.html | 2 +- .../types/Devtools.TreeNodeInfo.html | 2 +- api-reference/types/DocEvent.html | 2 +- api-reference/types/EditOpInfo.html | 2 +- api-reference/types/ElementNode.html | 2 +- api-reference/types/ErrorFn.html | 2 +- .../types/FullPanelToSDKMessage.html | 2 +- .../types/FullSDKToPanelMessage.html | 2 +- api-reference/types/IncreaseOpInfo.html | 2 +- api-reference/types/Indexable.html | 2 +- api-reference/types/JSONArray.html | 26 ++-- api-reference/types/JSONElement.html | 2 +- api-reference/types/JSONObject.html | 8 +- api-reference/types/MoveOpInfo.html | 2 +- api-reference/types/NextFn.html | 2 +- api-reference/types/ObjectOperationInfo.html | 2 +- api-reference/types/OperationInfo.html | 2 +- api-reference/types/PanelToSDKMessage.html | 2 +- api-reference/types/PrimitiveValue.html | 2 +- api-reference/types/RemoveOpInfo.html | 2 +- api-reference/types/SDKToPanelMessage.html | 2 +- api-reference/types/SetOpInfo.html | 2 +- api-reference/types/StyleOpInfo.html | 2 +- api-reference/types/TextNode.html | 2 +- api-reference/types/TextOperationInfo.html | 2 +- api-reference/types/TextPosStruct.html | 2 +- api-reference/types/TextPosStructRange.html | 2 +- api-reference/types/TimeTicketStruct.html | 2 +- api-reference/types/TransactionEvent.html | 2 +- api-reference/types/TreeChange.html | 2 +- api-reference/types/TreeEditOpInfo.html | 2 +- api-reference/types/TreeNode.html | 2 +- api-reference/types/TreeOperationInfo.html | 2 +- api-reference/types/TreePosStructRange.html | 2 +- api-reference/types/TreeStyleOpInfo.html | 2 +- api-reference/types/Unsubscribe.html | 2 +- api-reference/types/WrappedElement.html | 2 +- .../variables/EventSourceDevPanel.html | 2 +- api-reference/variables/EventSourceSDK.html | 2 +- api-reference/variables/converter.html | 2 +- api-reference/variables/default.html | 2 +- examples/nextjs-scheduler/404.html | 2 +- .../_buildManifest.js | 0 .../_ssgManifest.js | 0 ...9fc00264ed.js => page-eccac34c2844a9ff.js} | 2 +- examples/nextjs-scheduler/index.html | 2 +- examples/nextjs-scheduler/index.txt | 4 +- .../{index-1jBrjG-X.js => index-Cw6-JyZY.js} | 2 +- examples/profile-stack/index.html | 2 +- .../{index-BIdlKhE_.js => index-Dn-3KynT.js} | 2 +- examples/react-tldraw/index.html | 2 +- .../{index-0iJGe1Ls.js => index-DIeJWN1h.js} | 2 +- examples/react-todomvc/index.html | 2 +- .../{index-BXKIYS9E.js => index-CfPS2aDQ.js} | 2 +- examples/simultaneous-cursors/index.html | 2 +- .../{index-DWRqngRf.js => index-DB4O8pnL.js} | 2 +- examples/vanilla-codemirror6/index.html | 2 +- .../{index-CKJvWhky.js => index-DYVWARJt.js} | 2 +- examples/vanilla-quill/index.html | 2 +- .../{index-BqVvB3pR.js => index-ClPsSZVC.js} | 2 +- examples/vuejs-kanban/index.html | 2 +- 102 files changed, 351 insertions(+), 351 deletions(-) rename examples/nextjs-scheduler/_next/static/{UCUuluTca8pS8EyjYfV8y => WOBtSUHsV6HcsuY6KXQXp}/_buildManifest.js (100%) rename examples/nextjs-scheduler/_next/static/{UCUuluTca8pS8EyjYfV8y => WOBtSUHsV6HcsuY6KXQXp}/_ssgManifest.js (100%) rename examples/nextjs-scheduler/_next/static/chunks/app/{page-d016d69fc00264ed.js => page-eccac34c2844a9ff.js} (99%) rename examples/profile-stack/assets/{index-1jBrjG-X.js => index-Cw6-JyZY.js} (99%) rename examples/react-tldraw/assets/{index-BIdlKhE_.js => index-Dn-3KynT.js} (99%) rename examples/react-todomvc/assets/{index-0iJGe1Ls.js => index-DIeJWN1h.js} (99%) rename examples/simultaneous-cursors/assets/{index-BXKIYS9E.js => index-CfPS2aDQ.js} (99%) rename examples/vanilla-codemirror6/assets/{index-DWRqngRf.js => index-DB4O8pnL.js} (99%) rename examples/vanilla-quill/assets/{index-CKJvWhky.js => index-DYVWARJt.js} (99%) rename examples/vuejs-kanban/assets/{index-BqVvB3pR.js => index-ClPsSZVC.js} (99%) diff --git a/api-reference/classes/Change.html b/api-reference/classes/Change.html index 864e9b1af..a7827b988 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

  • 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 diff --git a/api-reference/classes/Client.html b/api-reference/classes/Client.html index f986bcb2a..c199b26a2 100644 --- a/api-reference/classes/Client.html +++ b/api-reference/classes/Client.html @@ -1,7 +1,7 @@ Client | yorkie-js-sdk

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

-

Constructors

Constructors

Properties

Constructors

Properties

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

Type declaration

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

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      +

Returns Client

Properties

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

Type declaration

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

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

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

      Generated

      from rpc yorkie.v1.YorkieService.AttachDocument

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

      Generated

      from rpc yorkie.v1.YorkieService.Broadcast

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

      Generated

      from rpc yorkie.v1.YorkieService.DeactivateClient

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

      Generated

      from rpc yorkie.v1.YorkieService.PushPullChanges

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

      Generated

      from rpc yorkie.v1.YorkieService.RemoveDocument

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

      Generated

      from rpc yorkie.v1.YorkieService.WatchDocument

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

Type declaration

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

Methods

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

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

    Type declaration

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

    Methods

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

      -

      Returns Promise<void>

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

      Returns Promise<void>

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

      -

      Type Parameters

      Parameters

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

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      -

      Parameters

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

      Returns Promise<void>

    • deactivate deactivates this client.

      -

      Returns Promise<void>

    • broadcast broadcasts the given payload to the given topic.

      +

      Parameters

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

      Returns Promise<void>

    • deactivate deactivates this client.

      +

      Returns Promise<void>

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

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

      -

      Type Parameters

      Parameters

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

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      -

      Parameters

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

      Returns Promise<any>

    • getID returns a ActorID of client.

      -

      Returns undefined | string

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

      Type Parameters

      Parameters

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

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      +

      Parameters

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

      Returns Promise<any>

    • getID returns a ActorID of client.

      +

      Returns undefined | string

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

      -

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

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

      Returns void

    • isActive checks if the client is active.

      -

      Returns boolean

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

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

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

      Returns void

    • isActive checks if the client is active.

      +

      Returns boolean

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

      -

      Returns Promise<void>

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

      Returns Promise<void>

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

      -

      Returns void

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

      Returns void

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

      -

      Parameters

      • docKey: string

      Returns Promise<void>

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

      Parameters

      • docKey: string

      Returns Promise<void>

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

      -

      Type Parameters

      Parameters

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

    \ No newline at end of file +

    Type Parameters

    Parameters

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

    \ No newline at end of file diff --git a/api-reference/classes/Counter.html b/api-reference/classes/Counter.html index 40f21dba3..24283aa5b 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

    • 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 diff --git a/api-reference/classes/Document.html b/api-reference/classes/Document.html index 54b363287..99357b248 100644 --- a/api-reference/classes/Document.html +++ b/api-reference/classes/Document.html @@ -1,6 +1,6 @@ Document | yorkie-js-sdk

    Class Document<T, P>

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

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Constructors

    Properties

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

    Type declaration

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

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

    +

    Constructors

    Properties

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

    Type declaration

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

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

    Type declaration

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

          Returns boolean

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

          Returns boolean

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

          Returns void

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

          -

          Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    -
    isUpdating: boolean

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

    Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    +
    isUpdating: boolean

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

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

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

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

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

    -
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      -

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

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

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

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

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

    +
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      +

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

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

      Parameters

      • pack: ChangePack<P>

        change pack

        -

      Returns void

    • applySnapshot applies the given snapshot into this document.

      -

      Parameters

      • serverSeq: bigint
      • Optional snapshot: Uint8Array

      Returns void

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

      -

      Parameters

      • resp: WatchDocumentResponse

      Returns void

    • broadcast the payload to the given topic.

      -

      Parameters

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

      Returns void

    • canRedo returns whether there are any operations to redo.

      -

      Returns boolean

    • canUndo returns whether there are any operations to undo.

      -

      Returns boolean

    • Internal

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

    Returns void

    \ No newline at end of file +

    Returns void

    \ No newline at end of file diff --git a/api-reference/classes/Primitive.html b/api-reference/classes/Primitive.html index 8637d7af7..f18a6706e 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 c28827b20..610e7e98c 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 30abaecd3..02b4a3e8c 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 ad03b138a..343dd62c7 100644 --- a/api-reference/classes/Tree.html +++ b/api-reference/classes/Tree.html @@ -1,6 +1,6 @@ Tree | yorkie-js-sdk

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

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

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

    Methods

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

    Constructors

    Properties

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

    Methods

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

      -

      Parameters

      Returns CRDTTreeNode

    • edit edits this tree with the given nodes.

      -

      Parameters

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

      Returns boolean

    • editBulk edits this tree with the given nodes.

      -

      Parameters

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

      Returns boolean

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

      -

      Parameters

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

      Returns boolean

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

      -

      Parameters

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

      Returns boolean

    • Parameters

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

      Returns boolean

    • getIndexTree returns the index tree of this tree.

      -

      Returns IndexTree<CRDTTreeNode>

    • indexToPath returns the path of the given index.

      -

      Parameters

      • index: number

      Returns number[]

    • Internal

      initialize initialize this tree with context and internal tree.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • tree: CRDTTree

      Returns void

    • pathToIndex returns the index of given path.

      -

      Parameters

      • path: number[]

      Returns number

    • posRangeToPathRange converts the position range into the path range.

      -

      Parameters

      Returns [number[], number[]]

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

      -

      Parameters

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

      Returns void

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

      -

      Parameters

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

      Returns void

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

      -

      Parameters

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

      Returns void

    \ No newline at end of file +

    Parameters

    Returns CRDTTreeNode

    \ No newline at end of file diff --git a/api-reference/enums/ClientCondition.html b/api-reference/enums/ClientCondition.html index f25fd3867..1437b05fd 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 c9c879bd9..c8c5205f5 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 95eb57b40..ab9cc4e42 100644 --- a/api-reference/enums/DocEventType.html +++ b/api-reference/enums/DocEventType.html @@ -1,5 +1,5 @@ DocEventType | yorkie-js-sdk

    Enumeration DocEventType

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

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Broadcast: "broadcast"

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

    -
    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    -
    Initialized: "initialized"

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

    -
    LocalBroadcast: "local-broadcast"

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

    -
    LocalChange: "local-change"

    local document change event type

    -
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    -
    RemoteChange: "remote-change"

    remote document change event type

    -
    Snapshot: "snapshot"

    snapshot event type

    -
    StatusChanged: "status-changed"

    status changed event type

    -
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    -
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    -
    Watched: "watched"

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

    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    +
    Initialized: "initialized"

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

    +
    LocalBroadcast: "local-broadcast"

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

    +
    LocalChange: "local-change"

    local document change event type

    +
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    +
    RemoteChange: "remote-change"

    remote document change event type

    +
    Snapshot: "snapshot"

    snapshot event type

    +
    StatusChanged: "status-changed"

    status changed event type

    +
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    +
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    +
    Watched: "watched"

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

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

    Enumeration DocumentStatus

    DocumentStatus represents the status of the document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Attached: "attached"

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

    -
    Detached: "detached"

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

    Detached: "detached"

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

    -
    Removed: "removed"

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

    Removed: "removed"

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

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

    Enumeration DocumentSyncStatus

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

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncFailed: "sync-failed"

    SyncFiled means that document synchronization has failed.

    -
    Synced: "synced"

    Synced means that document synced successfully.

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

    Synced means that document synced successfully.

    +
    \ No newline at end of file diff --git a/api-reference/enums/LogLevel.html b/api-reference/enums/LogLevel.html index e64e973b4..50d455902 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 dac3bd54f..fcd920706 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 061c7fc0f..80aac686a 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 8fb46c85d..086967a92 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 c9962ce37..be8dfc8c9 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 c2e251503..daa4754c0 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 c18d3dbc5..701baf8df 100644 --- a/api-reference/interfaces/ClientOptions.html +++ b/api-reference/interfaces/ClientOptions.html @@ -1,5 +1,5 @@ ClientOptions | yorkie-js-sdk

    Interface ClientOptions

    ClientOptions are user-settable options used when defining clients.

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

    Properties

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

    Properties

    apiKey?: string

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

    -
    key?: string

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

    key?: string

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

    -
    reconnectStreamDelay?: number

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

    reconnectStreamDelay?: number

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

    -
    retrySyncLoopDelay?: number

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

    retrySyncLoopDelay?: number

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

    -
    syncLoopDuration?: number

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

    syncLoopDuration?: number

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

    -
    token?: string

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

    token?: string

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

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/ConnectionChangedEvent.html b/api-reference/interfaces/ConnectionChangedEvent.html index 68669a5df..7f1458347 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 +
    \ No newline at end of file diff --git a/api-reference/interfaces/InitializedEvent.html b/api-reference/interfaces/InitializedEvent.html index 0f6dd35dc..f454e020d 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 e5ecfcd41..0976518f4 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 b74cf4c87..3136b7d7c 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 efadaeab3..b66c06187 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 2b50f6746..f68778a22 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 7ce6441f1..f06ac3173 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 e89386d84..501fa10f1 100644 --- a/api-reference/interfaces/SnapshotEvent.html +++ b/api-reference/interfaces/SnapshotEvent.html @@ -1,7 +1,7 @@ SnapshotEvent | yorkie-js-sdk

    Interface SnapshotEvent

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

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

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

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

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

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

    Type declaration

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

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

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

    Type declaration

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

    Interface SyncStatusChangedEvent

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

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

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

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

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    Properties

    enum DocEventType.SyncStatusChanged

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/UnwatchedEvent.html b/api-reference/interfaces/UnwatchedEvent.html index 9cb640932..946dbb947 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 fc75fce6c..ebcb1a429 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 2b19c043b..424e4aae5 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 0cd79d1b8..ea84df234 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 60812da13..d1daa18b9 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 16b536a0d..91b8b0429 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 8ec99dfcb..6acc1e1b7 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 bd929b6b1..aa23b54ba 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 876ec49fd..2208793c0 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 6d7da9a7f..de1c7cbf6 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 e66a67322..abbb6e265 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 36e1db94a..aca74de60 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 db1aab0ac..a69b2d9c2 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 c39e73729..ed318c37e 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 5b9fa2fdf..e74d3ef44 100644 --- a/api-reference/types/DocEvent.html +++ b/api-reference/types/DocEvent.html @@ -1,3 +1,3 @@ DocEvent | yorkie-js-sdk

    Type alias DocEvent<P, T>

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

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

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/EditOpInfo.html b/api-reference/types/EditOpInfo.html index 2862371ca..681cba979 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 1cfc32a07..4cc8ad6cf 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 c4a0bc78c..cb365e66e 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 4f01f2d5e..d465fcd06 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 e062ef127..a3ebe9543 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 a6f54ba4a..909e84333 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 1fa57f9de..a2536018b 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 f2825b47f..c25ae7b9b 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 c5401962f..b95491c6f 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 3d4e22791..9b97b27b8 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 94897c649..e1fd4418b 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 a142f7e67..585f1a75f 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 55960eaeb..9f09e88b0 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 f40b68821..ada958c07 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 a33e10501..915c3a221 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 27cdb65dc..b3906b3e1 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 3f41aa0c4..12451a367 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 b7dcec5fd..a390b66dc 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 a63a3b8e6..d0190659e 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 1d321475e..62bbaa09c 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 1686dcb2e..5e633ddaf 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 76f777811..2826ffca2 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 f21c6de26..721fbbc97 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 27db49a1a..82cc81082 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 b5f62825e..2f3447d2f 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 ad83c5802..8447d6100 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 43297874f..ef5f69c5e 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 650bd1b35..9afda4cfa 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 52afeffc1..e85c055c1 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 5866c7af4..b6d817b57 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 4cc48df2f..685bffaf5 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 48dc7488e..e34f07b3e 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 ba66aa800..5a826ee2e 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 d8aa32c74..d1e88fa1c 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 52e0a8c1d..d17f82347 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 4a77956bf..440cd4ac6 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 84d1d4b32..01f608878 100644 --- a/api-reference/variables/converter.html +++ b/api-reference/variables/converter.html @@ -17,4 +17,4 @@

    Parameters

    Returns string

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

    Parameters

    Returns Uint8Array

    \ No newline at end of file diff --git a/api-reference/variables/default.html b/api-reference/variables/default.html index 59fbfcace..a98033118 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 c6968d9f5..a69948042 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/UCUuluTca8pS8EyjYfV8y/_buildManifest.js b/examples/nextjs-scheduler/_next/static/WOBtSUHsV6HcsuY6KXQXp/_buildManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/UCUuluTca8pS8EyjYfV8y/_buildManifest.js rename to examples/nextjs-scheduler/_next/static/WOBtSUHsV6HcsuY6KXQXp/_buildManifest.js diff --git a/examples/nextjs-scheduler/_next/static/UCUuluTca8pS8EyjYfV8y/_ssgManifest.js b/examples/nextjs-scheduler/_next/static/WOBtSUHsV6HcsuY6KXQXp/_ssgManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/UCUuluTca8pS8EyjYfV8y/_ssgManifest.js rename to examples/nextjs-scheduler/_next/static/WOBtSUHsV6HcsuY6KXQXp/_ssgManifest.js diff --git a/examples/nextjs-scheduler/_next/static/chunks/app/page-d016d69fc00264ed.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-eccac34c2844a9ff.js similarity index 99% rename from examples/nextjs-scheduler/_next/static/chunks/app/page-d016d69fc00264ed.js rename to examples/nextjs-scheduler/_next/static/chunks/app/page-eccac34c2844a9ff.js index 1461f844f..7ddbd2652 100644 --- a/examples/nextjs-scheduler/_next/static/chunks/app/page-d016d69fc00264ed.js +++ b/examples/nextjs-scheduler/_next/static/chunks/app/page-eccac34c2844a9ff.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1807))},1807:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return ng}});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,O,B,J,L,_,M,q,K,z=r(3165),F=r(7397),U=r.n(F),j=r(6189);let V=["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:ew},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:ez}}]);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:eF},{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}]);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:eo,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}]);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.body={case:void 0},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.Operation",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ea,oneof:"body"},{no:2,name:"add",kind:"message",T:ec,oneof:"body"},{no:3,name:"move",kind:"message",T:el,oneof:"body"},{no:4,name:"remove",kind:"message",T:eh,oneof:"body"},{no:5,name:"edit",kind:"message",T:ed,oneof:"body"},{no:6,name:"select",kind:"message",T:eu,oneof:"body"},{no:7,name:"style",kind:"message",T:eg,oneof:"body"},{no:8,name:"increase",kind:"message",T:ef,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:em,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ep,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ey,oneof:"body"}]);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.key="",Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation.Set",ea.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:ev},{no:4,name:"executed_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(),Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Add",ec.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:ev},{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.Move",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:"created_at",kind:"message",T:ej},{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.Remove",eh.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 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.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Edit",ed.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 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(),Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Select",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:"executed_at",kind:"message",T:ej}]);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.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Style",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:"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 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(),Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Increase",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ev},{no:3,name:"executed_at",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(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.TreeEdit",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eB},{no:3,name:"to",kind:"message",T:eB},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eN,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,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.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeStyle",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eB},{no:3,name:"to",kind:"message",T:eB},{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 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(),Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.ArraySet",ey.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:ev},{no:4,name:"executed_at",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(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.JSONElementSimple",ev.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 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.body={case:void 0},Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElement",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eA,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eT,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eS,oneof:"body"},{no:5,name:"text",kind:"message",T:eI,oneof:"body"},{no:6,name:"counter",kind:"message",T:eC,oneof:"body"},{no:7,name:"tree",kind:"message",T:ex,oneof:"body"}]);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.nodes=[],Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement.JSONObject",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eP,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 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.JSONArray",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.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.Primitive",eS.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 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.nodes=[],Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Text",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ek,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 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.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Counter",eC.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 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.nodes=[],Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Tree",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eR,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 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.key="",Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.RHTNode",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:ew}]);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(),Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RGANode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eE},{no:2,name:"element",kind:"message",T:ew}]);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.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.NodeAttr",eb.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 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.attributes={},Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.TextNode",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eD},{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:eD},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eb}}]);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.offset=0,Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNodeID",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);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.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TreeNode",eR.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:eb}}]);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.content=[],Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNodes",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eR,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 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.TreePos",eB.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 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.id="",this.username="",Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.User",eJ.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 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.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.Project",eL.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 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(),Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.UpdatableProjectFields",e_.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:eM},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);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(),this.methods=[],Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);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.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.DocumentSummary",eq.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:ez}]),(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 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.data={},Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.Presence",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);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.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Checkpoint",eF.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 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.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.DocEventBody",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",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.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEvent",eW.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:eV}]);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.clientKey="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.ActivateClientRequest",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);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.clientId="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientResponse",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",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.DeactivateClientRequest",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(),Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientResponse",eZ.fields=Q.w.util.newFieldList(()=>[]);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.clientId="",Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.AttachDocumentRequest",eX.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);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.documentId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentResponse",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_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.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.DetachDocumentRequest",e$.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 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(),Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentResponse",e0.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);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(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.WatchDocumentRequest",e1.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);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.body={case:void 0},Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentResponse",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e3,oneof:"body"},{no:2,name:"event",kind:"message",T:eW,oneof:"body"}]);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.clientIds=[],Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);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.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.RemoveDocumentRequest",e9.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 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(),Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentResponse",e4.fields=Q.w.util.newFieldList(()=>[{no:1,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(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.PushPullChangesRequest",e8.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 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(),Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesResponse",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);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(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.BroadcastRequest",e6.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 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(),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastResponse",e7.fields=Q.w.util.newFieldList(()=>[]);var te=r(6438);let tt={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eG,O:eH,kind:te.t.Unary},deactivateClient:{name:"DeactivateClient",I:eY,O:eZ,kind:te.t.Unary},attachDocument:{name:"AttachDocument",I:eX,O:eQ,kind:te.t.Unary},detachDocument:{name:"DetachDocument",I:e$,O:e0,kind:te.t.Unary},removeDocument:{name:"RemoveDocument",I:e9,O:e4,kind:te.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e8,O:e5,kind:te.t.Unary},watchDocument:{name:"WatchDocument",I:e1,O:e2,kind:te.t.ServerStreaming},broadcast:{name:"Broadcast",I:e6,O:e7,kind:te.t.Unary}}};var tr=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";class tn 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 ti(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 ts=e=>!e||0===Object.entries(e).length,to=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},ta=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 tc{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ti(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 tl="000000000000000000000000";class th{static of(e,t,r){return new th(e,t,r)}static fromStruct(e){return th.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 th(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 td=new th(0n,0,tl),tu=new th(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");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}})}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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new tn(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 tn(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,td);e.setRemovedAt(td),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:ta(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):td:tu;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:ta(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}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:ta(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tB(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){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tB))throw new tn(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,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){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tB))throw new tn(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let 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 tn(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new tn(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new tn(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new tn(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 tn(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 tn(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tz{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new tn(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new tn(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new tn(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){tK(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 tn(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 tn(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 tn(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 tn(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 tU(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(th.fromStruct(e.parentID.createdAt),e.parentID.offset),tG.of(th.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 tn(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(th.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 tn(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new tn(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){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new 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=ta(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[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):td:tu;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):td:tu;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tN),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):td:tu;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tY(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new tn(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?ta(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 tz(e),this.nodeMapByID=new tV(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){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tX))throw new tn(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>th.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath: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${static of(e,t,r,n){return new t$(e,t,r,n)}next(){return new t$(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new t$(this.clientSeq,e,this.actor):new t$(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return th.of(this.lamport,e,this.actor)}setActor(e){return new t$(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n){this.clientSeq=e,this.serverSeq=n,this.lamport=t,this.actor=r}}let t0=new t$(0,0n,tl);class t1{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t1({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ti(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:rq.bytesToHex(rq.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rq.bytesToHex(rq.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t1.create({id:rq.bytesToChangeID(rq.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rq.bytesToOperation(rq.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 t2{static create(e,t,r,n,i,s){return new t2(e,t,r,n,i,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}constructor(e,t,r,n,i,s){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=i,this.minSyncedTicket=s}}class t3{static of(e,t){return new t3(e,t)}increaseClientSeq(e){return 0===e?this:new t3(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 t3.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 t9=new t3(0n,0);class t4{static of(e,t){return new t4(e,t)}static fromStruct(e){return t4.of(th.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 t4(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 t8=t4.of(td,0);class t5{static of(e,t){return new t5(e,t)}static fromStruct(e){let t=t4.fromStruct(e.id);return t5.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t4.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 t6 extends tA{static create(e,t){return new t6(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 tn(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){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):td:tu;a.canDelete(t,o)?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 rt extends tf{static create(e,t,r){return new rt(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 tn(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=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":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!!rt.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 tn(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+re(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=re(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tS.Z.fromNumber(t):this.value=t;break;default:throw new tn(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rr extends tw{static create(e,t,r){return new rr(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof rt))throw new tn(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 rr.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 rn extends tw{static create(e,t,r,n,i,s){return new rn(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new rn(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tX))throw new tn(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}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath: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 ri(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rM(e.getActorID())})}function rs(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rM(e.getActorID())})}function ro(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 tn(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ra(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new tn(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rc(e){if(e instanceof tv)return new ev({type:S.JSON_OBJECT,createdAt:rs(e.getCreatedAt()),value:rL(e)});if(e instanceof tP)return new ev({type:S.JSON_ARRAY,createdAt:rs(e.getCreatedAt()),value:rf(e).toBinary()});if(e instanceof tB)return new ev({type:S.TEXT,createdAt:rs(e.getCreatedAt())});if(e instanceof tI)return new ev({type:ro(e.getType()),createdAt:rs(e.getCreatedAt()),value:e.toBytes()});if(e instanceof rt)return new ev({type:ra(e.getType()),createdAt:rs(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tX)return new ev({type:S.TREE,createdAt:rs(e.getCreatedAt()),value:rm(e).toBinary()});throw new tn(x.ErrUnimplemented,"unimplemented element")}function rl(e){return new eU({createdAt:rs(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rh(e){return new eB({parentId:rd(e.getParentID()),leftSiblingId:rd(e.getLeftSiblingID())})}function rd(e){return new eO({createdAt:rs(e.getCreatedAt()),offset:e.getOffset()})}function ru(e){let t=new eo;if(e instanceof tb){let r=new ea;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.key=e.getKey(),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tk){let r=new ec;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.prevCreatedAt=rs(e.getPrevCreatedAt()),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.prevCreatedAt=rs(e.getPrevCreatedAt()),r.createdAt=rs(e.getCreatedAt()),r.executedAt=rs(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tE){let r=new eh;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.createdAt=rs(e.getCreatedAt()),r.executedAt=rs(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tJ){let r=new ed;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rl(e.getFromPos()),r.to=rl(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rs(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tL){let r=new eg;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rl(e.getFromPos()),r.to=rl(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rs(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rr){let r=new ef;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tQ){let r=new em,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rh(e.getFromPos()),r.to=rh(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eN({content:rg(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rs(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof rn){let r=new ep;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rh(e.getFromPos()),r.to=rh(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(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=rs(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new tn(x.ErrUnimplemented,"unimplemented operation");return t}function rg(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eR({id:rd(e.id),type:e.type,removedAt:rs(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rd(e.insPrevID)),e.insNextID&&(n.insNextId=rd(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new eb({value:r.getValue(),updatedAt:rs(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rf(e){let t=new ew;return t.body.case="jsonArray",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({element:rp(r.getValue())}));return t}(e.getElements()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}function rm(e){let t=new ew;return t.body.case="tree",t.body.value=new ex({nodes:rg(e.getRoot()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}function rp(e){if(e instanceof tv)return function(e){let t=new ew;return t.body.case="jsonObject",t.body.value=new eA({nodes:function(e){let t=[];for(let r of e)t.push(new eP({key:r.getStrKey(),element:rp(r.getValue())}));return t}(e.getRHT()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tP)return rf(e);if(e instanceof tI)return function(e){let t=new ew;return t.body.case="primitive",t.body.value=new eS({type:ro(e.getType()),value:e.toBytes(),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tB)return function(e){let t=new ew;return t.body.case="text",t.body.value=new eI({nodes:function(e){let t=[];for(let n of e){var r;let e=new ek;e.id=new eD({createdAt:rs((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rs(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new eb;t.value=e.getValue(),t.updatedAt=rs(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof rt)return function(e){let t=new ew;return t.body.case="counter",t.body.value=new eC({type:ra(e.getType()),value:e.toBytes(),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tX)return rm(e);throw new tn(x.ErrUnimplemented,"unimplemented element")}function ry(e){for(let t of e.findDetails(tr.Qf))if(t.metadata.code)return t.metadata.code;return""}function rv(e){return t$.of(e.clientSeq,BigInt(e.lamport),r_(e.actorId),BigInt(e.serverSeq))}function rw(e){if(e)return th.of(BigInt(e.lamport),e.delimiter,r_(e.actorId))}function rA(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rT(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 tn(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rS(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new tn(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rI(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tv.create(rw(e.createdAt));return rJ(e.value);case S.JSON_ARRAY:if(!e.value)return tP.create(rw(e.createdAt));return function(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rN(ew.fromBinary(e).body.value)}(e.value);case S.TEXT:return tB.create(t7.create(),rw(e.createdAt));case S.TREE:return function(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rO(ew.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(rT(e.type),e.value),rw(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return rt.create(rS(e.type),rt.valueFromBytes(rS(e.type),e.value),rw(e.createdAt))}}function rC(e){return t5.of(t4.of(rw(e.createdAt),e.offset),e.relativeOffset)}function rx(e){return t4.of(rw(e.createdAt),e.offset)}function rP(e){return tW.of(rE(e.parentId),rE(e.leftSiblingId))}function rE(e){return tG.of(rw(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=rE(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,rw(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rE(e.insPrevId)),e.insNextId&&(r.insNextID=rE(e.insNextId)),r.removedAt=rw(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,td).getRoot()}function rk(e){if("set"===e.body.case){let t=e.body.value;return tb.create(t.key,rI(t.value),rw(t.parentCreatedAt),rw(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tk.create(rw(t.parentCreatedAt),rw(t.prevCreatedAt),rI(t.value),rw(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tD.create(rw(t.parentCreatedAt),rw(t.prevCreatedAt),rw(t.createdAt),rw(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tE.create(rw(t.parentCreatedAt),rw(t.createdAt),rw(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,rw(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tJ.create(rw(t.parentCreatedAt),rC(t.from),rC(t.to),r,t.content,n,rw(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,rw(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rw(t.parentCreatedAt),rC(t.from),rC(t.to),r,n,rw(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rr.create(rw(t.parentCreatedAt),rI(t.value),rw(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,rw(n))}),tQ.create(rw(t.parentCreatedAt),rP(t.from),rP(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,rw(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,rw(r))}),(null==n?void 0:n.length)>0)?rn.createTreeRemoveStyleOperation(rw(t.parentCreatedAt),rP(t.from),rP(t.to),i,n,rw(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),rn.create(rw(t.parentCreatedAt),rP(t.from),rP(t.to),i,r,rw(t.executedAt)))}else throw new tn(x.ErrUnimplemented,"unimplemented operation")}function rD(e){let t=[];for(let r of e)t.push(t1.create({id:rv(r.id),operations:function(e){let t=[];for(let r of e){let e=rk(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rA(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new tn(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rR(e){let t=new ty;for(let r of e.nodes){let e=rB(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tv(rw(e.createdAt),t);return r.setMovedAt(rw(e.movedAt)),r.setRemovedAt(rw(e.removedAt)),r}function rN(e){let t=new tx;for(let r of e.nodes)t.insert(rB(r.element));let r=new tP(rw(e.createdAt),t);return r.setMovedAt(rw(e.movedAt)),r.setRemovedAt(rw(e.removedAt)),r}function rO(e){let t=rb(e.nodes);return tX.create(t,rw(e.createdAt))}function rB(e){if("jsonObject"===e.body.case)return rR(e.body.value);if("jsonArray"===e.body.case)return rN(e.body.value);if("primitive"===e.body.case)return function(e){let t=tI.of(tI.valueFromBytes(rT(e.type),e.value),rw(e.createdAt));return t.setMovedAt(rw(e.movedAt)),t.setRemovedAt(rw(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new t7,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tO.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rw(n.updatedAt))});let r=t6.create(rx(e.id),t);return r.remove(rw(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rx(n.insPrevId))),r=e}let n=new tB(t,rw(e.createdAt));return n.setMovedAt(rw(e.movedAt)),n.setRemovedAt(rw(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=rt.create(rS(e.type),rt.valueFromBytes(rS(e.type),e.value),rw(e.createdAt));return t.setMovedAt(rw(e.movedAt)),t.setRemovedAt(rw(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rO(e.body.value);throw new tn(x.ErrUnimplemented,"unimplemented element")}function rJ(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rR(ew.fromBinary(e).body.value)}function rL(e){return rp(e).toBinary()}function r_(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rM(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rq={fromPresence:rA,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eF({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:ri(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(ru(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 ez,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 tn(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:rs(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t2.create(e.documentKey,(t=e.checkpoint,t3.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rD(e.changes),e.snapshot,rw(e.minSyncedTicket))},fromChanges:rD,toTreeNodes:rg,fromTreeNodes:rb,objectToBytes:rL,bytesToObject:rJ,bytesToSnapshot:function(e){if(!e)return{root:tv.create(td),presences:new Map};let t=er.fromBinary(e);return{root:rB(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rA(n))}),t}(t.presences)}},bytesToHex:r_,hexToBytes:rM,toHexString:function(e){return r_(e)},toUint8Array:function(e){return rM(e)},toOperation:ru,toChangeID:ri,PbChangeID:es,bytesToChangeID:function(e){return rv(es.fromBinary(e))},bytesToOperation:function(e){return rk(eo.fromBinary(e))}};(f=O||(O={}))[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 rK=3;function rz(e){rK=e}let rF={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;rrK<=e};function rU(){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 rj{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 rV=()=>{};class rW{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 tn(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new tn(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=rV),void 0===n.error&&(n.error=rV),void 0===n.complete&&(n.complete=rV);let i=rU(),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){rF.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=ti(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class rH{static create(){return new rH(tv.create(td))}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 tn(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 rH(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r);n.element.getRemovedAt()&&e.compare(n.element.getRemovedAt())>=0&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();void 0!==n&&e.compare(n)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tB||e instanceof tX)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function rY(e,t){let r=new rZ(e);return new Proxy(t,r.getHandlers())}class rZ{static setInternal(e,t,r,n){if(r.includes("."))throw new tn(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=r8(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 tn(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=r8(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)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),rZ.setInternal(e,t,r,n),!0),get:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():r4(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]")),rZ.deleteInternal(e,t,r),!0)}}}class rX{static*iteratorInternal(e,t){for(let r of t)yield r9(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=r8(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return rX.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=r8(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 rX.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=>r4(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>r4(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=>r4(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 r9(e,n)}:"getElementByIndex"===r?r=>r9(e,t.get(r)):"getLast"===r?()=>r9(e,t.getLast()):"deleteByID"===r?r=>{let n=rX.deleteInternalByID(e,t,r);return r9(e,n)}:"insertAfter"===r?(r,n)=>{let i=rX.insertAfterInternal(e,t,r,n);return r9(e,i)}:"insertBefore"===r?(r,n)=>{let i=rX.insertBeforeInternal(e,t,r,n);return r9(e,i)}:"moveBefore"===r?(r,n)=>{rX.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{rX.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{rX.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{rX.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?r4(e,t.get(Number(r))):"push"===r?r=>rX.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;orX.includes(e,t,r,n):"indexOf"===r?(r,n)=>rX.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>rX.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>rX.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;sr4(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("array[".concat(r,"]")),rX.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class rQ{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new tn(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rF.isEnabled(O.Debug)&&rF.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?to(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 tn(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new tn(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rF.isEnabled(O.Debug)&&rF.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=to(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 tn(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 tn(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([t5.fromStruct(e[0]),t5.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new tn(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 tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r${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 tn(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(rr.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new tn(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r0(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===t_){r1(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&&!ts(a)){let e=to(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))r0(e,c,r)}}function r1(e){if(!e.value.length)throw new tn(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r2(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 tn(x.ErrInvalidArgument,"element node and text node cannot be passed together");r1(t)}else for(let t of e){let{type:e}=t;if(e===t_)throw new tn(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r3{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)r0(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new tn(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?to(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(rn.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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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?to(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(rn.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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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(rn.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]&&(r2(r),r[0].type!==t_))for(let e of r){let{children:t=[]}=e;r2(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&&!ts(a)){let e=to(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))r0(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new tn(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new tn(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new tn(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 tn(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 r9(e,t){if(t){if(t instanceof tI)return t;if(t instanceof tv)return rY(e,t);if(t instanceof tP)return function(e,t){let r=new rX(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tB)return new rQ(e,t);else if(t instanceof rt){let r=new r$(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tX){let r=new r3;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function r4(e,t){let r=r9(e,t);return r instanceof tI?r.getValue():r}function r8(e,t,r){let n;if(tI.isSupport(t))n=tI.of(t,r);else if(Array.isArray(t))n=tP.create(r,rX.buildArrayElements(e,t));else if("object"==typeof t)t instanceof rQ?(n=tB.create(t7.create(),r),t.initialize(e,n)):t instanceof r$?(n=rt.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r3?(n=tX.create(t.buildRoot(e),r),t.initialize(e,n)):n=tv.create(r,rZ.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class r5{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 r6="disconnected",r7=new Map,ne=new Map;function nt(e,t){((null==t?void 0:t.force)||"disconnected"!==r6)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ne,(m=B||(B={})).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",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class nr{update(e,t){if("removed"===this.getStatus())throw new tn(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),rY(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tc(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rF.isEnabled(O.Trivial)&&rF.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),rF.isEnabled(O.Trivial)&&rF.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new tn(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):"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 tn(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])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),E.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,E.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),rF.isEnabled(O.Trivial)&&rF.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:ti(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t2.create(this.key,t,!1,e)}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),rY(rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){let{root:r,presences:n}=rq.bytesToSnapshot(t);this.root=new rH(r),this.presences=n,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:E.Remote,value:{snapshot:this.isEnableDevtools()?rq.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){for(let r of(rF.isEnabled(O.Debug)&&rF.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rF.isEnabled(O.Trivial)&&rF.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rF.isEnabled(O.Debug)&&rF.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.syncLamport(e.getID().getLamport()),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)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(tl),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}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rq.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t1.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 tn(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?ti(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?ti(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ti(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ti(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ti(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new tn(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new tn(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tc(t,ti(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 tn(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new tn(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tc(t,ti(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}])}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=rH.create(),this.changeID=t0,this.checkpoint=t9,this.localChanges=[],this.eventStream=function(e){let t=new rW(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 r5,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()||r7.has(e.getKey()))return;ne.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)||(ne.get(e.getKey()).push(t),"synced"===r6&&nt({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});r7.set(e.getKey(),[t]),nt({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"!==r6)break;r6="connected",nt({msg:"doc::available",docKey:e.getKey()}),rF.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":r6="disconnected",rF.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":r6="synced",nt({msg:"doc::sync::full",docKey:e.getKey(),events:ne.get(e.getKey())}),rF.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nn=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.1"}');let ni=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=K||(K={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let ns={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},no={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class na{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rF.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rF.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rF.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rF.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new tn(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:rq.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let r=rq.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()===B.Removed||(e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rj(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rF.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'))),e}).catch(e=>{throw rF.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new tn(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:rq.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=rq.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rF.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rF.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new tn(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 tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new tn(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rF.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rF.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new tn(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rq.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=rq.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rF.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rF.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new tn(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!ni(r))throw new tn(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:no.maxRetries,a=no.maxBackoff,c=0,l=e=>Math.min(no.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(()=>{rF.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rF.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rF.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rF.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rF.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rF.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rF.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 tn(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 tn(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}]),rF.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}]),rF.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===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(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rq.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rq.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()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rF.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rF.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((ry(e)===x.ErrClientNotActivated||ry(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){rF.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||ns,this.key=t.key?t.key:rU(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ns.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ns.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ns.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tt,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nn.u2+"/"+nn.i8),await e(t))]})),this.taskQueue=[]}}var nc={Client:na,Document:nr,Primitive:tI,Text:rQ,Counter:r$,Tree:r3,LogLevel:O,setLogLevel:rz,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:na,Document:nr,Primitive:tI,Text:rQ,Counter:r$,Tree:r3,LogLevel:O,setLogLevel:rz,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nl=r(6182);function nh(e){let{content:t,actions:r}=e,[n,i]=(0,j.useState)(new Date),[s,o]=(0,j.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,z.jsx)("article",{children:(0,z.jsxs)("div",{children:[(0,z.jsx)(nl.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,z.jsxs)("p",{children:["selected day : ",a]}),(0,z.jsx)("div",{className:U().memo,children:t.map((e,t)=>{if(e.date===a)return(0,z.jsx)("p",{children:e.text},t)})}),(0,z.jsxs)("div",{className:U().inputForm_editor,children:[(0,z.jsx)("h3",{children:"input form"}),(0,z.jsx)("textarea",{className:U().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,z.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,z.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let nd=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],nu="next.js-Scheduler-".concat(W(new Date));function ng(){let[e,t]=(0,j.useState)([]),[r,n]=(0,j.useState)(nd),[i]=(0,j.useState)(()=>new nc.Document(nu));return(0,j.useEffect)(()=>{let e=new nc.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()*V.length);return V[e]}()}}),t.update(e=>{e.content||(e.content=nd)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,z.jsxs)("main",{className:U().main,children:[(0,z.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,z.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,z.jsx)(nh,{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,1807))},1807:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return ng}});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,O,B,J,L,_,M,q,K,z=r(3165),F=r(7397),U=r.n(F),j=r(6189);let V=["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:ew},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:ez}}]);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:eF},{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}]);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:eo,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}]);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.body={case:void 0},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.Operation",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ea,oneof:"body"},{no:2,name:"add",kind:"message",T:ec,oneof:"body"},{no:3,name:"move",kind:"message",T:el,oneof:"body"},{no:4,name:"remove",kind:"message",T:eh,oneof:"body"},{no:5,name:"edit",kind:"message",T:ed,oneof:"body"},{no:6,name:"select",kind:"message",T:eu,oneof:"body"},{no:7,name:"style",kind:"message",T:eg,oneof:"body"},{no:8,name:"increase",kind:"message",T:ef,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:em,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ep,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ey,oneof:"body"}]);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.key="",Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation.Set",ea.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:ev},{no:4,name:"executed_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(),Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Add",ec.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:ev},{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.Move",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:"created_at",kind:"message",T:ej},{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.Remove",eh.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 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.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Edit",ed.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 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(),Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Select",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:"executed_at",kind:"message",T:ej}]);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.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Style",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:"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 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(),Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Increase",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ev},{no:3,name:"executed_at",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(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.TreeEdit",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eB},{no:3,name:"to",kind:"message",T:eB},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eN,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,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.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeStyle",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eB},{no:3,name:"to",kind:"message",T:eB},{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 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(),Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.ArraySet",ey.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:ev},{no:4,name:"executed_at",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(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.JSONElementSimple",ev.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 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.body={case:void 0},Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElement",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eA,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eT,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eS,oneof:"body"},{no:5,name:"text",kind:"message",T:eI,oneof:"body"},{no:6,name:"counter",kind:"message",T:eC,oneof:"body"},{no:7,name:"tree",kind:"message",T:ex,oneof:"body"}]);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.nodes=[],Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement.JSONObject",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eP,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 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.JSONArray",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.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.Primitive",eS.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 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.nodes=[],Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Text",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ek,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 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.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Counter",eC.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 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.nodes=[],Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Tree",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eR,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 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.key="",Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.RHTNode",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:ew}]);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(),Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RGANode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eE},{no:2,name:"element",kind:"message",T:ew}]);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.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.NodeAttr",eb.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 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.attributes={},Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.TextNode",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eD},{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:eD},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:eb}}]);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.offset=0,Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNodeID",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);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.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TreeNode",eR.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:eb}}]);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.content=[],Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNodes",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eR,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 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.TreePos",eB.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 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.id="",this.username="",Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.User",eJ.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 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.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.Project",eL.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 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(),Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.UpdatableProjectFields",e_.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:eM},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);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(),this.methods=[],Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);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.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.DocumentSummary",eq.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:ez}]),(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 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.data={},Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.Presence",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);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.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Checkpoint",eF.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 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.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.DocEventBody",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",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.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEvent",eW.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:eV}]);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.clientKey="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.ActivateClientRequest",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);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.clientId="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientResponse",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",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.DeactivateClientRequest",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(),Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientResponse",eZ.fields=Q.w.util.newFieldList(()=>[]);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.clientId="",Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.AttachDocumentRequest",eX.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);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.documentId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentResponse",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_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.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.DetachDocumentRequest",e$.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 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(),Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentResponse",e0.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);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(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.WatchDocumentRequest",e1.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);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.body={case:void 0},Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentResponse",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e3,oneof:"body"},{no:2,name:"event",kind:"message",T:eW,oneof:"body"}]);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.clientIds=[],Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);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.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.RemoveDocumentRequest",e9.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 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(),Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentResponse",e4.fields=Q.w.util.newFieldList(()=>[{no:1,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(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.PushPullChangesRequest",e8.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 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(),Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesResponse",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);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(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.BroadcastRequest",e6.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 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(),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastResponse",e7.fields=Q.w.util.newFieldList(()=>[]);var te=r(6438);let tt={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eG,O:eH,kind:te.t.Unary},deactivateClient:{name:"DeactivateClient",I:eY,O:eZ,kind:te.t.Unary},attachDocument:{name:"AttachDocument",I:eX,O:eQ,kind:te.t.Unary},detachDocument:{name:"DetachDocument",I:e$,O:e0,kind:te.t.Unary},removeDocument:{name:"RemoveDocument",I:e9,O:e4,kind:te.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e8,O:e5,kind:te.t.Unary},watchDocument:{name:"WatchDocument",I:e1,O:e2,kind:te.t.ServerStreaming},broadcast:{name:"Broadcast",I:e6,O:e7,kind:te.t.Unary}}};var tr=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";class tn 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 ti(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 ts=e=>!e||0===Object.entries(e).length,to=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},ta=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 tc{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ti(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 tl="000000000000000000000000";class th{static of(e,t,r){return new th(e,t,r)}static fromStruct(e){return th.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 th(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 td=new th(0n,0,tl),tu=new th(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");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}})}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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(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 tn(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new tn(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 tn(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,td);e.setRemovedAt(td),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:ta(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):td:tu;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:ta(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}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:ta(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tB(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){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tB))throw new tn(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,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){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tB))throw new tn(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let 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 tn(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new tn(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new tn(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new tn(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 tn(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 tn(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tz{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new tn(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new tn(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new tn(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){tK(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 tn(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 tn(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 tn(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 tn(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 tU(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(th.fromStruct(e.parentID.createdAt),e.parentID.offset),tG.of(th.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 tn(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(th.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 tn(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new tn(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){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new 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=ta(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[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):td:tu;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):td:tu;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tN),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):td:tu;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tY(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new tn(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?ta(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 tz(e),this.nodeMapByID=new tV(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){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tX))throw new tn(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>th.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath: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${static of(e,t,r,n){return new t$(e,t,r,n)}next(){return new t$(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new t$(this.clientSeq,e,this.actor):new t$(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return th.of(this.lamport,e,this.actor)}setActor(e){return new t$(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n){this.clientSeq=e,this.serverSeq=n,this.lamport=t,this.actor=r}}let t0=new t$(0,0n,tl);class t1{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t1({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ti(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:rq.bytesToHex(rq.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rq.bytesToHex(rq.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t1.create({id:rq.bytesToChangeID(rq.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rq.bytesToOperation(rq.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 t2{static create(e,t,r,n,i,s){return new t2(e,t,r,n,i,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}constructor(e,t,r,n,i,s){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=i,this.minSyncedTicket=s}}class t3{static of(e,t){return new t3(e,t)}increaseClientSeq(e){return 0===e?this:new t3(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 t3.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 t9=new t3(0n,0);class t4{static of(e,t){return new t4(e,t)}static fromStruct(e){return t4.of(th.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 t4(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 t8=t4.of(td,0);class t5{static of(e,t){return new t5(e,t)}static fromStruct(e){let t=t4.fromStruct(e.id);return t5.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t4.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 t6 extends tA{static create(e,t){return new t6(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 tn(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){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):td:tu;a.canDelete(t,o)?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 rt extends tf{static create(e,t,r){return new rt(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 tn(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=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":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!!rt.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 tn(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+re(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=re(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tS.Z.fromNumber(t):this.value=t;break;default:throw new tn(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rr extends tw{static create(e,t,r){return new rr(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof rt))throw new tn(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 rr.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 rn extends tw{static create(e,t,r,n,i,s){return new rn(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new rn(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new tn(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tX))throw new tn(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}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath: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 ri(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rM(e.getActorID())})}function rs(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rM(e.getActorID())})}function ro(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 tn(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ra(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new tn(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rc(e){if(e instanceof tv)return new ev({type:S.JSON_OBJECT,createdAt:rs(e.getCreatedAt()),value:rL(e)});if(e instanceof tP)return new ev({type:S.JSON_ARRAY,createdAt:rs(e.getCreatedAt()),value:rf(e).toBinary()});if(e instanceof tB)return new ev({type:S.TEXT,createdAt:rs(e.getCreatedAt())});if(e instanceof tI)return new ev({type:ro(e.getType()),createdAt:rs(e.getCreatedAt()),value:e.toBytes()});if(e instanceof rt)return new ev({type:ra(e.getType()),createdAt:rs(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tX)return new ev({type:S.TREE,createdAt:rs(e.getCreatedAt()),value:rm(e).toBinary()});throw new tn(x.ErrUnimplemented,"unimplemented element")}function rl(e){return new eU({createdAt:rs(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rh(e){return new eB({parentId:rd(e.getParentID()),leftSiblingId:rd(e.getLeftSiblingID())})}function rd(e){return new eO({createdAt:rs(e.getCreatedAt()),offset:e.getOffset()})}function ru(e){let t=new eo;if(e instanceof tb){let r=new ea;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.key=e.getKey(),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tk){let r=new ec;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.prevCreatedAt=rs(e.getPrevCreatedAt()),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.prevCreatedAt=rs(e.getPrevCreatedAt()),r.createdAt=rs(e.getCreatedAt()),r.executedAt=rs(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tE){let r=new eh;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.createdAt=rs(e.getCreatedAt()),r.executedAt=rs(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tJ){let r=new ed;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rl(e.getFromPos()),r.to=rl(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rs(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof tL){let r=new eg;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rl(e.getFromPos()),r.to=rl(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rs(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rr){let r=new ef;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.value=rc(e.getValue()),r.executedAt=rs(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof tQ){let r=new em,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(r);r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rh(e.getFromPos()),r.to=rh(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eN({content:rg(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rs(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof rn){let r=new ep;r.parentCreatedAt=rs(e.getParentCreatedAt()),r.from=rh(e.getFromPos()),r.to=rh(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rs(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=rs(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new tn(x.ErrUnimplemented,"unimplemented operation");return t}function rg(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eR({id:rd(e.id),type:e.type,removedAt:rs(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rd(e.insPrevID)),e.insNextID&&(n.insNextId=rd(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new eb({value:r.getValue(),updatedAt:rs(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rf(e){let t=new ew;return t.body.case="jsonArray",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({element:rp(r.getValue())}));return t}(e.getElements()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}function rm(e){let t=new ew;return t.body.case="tree",t.body.value=new ex({nodes:rg(e.getRoot()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}function rp(e){if(e instanceof tv)return function(e){let t=new ew;return t.body.case="jsonObject",t.body.value=new eA({nodes:function(e){let t=[];for(let r of e)t.push(new eP({key:r.getStrKey(),element:rp(r.getValue())}));return t}(e.getRHT()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tP)return rf(e);if(e instanceof tI)return function(e){let t=new ew;return t.body.case="primitive",t.body.value=new eS({type:ro(e.getType()),value:e.toBytes(),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tB)return function(e){let t=new ew;return t.body.case="text",t.body.value=new eI({nodes:function(e){let t=[];for(let n of e){var r;let e=new ek;e.id=new eD({createdAt:rs((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rs(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new eb;t.value=e.getValue(),t.updatedAt=rs(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof rt)return function(e){let t=new ew;return t.body.case="counter",t.body.value=new eC({type:ra(e.getType()),value:e.toBytes(),createdAt:rs(e.getCreatedAt()),movedAt:rs(e.getMovedAt()),removedAt:rs(e.getRemovedAt())}),t}(e);if(e instanceof tX)return rm(e);throw new tn(x.ErrUnimplemented,"unimplemented element")}function ry(e){for(let t of e.findDetails(tr.Qf))if(t.metadata.code)return t.metadata.code;return""}function rv(e){return t$.of(e.clientSeq,BigInt(e.lamport),r_(e.actorId),BigInt(e.serverSeq))}function rw(e){if(e)return th.of(BigInt(e.lamport),e.delimiter,r_(e.actorId))}function rA(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rT(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 tn(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rS(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new tn(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rI(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tv.create(rw(e.createdAt));return rJ(e.value);case S.JSON_ARRAY:if(!e.value)return tP.create(rw(e.createdAt));return function(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rN(ew.fromBinary(e).body.value)}(e.value);case S.TEXT:return tB.create(t7.create(),rw(e.createdAt));case S.TREE:return function(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rO(ew.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(rT(e.type),e.value),rw(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return rt.create(rS(e.type),rt.valueFromBytes(rS(e.type),e.value),rw(e.createdAt))}}function rC(e){return t5.of(t4.of(rw(e.createdAt),e.offset),e.relativeOffset)}function rx(e){return t4.of(rw(e.createdAt),e.offset)}function rP(e){return tW.of(rE(e.parentId),rE(e.leftSiblingId))}function rE(e){return tG.of(rw(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=rE(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,rw(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rE(e.insPrevId)),e.insNextId&&(r.insNextID=rE(e.insNextId)),r.removedAt=rw(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,td).getRoot()}function rk(e){if("set"===e.body.case){let t=e.body.value;return tb.create(t.key,rI(t.value),rw(t.parentCreatedAt),rw(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tk.create(rw(t.parentCreatedAt),rw(t.prevCreatedAt),rI(t.value),rw(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tD.create(rw(t.parentCreatedAt),rw(t.prevCreatedAt),rw(t.createdAt),rw(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tE.create(rw(t.parentCreatedAt),rw(t.createdAt),rw(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,rw(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tJ.create(rw(t.parentCreatedAt),rC(t.from),rC(t.to),r,t.content,n,rw(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,rw(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rw(t.parentCreatedAt),rC(t.from),rC(t.to),r,n,rw(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rr.create(rw(t.parentCreatedAt),rI(t.value),rw(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,rw(n))}),tQ.create(rw(t.parentCreatedAt),rP(t.from),rP(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,rw(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,rw(r))}),(null==n?void 0:n.length)>0)?rn.createTreeRemoveStyleOperation(rw(t.parentCreatedAt),rP(t.from),rP(t.to),i,n,rw(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),rn.create(rw(t.parentCreatedAt),rP(t.from),rP(t.to),i,r,rw(t.executedAt)))}else throw new tn(x.ErrUnimplemented,"unimplemented operation")}function rD(e){let t=[];for(let r of e)t.push(t1.create({id:rv(r.id),operations:function(e){let t=[];for(let r of e){let e=rk(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rA(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new tn(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rR(e){let t=new ty;for(let r of e.nodes){let e=rB(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tv(rw(e.createdAt),t);return r.setMovedAt(rw(e.movedAt)),r.setRemovedAt(rw(e.removedAt)),r}function rN(e){let t=new tx;for(let r of e.nodes)t.insert(rB(r.element));let r=new tP(rw(e.createdAt),t);return r.setMovedAt(rw(e.movedAt)),r.setRemovedAt(rw(e.removedAt)),r}function rO(e){let t=rb(e.nodes);return tX.create(t,rw(e.createdAt))}function rB(e){if("jsonObject"===e.body.case)return rR(e.body.value);if("jsonArray"===e.body.case)return rN(e.body.value);if("primitive"===e.body.case)return function(e){let t=tI.of(tI.valueFromBytes(rT(e.type),e.value),rw(e.createdAt));return t.setMovedAt(rw(e.movedAt)),t.setRemovedAt(rw(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new t7,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tO.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rw(n.updatedAt))});let r=t6.create(rx(e.id),t);return r.remove(rw(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rx(n.insPrevId))),r=e}let n=new tB(t,rw(e.createdAt));return n.setMovedAt(rw(e.movedAt)),n.setRemovedAt(rw(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=rt.create(rS(e.type),rt.valueFromBytes(rS(e.type),e.value),rw(e.createdAt));return t.setMovedAt(rw(e.movedAt)),t.setRemovedAt(rw(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rO(e.body.value);throw new tn(x.ErrUnimplemented,"unimplemented element")}function rJ(e){if(!e)throw new tn(x.ErrInvalidArgument,"bytes is empty");return rR(ew.fromBinary(e).body.value)}function rL(e){return rp(e).toBinary()}function r_(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rM(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rq={fromPresence:rA,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eF({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:ri(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(ru(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 ez,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 tn(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:rs(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t2.create(e.documentKey,(t=e.checkpoint,t3.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rD(e.changes),e.snapshot,rw(e.minSyncedTicket))},fromChanges:rD,toTreeNodes:rg,fromTreeNodes:rb,objectToBytes:rL,bytesToObject:rJ,bytesToSnapshot:function(e){if(!e)return{root:tv.create(td),presences:new Map};let t=er.fromBinary(e);return{root:rB(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rA(n))}),t}(t.presences)}},bytesToHex:r_,hexToBytes:rM,toHexString:function(e){return r_(e)},toUint8Array:function(e){return rM(e)},toOperation:ru,toChangeID:ri,PbChangeID:es,bytesToChangeID:function(e){return rv(es.fromBinary(e))},bytesToOperation:function(e){return rk(eo.fromBinary(e))}};(f=O||(O={}))[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 rK=3;function rz(e){rK=e}let rF={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;rrK<=e};function rU(){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 rj{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 rV=()=>{};class rW{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 tn(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new tn(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=rV),void 0===n.error&&(n.error=rV),void 0===n.complete&&(n.complete=rV);let i=rU(),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){rF.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=ti(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class rH{static create(){return new rH(tv.create(td))}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 tn(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 rH(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r);n.element.getRemovedAt()&&e.compare(n.element.getRemovedAt())>=0&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();void 0!==n&&e.compare(n)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tB||e instanceof tX)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function rY(e,t){let r=new rZ(e);return new Proxy(t,r.getHandlers())}class rZ{static setInternal(e,t,r,n){if(r.includes("."))throw new tn(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=r8(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 tn(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=r8(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)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),rZ.setInternal(e,t,r,n),!0),get:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():r4(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("obj[".concat(r,"]")),rZ.deleteInternal(e,t,r),!0)}}}class rX{static*iteratorInternal(e,t){for(let r of t)yield r9(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=r8(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return rX.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=r8(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 rX.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=>r4(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tI.isSupport(r))return Array.from(t).map(t=>r4(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=>r4(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 r9(e,n)}:"getElementByIndex"===r?r=>r9(e,t.get(r)):"getLast"===r?()=>r9(e,t.getLast()):"deleteByID"===r?r=>{let n=rX.deleteInternalByID(e,t,r);return r9(e,n)}:"insertAfter"===r?(r,n)=>{let i=rX.insertAfterInternal(e,t,r,n);return r9(e,i)}:"insertBefore"===r?(r,n)=>{let i=rX.insertBeforeInternal(e,t,r,n);return r9(e,i)}:"moveBefore"===r?(r,n)=>{rX.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{rX.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{rX.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{rX.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?r4(e,t.get(Number(r))):"push"===r?r=>rX.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;orX.includes(e,t,r,n):"indexOf"===r?(r,n)=>rX.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>rX.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>rX.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;sr4(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rF.isEnabled(O.Trivial)&&rF.trivial("array[".concat(r,"]")),rX.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class rQ{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new tn(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rF.isEnabled(O.Debug)&&rF.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?to(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 tn(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new tn(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rF.isEnabled(O.Debug)&&rF.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=to(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 tn(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 tn(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([t5.fromStruct(e[0]),t5.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new tn(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 tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new tn(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r${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 tn(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(rr.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new tn(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r0(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===t_){r1(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&&!ts(a)){let e=to(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))r0(e,c,r)}}function r1(e){if(!e.value.length)throw new tn(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r2(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 tn(x.ErrInvalidArgument,"element node and text node cannot be passed together");r1(t)}else for(let t of e){let{type:e}=t;if(e===t_)throw new tn(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r3{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)r0(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new tn(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?to(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(rn.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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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?to(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(rn.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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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(rn.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]&&(r2(r),r[0].type!==t_))for(let e of r){let{children:t=[]}=e;r2(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&&!ts(a)){let e=to(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))r0(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new tn(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new tn(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new tn(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 tn(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new tn(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 tn(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 r9(e,t){if(t){if(t instanceof tI)return t;if(t instanceof tv)return rY(e,t);if(t instanceof tP)return function(e,t){let r=new rX(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tB)return new rQ(e,t);else if(t instanceof rt){let r=new r$(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tX){let r=new r3;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function r4(e,t){let r=r9(e,t);return r instanceof tI?r.getValue():r}function r8(e,t,r){let n;if(tI.isSupport(t))n=tI.of(t,r);else if(Array.isArray(t))n=tP.create(r,rX.buildArrayElements(e,t));else if("object"==typeof t)t instanceof rQ?(n=tB.create(t7.create(),r),t.initialize(e,n)):t instanceof r$?(n=rt.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r3?(n=tX.create(t.buildRoot(e),r),t.initialize(e,n)):n=tv.create(r,rZ.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class r5{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 r6="disconnected",r7=new Map,ne=new Map;function nt(e,t){((null==t?void 0:t.force)||"disconnected"!==r6)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ne,(m=B||(B={})).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",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class nr{update(e,t){if("removed"===this.getStatus())throw new tn(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),rY(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tc(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rF.isEnabled(O.Trivial)&&rF.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),rF.isEnabled(O.Trivial)&&rF.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new tn(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):"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 tn(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])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),E.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,E.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),rF.isEnabled(O.Trivial)&&rF.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:ti(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t2.create(this.key,t,!1,e)}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),rY(rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){let{root:r,presences:n}=rq.bytesToSnapshot(t);this.root=new rH(r),this.presences=n,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:E.Remote,value:{snapshot:this.isEnableDevtools()?rq.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){for(let r of(rF.isEnabled(O.Debug)&&rF.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rF.isEnabled(O.Trivial)&&rF.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rF.isEnabled(O.Debug)&&rF.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.syncLamport(e.getID().getLamport()),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)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(tl),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}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rq.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t1.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 tn(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?ti(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?ti(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ti(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ti(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ti(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new tn(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new tn(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tc(t,ti(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 tn(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new tn(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rG.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tw)){new tc(t,ti(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}])}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=rH.create(),this.changeID=t0,this.checkpoint=t9,this.localChanges=[],this.eventStream=function(e){let t=new rW(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 r5,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()||r7.has(e.getKey()))return;ne.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)||(ne.get(e.getKey()).push(t),"synced"===r6&&nt({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});r7.set(e.getKey(),[t]),nt({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"!==r6)break;r6="connected",nt({msg:"doc::available",docKey:e.getKey()}),rF.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":r6="disconnected",rF.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":r6="synced",nt({msg:"doc::sync::full",docKey:e.getKey(),events:ne.get(e.getKey())}),rF.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nn=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.2"}');let ni=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=K||(K={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let ns={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},no={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class na{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rF.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rF.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rF.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rF.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new tn(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:rq.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let r=rq.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()===B.Removed||(e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rj(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rF.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'))),e}).catch(e=>{throw rF.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new tn(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:rq.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=rq.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rF.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rF.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new tn(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 tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new tn(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rF.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rF.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new tn(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rq.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=rq.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rF.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rF.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new tn(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new tn(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!ni(r))throw new tn(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:no.maxRetries,a=no.maxBackoff,c=0,l=e=>Math.min(no.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(()=>{rF.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rF.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rF.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rF.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rF.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rF.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rF.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 tn(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 tn(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}]),rF.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}]),rF.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===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(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rq.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rq.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()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rF.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rF.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((ry(e)===x.ErrClientNotActivated||ry(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){rF.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||ns,this.key=t.key?t.key:rU(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ns.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ns.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ns.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tt,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nn.u2+"/"+nn.i8),await e(t))]})),this.taskQueue=[]}}var nc={Client:na,Document:nr,Primitive:tI,Text:rQ,Counter:r$,Tree:r3,LogLevel:O,setLogLevel:rz,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:na,Document:nr,Primitive:tI,Text:rQ,Counter:r$,Tree:r3,LogLevel:O,setLogLevel:rz,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nl=r(6182);function nh(e){let{content:t,actions:r}=e,[n,i]=(0,j.useState)(new Date),[s,o]=(0,j.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,z.jsx)("article",{children:(0,z.jsxs)("div",{children:[(0,z.jsx)(nl.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,z.jsxs)("p",{children:["selected day : ",a]}),(0,z.jsx)("div",{className:U().memo,children:t.map((e,t)=>{if(e.date===a)return(0,z.jsx)("p",{children:e.text},t)})}),(0,z.jsxs)("div",{className:U().inputForm_editor,children:[(0,z.jsx)("h3",{children:"input form"}),(0,z.jsx)("textarea",{className:U().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,z.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,z.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let nd=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],nu="next.js-Scheduler-".concat(W(new Date));function ng(){let[e,t]=(0,j.useState)([]),[r,n]=(0,j.useState)(nd),[i]=(0,j.useState)(()=>new nc.Document(nu));return(0,j.useEffect)(()=>{let e=new nc.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()*V.length);return V[e]}()}}),t.update(e=>{e.content||(e.content=nd)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,z.jsxs)("main",{className:U().main,children:[(0,z.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,z.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,z.jsx)(nh,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.html b/examples/nextjs-scheduler/index.html index 87c63606d..6a59934a5 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 : 21-10-24

    input form

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

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 22-10-24

    input form

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.txt b/examples/nextjs-scheduler/index.txt index e082baf80..7ba90c75f 100644 --- a/examples/nextjs-scheduler/index.txt +++ b/examples/nextjs-scheduler/index.txt @@ -1,7 +1,7 @@ 2:I[9974,[],""] -3:I[1807,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-d016d69fc00264ed.js"],""] +3:I[1807,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-eccac34c2844a9ff.js"],""] 4:I[4926,[],""] 5:I[4582,[],""] -0:["UCUuluTca8pS8EyjYfV8y",[[["",{"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:["WOBtSUHsV6HcsuY6KXQXp",[[["",{"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-1jBrjG-X.js b/examples/profile-stack/assets/index-Cw6-JyZY.js similarity index 99% rename from examples/profile-stack/assets/index-1jBrjG-X.js rename to examples/profile-stack/assets/index-Cw6-JyZY.js index 12df8cf93..903332e31 100644 --- a/examples/profile-stack/assets/index-1jBrjG-X.js +++ b/examples/profile-stack/assets/index-Cw6-JyZY.js @@ -20,7 +20,7 @@ var na=Object.defineProperty;var sa=(n,t,e)=>t in n?na(n,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var ve=null;try{ve=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 Z(n){return(n&&n.__isLong__)===!0}function Ni(n){var t=Math.clz32(n&-n);return n?31-t:t}O.isLong=Z;var Ci={},Pi={};function wr(n,t){var e,r,s;return t?(n>>>=0,(s=0<=n&&n<256)&&(r=Pi[n],r)?r:(e=B(n,0,!0),s&&(Pi[n]=e),e)):(n|=0,(s=-128<=n&&n<128)&&(r=Ci[n],r)?r:(e=B(n,n<0?-1:0,!1),s&&(Ci[n]=e),e))}O.fromInt=wr;function we(n,t){if(isNaN(n))return t?jt:Se;if(t){if(n<0)return jt;if(n>=So)return xo}else{if(n<=-Oi)return te;if(n+1>=Oi)return ko}return n<0?we(-n,t).neg():B(n%Dr|0,n/Dr|0,t)}O.fromNumber=we;function B(n,t,e){return new O(n,t,e)}O.fromBits=B;var Mn=Math.pow;function qs(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?jt:Se;if(e=e||10,e<2||360)throw Error("interior hyphen");if(r===0)return qs(n.substring(1),t,e).neg();for(var s=we(Mn(e,8)),i=Se,o=0;o>>0:this.low};T.toNumber=function(){return this.unsigned?(this.high>>>0)*Dr+(this.low>>>0):this.high*Dr+(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(te)?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 Z(t)||(t=Ne(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(Z(t)||(t=Ne(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(te)?te:this.not().add(Sr)};T.neg=T.negate;T.add=function(t){Z(t)||(t=Ne(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,p=0,v=0,m=0;return m+=i+h,v+=m>>>16,m&=65535,v+=s+l,p+=v>>>16,v&=65535,p+=r+c,f+=p>>>16,p&=65535,f+=e+o,f&=65535,B(v<<16|m,f<<16|p,this.unsigned)};T.subtract=function(t){return Z(t)||(t=Ne(t)),this.add(t.neg())};T.sub=T.subtract;T.multiply=function(t){if(this.isZero())return this;if(Z(t)||(t=Ne(t)),ve){var e=ve.mul(this.low,this.high,t.low,t.high);return B(e,ve.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?jt:Se;if(this.eq(te))return t.isOdd()?te:Se;if(t.eq(te))return this.isOdd()?te:Se;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(Bi)&&t.lt(Bi))return we(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,p=0,v=0,m=0,w=0;return w+=o*f,m+=w>>>16,w&=65535,m+=i*f,v+=m>>>16,m&=65535,m+=o*h,v+=m>>>16,m&=65535,v+=s*f,p+=v>>>16,v&=65535,v+=i*h,p+=v>>>16,v&=65535,v+=o*l,p+=v>>>16,v&=65535,p+=r*f+s*h+i*l+o*c,p&=65535,B(m<<16|w,p<<16|v,this.unsigned)};T.mul=T.multiply;T.divide=function(t){if(Z(t)||(t=Ne(t)),t.isZero())throw Error("division by zero");if(ve){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?ve.div_u:ve.div_s)(this.low,this.high,t.low,t.high);return B(e,ve.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?jt:Se;var r,s,i;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return jt;if(t.gt(this.shru(1)))return Io;i=jt}else{if(this.eq(te)){if(t.eq(Sr)||t.eq(Ps))return te;if(t.eq(te))return Sr;var o=this.shr(1);return r=o.div(t).shl(1),r.eq(Se)?t.isNegative()?Sr:Ps:(s=this.sub(t.mul(r)),i=r.add(s.div(t)),i)}else if(t.eq(te))return this.unsigned?jt:Se;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=Se}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:Mn(2,c-48),h=we(r),f=h.mul(t);f.isNegative()||f.gt(s);)r-=l,h=we(r,this.unsigned),f=h.mul(t);h.isZero()&&(h=Sr),i=i.add(h),s=s.sub(f)}return i};T.div=T.divide;T.modulo=function(t){if(Z(t)||(t=Ne(t)),ve){var e=(this.unsigned?ve.rem_u:ve.rem_s)(this.low,this.high,t.low,t.high);return B(e,ve.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?Ni(this.low):Ni(this.high)+32};T.ctz=T.countTrailingZeros;T.and=function(t){return Z(t)||(t=Ne(t)),B(this.low&t.low,this.high&t.high,this.unsigned)};T.or=function(t){return Z(t)||(t=Ne(t)),B(this.low|t.low,this.high|t.high,this.unsigned)};T.xor=function(t){return Z(t)||(t=Ne(t)),B(this.low^t.low,this.high^t.high,this.unsigned)};T.shiftLeft=function(t){return Z(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 Z(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 Z(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 Z(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 G=(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))(G||{});class $ extends Qr{constructor(e,r){super(r);a(this,"valueType");a(this,"value");this.valueType=$.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,r){return new $(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 g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Ue(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=$.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 $.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 g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class $n extends bo{constructor(e){super(e);a(this,"prev");a(this,"next");this.value=e}static createAfter(e,r){const s=new $n(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 Hr{constructor(){a(this,"dummyHead");a(this,"last");a(this,"nodeMapByIndex");a(this,"nodeMapByCreatedAt");const t=$.of(0,ke);t.setRemovedAt(ke),this.dummyHead=new $n(t),this.last=this.dummyHead,this.nodeMapByIndex=new Wr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Hr}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new g(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=$n.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 g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new g(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 g(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 sr{constructor(e,r){super(e);a(this,"elements");this.elements=r}static create(e,r){if(!r)return new ae(e,Hr.create());const s=Hr.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 sr&&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({...m,value:m.value?{attributes:kr(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,v,f,[l,l]]}setStyle(e,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(e[1],s),[,c]=this.rgaTreeSplit.findNodeWithSplit(e[0],s),l=[],h=this.rgaTreeSplit.findBetween(c,o),f=new Map,p=[];for(const m of h){const w=m.getCreatedAt().getActorID(),k=i!=null&&i.size?i.has(w)?i.get(w):ke:$r;if(m.canStyle(s,k)){const E=f.get(w),C=m.getCreatedAt();(!E||C.after(E))&&f.set(w,C),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[w,k]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:s.getActorID(),from:w,to:k,value:{attributes:kr(r)}});for(const[E,C]of Object.entries(r)){const[P]=m.getValue().setAttr(E,C,s);P!==void 0&&v.push({parent:m.getValue(),child:P})}}return[f,v,l]}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:kr(s.getAttributes()),content:s.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Te(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 en extends Ee{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 en(e,r,s,i,o,c,l)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Te))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h})=>({type:"edit",from:c,to:l,value:h,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 tn extends Ee{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 tn(e,r,s,i,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Te))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const c of i)e.registerGCPair(c);return{opInfos:o.map(({from:c,to:l,value:h})=>({type:"style",from:c,to:l,value:h,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 Jc=2,Fc="root",Gt="text";function Jr(n,t){let e=0;const r=n.children;for(let s=0;s0)throw new g(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===Gt}get paddedSize(){return this.size+(this.isText?0:Jc)}isAncestorOf(t){return $c(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 g(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 g(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 g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new g(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 g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new g(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 g(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 $c(n,t){if(n===t)return!1;for(;t.parent;){if(t.parent===n)return!0;t=t.parent}return!1}var V=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(V||{});function Eo(n,t,e,r){if(t>e)throw new g(d.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>n.size)throw new g(d.ErrInvalidArgument,`from is out of range: ${t} > ${n.size}`);if(e>n.size)throw new g(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),Eo(i,Math.max(0,o),Math.min(c,i.size),r),h&&r([i,"End"],h)}s+=i.paddedSize}}function No(n,t,e=0){for(const r of n.children)No(r,t,e+1);t(n,e)}function Vn(n,t,e=0){for(const r of n._children)Vn(r,t,e+1);t(n,e)}function Ds(n,t,e=!0){if(t>n.size)throw new g(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 Ds(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 Ds(i,t-s-1,e);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Co(n){return n.isText||n.children.length===0?n:Co(n.children[0])}function Uc(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 Kc(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 Ie{constructor(t,e){a(this,"parentID");a(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new Ie(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],Ie.of(r.id,Y.of(s.getCreatedAt(),s.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return Ie.of(Y.of(oe.fromStruct(t.parentID.createdAt),t.parentID.offset),Y.of(oe.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 g(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 Y{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Y(t,e)}static fromStruct(t){return Y.of(oe.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 g(d.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new g(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 ie(Y.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new ie(Y.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){return!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,r){this.attrs||(this.attrs=new Yt);const s=new Array;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 Os(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(Os)};return n.attrs&&(t.attributes=kr((e=n.attrs)==null?void 0:e.toObject())),t}function zs(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()}="${Ue(e.getValue())}"`}).join(" ")),`<${n.type}${t}>${n.children.map(e=>zs(e)).join("")}`}function Do(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(Do),size:n.size,isRemoved:n.isRemoved}}class Ae extends Qr{constructor(e,r){super(r);a(this,"indexTree");a(this,"nodeMapByID");this.indexTree=new qc(e),this.nodeMapByID=new Po(Y.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(e,r){return new Ae(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 p=f;p{const k=w.getCreatedAt().getActorID(),E=i?i.has(k)?i.get(k):ke:$r;if(w.canStyle(s,E)&&r){const C=v.get(k),P=w.getCreatedAt();(!C||P.after(C))&&v.set(k,P);const H=w.setAttrs(r,s),D=H.reduce((K,[,Zt])=>(Zt&&(K[Zt.getKey()]=p[Zt.getKey()]),K),{}),L=w.parent,F=w.prevSibling||w.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(L,F),to:this.toIndex(w,w),fromPath:this.toPath(L,F),toPath:this.toPath(w,w),actor:s.getActorID(),value:D});for(const[K]of H)K&&m.push({parent:w,child:K})}}),[v,m,f]}removeStyle(e,r,s,i){const[o,c]=this.findNodesAndSplitText(e[0],s),[l,h]=this.findNodesAndSplitText(e[1],s),f=[],p=new Map,v=[];return this.traverseInPosRange(o,c,l,h,([m])=>{const w=m.getCreatedAt().getActorID(),k=i?i.has(w)?i.get(w):ke:$r;if(m.canStyle(s,k)&&r){const E=p.get(w),C=m.getCreatedAt();(!E||C.after(E))&&p.set(w,C),m.attrs||(m.attrs=new Yt);for(const D of r){const L=m.attrs.remove(D,s);for(const F of L)v.push({parent:m,child:F})}const P=m.parent,H=m.prevSibling||m.parent;f.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(P,H),to:this.toIndex(m,m),fromPath:this.toPath(P,H),toPath:this.toPath(m,m),value:r})}}),[p,v,f]}edit(e,r,s,i,o,c){const[l,h]=this.findNodesAndSplitText(e[0],i),[f,p]=this.findNodesAndSplitText(e[1],i),v=this.toIndex(l,h),m=this.toPath(l,h),w=[],k=[],E=[],C=new Map;this.traverseInPosRange(l,h,f,p,([D,L],F)=>{if(L===V.Start&&!F)for(const ur of D.children)E.push(ur);const K=D.getCreatedAt().getActorID(),Zt=c?c.has(K)?c.get(K):ke:$r;if(D.canDelete(i,Zt)||w.includes(D.parent)){const ur=C.get(K),nn=D.getCreatedAt();(!ur||nn.after(ur))&&C.set(K,nn),(L===V.Text||L===V.Start)&&w.push(D),k.push([D,L])}});const P=this.makeDeletionChanges(k,i),H=[];for(const D of w)D.remove(i),D.isRemoved&&H.push({parent:this,child:D});for(const D of E)D.removedAt||l.append(D);if(s>0){let D=0,L=l,F=h;for(;D{l.isRemoved&&(K.remove(i),H.push({parent:this,child:K})),this.nodeMapByID.put(K.id,K)}),F.isRemoved||D.push(F);if(D.length){const F=D.map(K=>Os(K));P.length&&P[P.length-1].from===v?P[P.length-1].value=F:P.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[P,H,C]}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 g(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 Ie.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 zs(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 m,w,k,E;let l,h,f;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(l=this.indexTree.indexOf(p),h=this.indexTree.treePosToPath(p),f=Ie.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(w=s.insPrevID)==null?void 0:w.toTestString(),insNext:(k=s.insNextID)==null?void 0:k.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:c,attributes:s.attrs?kr((E=s.attrs)==null?void 0:E.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(E,m)):s.push({type:"content",from:C,to:P,fromPath:this.toPath(k,p),toPath:this.toPath(E,m),actor:r.getActorID()}))}return s.reverse()}findRightToken([e,r]){if(r===V.Start){const l=e.allChildren;return l.length>0?[l[0],l[0].isText?V.Text:V.Start]:[e,V.End]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===i.length-1)return[s,V.End];const c=i[o+1];return[c,c.isText?V.Text:V.Start]}findLeftToken([e,r]){if(r===V.End){const l=e.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?V.Text:V.End]}return[e,V.Start]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===0)return[s,V.Start];const c=i[o-1];return[c,c.isText?V.Text:V.End]}}class rn extends Ee{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 rn(e,r,s,i,o,c,l)}execute(e){var l;const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,c]=i.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,s,(()=>{let h=s.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>oe.of(s.getLamport(),++h,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of c)e.registerGCPair(h);return{opInfos:o.map(({from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w}))}}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=>zs(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class tr{constructor(t,e,r,s){a(this,"clientSeq");a(this,"serverSeq");a(this,"lamport");a(this,"actor");this.clientSeq=t,this.serverSeq=s,this.lamport=e,this.actor=r}static of(t,e,r,s){return new tr(t,e,r,s)}next(){return new tr(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(t){return t>this.lamport?new tr(this.clientSeq,t,this.actor):new tr(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(t){return oe.of(this.lamport,t,this.actor)}setActor(t){return new tr(this.clientSeq,this.lamport,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const jc=new tr(0,0n,$s);class Or{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 Or({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);if(!c)continue;const{opInfos:l,reverseOp:h}=c;s.push(...l),h&&i.unshift(h)}return this.presenceChange&&(this.presenceChange.type===ar.Put?e.set(this.id.getActorID(),be(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:W.bytesToHex(W.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>W.bytesToHex(W.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:r,presenceChange:s,message:i}=t;return Or.create({id:W.bytesToChangeID(W.hexToBytes(e)),operations:r==null?void 0:r.map(o=>W.bytesToOperation(W.hexToBytes(o))),presenceChange:s,message:i})}}class jn{constructor(t,e,r,s,i,o){a(this,"documentKey");a(this,"checkpoint");a(this,"isRemoved");a(this,"changes");a(this,"snapshot");a(this,"minSyncedTicket");this.documentKey=t,this.checkpoint=e,this.isRemoved=r,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(t,e,r,s,i,o){return new jn(t,e,r,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class xr{constructor(t,e){a(this,"serverSeq");a(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new xr(t,e)}increaseClientSeq(t){return t===0?this:new xr(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 xr.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 Gc=new xr(0n,0);class qe{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new qe(t,e)}static fromStruct(t){return qe.of(oe.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 qe(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 Wc=qe.of(ke,0);class xe{constructor(t,e){a(this,"id");a(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new xe(t,e)}static fromStruct(t){const e=qe.fromStruct(t.id);return xe.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qe.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 ir extends bo{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 ir(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 g(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){if(!t.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(t,e,r),o=new Map,c=new Map,l=this.makeChanges(i,e);for(const h of s){const f=h.getCreatedAt().getActorID();(!o.has(f)||h.getID().getCreatedAt().after(o.get(f)))&&o.set(f,h.getID().getCreatedAt()),c.set(h.getID().toIDString(),h),h.remove(e)}return this.deleteIndexNodes(i),[l,o,c]}filterNodes(t,e,r){const s=!!r,i=[],o=[],[c,l]=this.findEdgesOfCandidates(t);o.push(c);for(const h of t){const f=h.getCreatedAt().getActorID(),p=s?r.has(f)?r.get(f):ke:$r;h.canDelete(e,p)?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 ze=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(ze||{});class ce extends Qr{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=Ri(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=O.fromNumber(r):this.value=r;break;default:throw new g(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 g(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 g(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()===G.Long?this.value=this.value+e.getValue().toInt():this.value=O.fromNumber(this.value+Ri(e.getValue())).toInt(),this}}class Rr extends Ee{constructor(e,r,s){super(e,s);a(this,"value");this.value=r}static create(e,r,s){return new Rr(e,r,s)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ce))throw new g(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()===G.Long?e.getValue().multiply(-1):e.getValue()*-1;return Rr.create(this.getParentCreatedAt(),$.of(s,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Wt extends Ee{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 Wt(e,r,s,i,o,new Array,c)}static createTreeRemoveStyleOperation(e,r,s,i,o,c){return new Wt(e,r,s,i,new Map,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const c={};[...this.attributes].forEach(([l,h])=>c[l]=h),[,o,i]=s.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const c=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h,fromPath:f,toPath:p})=>({type:"tree-style",from:c,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:f,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 Hc(n){const t=new Ms,e=t.data;for(const[r,s]of Object.entries(n))e[r]=JSON.stringify(s);return t}function Yc(n){if(n.type===ar.Put)return new jr({type:yr.PUT,presence:Hc(n.presence)});if(n.type===ar.Clear)return new jr({type:yr.CLEAR});throw new g(d.ErrUnimplemented,"unimplemented type")}function Xc(n){return new wo({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function Oo(n){return new Kn({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:Ys(n.getActorID())})}function S(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:Ys(n.getActorID())})}function Bo(n){switch(n){case G.Null:return N.NULL;case G.Boolean:return N.BOOLEAN;case G.Integer:return N.INTEGER;case G.Long:return N.LONG;case G.Double:return N.DOUBLE;case G.String:return N.STRING;case G.Bytes:return N.BYTES;case G.Date:return N.DATE;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function Ro(n){switch(n){case ze.IntegerCnt:return N.INTEGER_CNT;case ze.LongCnt:return N.LONG_CNT;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function es(n){if(n instanceof re)return new ue({type:N.JSON_OBJECT,createdAt:S(n.getCreatedAt()),value:Wo(n)});if(n instanceof ae)return new ue({type:N.JSON_ARRAY,createdAt:S(n.getCreatedAt()),value:ku(n)});if(n instanceof Te)return new ue({type:N.TEXT,createdAt:S(n.getCreatedAt())});if(n instanceof $)return new ue({type:Bo(n.getType()),createdAt:S(n.getCreatedAt()),value:n.toBytes()});if(n instanceof ce)return new ue({type:Ro(n.getType()),createdAt:S(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Ae)return new ue({type:N.TREE,createdAt:S(n.getCreatedAt()),value:Eu(n)});throw new g(d.ErrUnimplemented,"unimplemented element")}function Zc(n){return new Kr({createdAt:S(n.getCreatedAt()),offset:n.getOffset()})}function on(n){return new Ht({createdAt:S(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function an(n){return new pr({parentId:Ur(n.getParentID()),leftSiblingId:Ur(n.getLeftSiblingID())})}function Ur(n){return new nr({createdAt:S(n.getCreatedAt()),offset:n.getOffset()})}function Lo(n){const t=new Fs;if(n instanceof vr){const e=n,r=new Tn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.key=e.getKey(),r.value=es(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(n instanceof _r){const e=n,r=new An;r.parentCreatedAt=S(e.getParentCreatedAt()),r.prevCreatedAt=S(e.getPrevCreatedAt()),r.value=es(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(n instanceof rr){const e=n,r=new bn;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 cr){const e=n,r=new Sn;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 en){const e=n,r=new In;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=on(e.getFromPos()),r.to=on(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 tn){const e=n,r=new kn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=on(e.getFromPos()),r.to=on(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 Rr){const e=n,r=new xn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.value=es(e.getValue()),r.executedAt=S(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(n instanceof rn){const e=n,r=new En,s=r.createdAtMapByActor;for(const[i,o]of e.getMaxCreatedAtMapByActor())s[i]=S(o);r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=an(e.getFromPos()),r.to=an(e.getToPos()),r.contents=su(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=S(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(n instanceof Wt){const e=n,r=new Nn;r.parentCreatedAt=S(e.getParentCreatedAt()),r.from=an(e.getFromPos()),r.to=an(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 g(d.ErrUnimplemented,"unimplemented operation");return t}function Qc(n){const t=[];for(const e of n)t.push(Lo(e));return t}function _c(n){const t=new yo({id:Oo(n.getID()),message:n.getMessage()});return n.hasOperations()&&(t.operations=Qc(n.getOperations())),n.hasPresenceChange()&&(t.presenceChange=Yc(n.getPresenceChange())),t}function eu(n){const t=[];for(const e of n)t.push(_c(e));return t}function tu(n){const t=[];for(const e of n)t.push(new vo({key:e.getStrKey(),element:Vs(e.getValue())}));return t}function ru(n){const t=[];for(const e of n)t.push(new Ln({element:Vs(e.getValue())}));return t}function nu(n){const t=[];for(const e of n){const r=new Jn;r.id=Zc(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 Cr;c.value=o.getValue(),c.updatedAt=S(o.getUpdatedAt()),s[o.getKey()]=c}t.push(r)}return t}function su(n){const t=[];if(!n||!n.length)return t;for(const e of n)t.push(new Fn({content:Ks(e)}));return t}function iu(n){const t={};for(const e of n)t[e.getKey()]=new Cr({value:e.getValue(),updatedAt:S(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ks(n){if(!n)return[];const t=[];return Vn(n,(e,r)=>{const s=new Vr({id:Ur(e.id),type:e.type,removedAt:S(e.removedAt),depth:r});e.isText&&(s.value=e.value),e.insPrevID&&(s.insPrevId=Ur(e.insPrevID)),e.insNextID&&(s.insNextId=Ur(e.insNextID)),e.attrs&&(s.attributes=iu(e.attrs)),t.push(s)}),t}function ou(n){const t=new ne;return t.body.case="jsonObject",t.body.value=new Cn({nodes:tu(n.getRHT()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Jo(n){const t=new ne;return t.body.case="jsonArray",t.body.value=new Pn({nodes:ru(n.getElements()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function au(n){const t=new ne;return t.body.case="primitive",t.body.value=new Dn({type:Bo(n.getType()),value:n.toBytes(),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function cu(n){const t=new ne;return t.body.case="text",t.body.value=new On({nodes:nu(n.getRGATreeSplit()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function uu(n){const t=new ne;return t.body.case="counter",t.body.value=new Bn({type:Ro(n.getType()),value:n.toBytes(),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Fo(n){const t=new ne;return t.body.case="tree",t.body.value=new Rn({nodes:Ks(n.getRoot()),createdAt:S(n.getCreatedAt()),movedAt:S(n.getMovedAt()),removedAt:S(n.getRemovedAt())}),t}function Vs(n){if(n instanceof re)return ou(n);if(n instanceof ae)return Jo(n);if(n instanceof $)return au(n);if(n instanceof Te)return cu(n);if(n instanceof ce)return uu(n);if(n instanceof Ae)return Fo(n);throw new g(d.ErrUnimplemented,"unimplemented element")}function lu(n){return new Xt({documentKey:n.getDocumentKey(),checkpoint:Xc(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:eu(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:S(n.getMinSyncedTicket())})}function Li(n){const t=n.findDetails(Ec);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function Mo(n){return tr.of(n.clientSeq,BigInt(n.lamport),Hs(n.actorId),BigInt(n.serverSeq))}function I(n){if(n)return oe.of(BigInt(n.lamport),n.delimiter,Hs(n.actorId))}function js(n){const t={};return Object.entries(n.data).forEach(([e,r])=>{t[e]=JSON.parse(r)}),t}function hu(n){const t=n.type;if(t===yr.PUT){const e=js(n.presence);return{type:ar.Put,presence:e}}if(t===yr.CLEAR)return{type:ar.Clear};throw new g(d.ErrInvalidType,`unsupported type: ${t}`)}function fu(n){const t=new Map;return Object.entries(n).forEach(([e,r])=>{t.set(e,js(r))}),t}function $o(n){switch(n){case N.NULL:return G.Null;case N.BOOLEAN:return G.Boolean;case N.INTEGER:return G.Integer;case N.LONG:return G.Long;case N.DOUBLE:return G.Double;case N.STRING:return G.String;case N.BYTES:return G.Bytes;case N.DATE:return G.Date}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function Un(n){switch(n){case N.INTEGER_CNT:return ze.IntegerCnt;case N.LONG_CNT:return ze.LongCnt}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function ts(n){switch(n.type){case N.JSON_OBJECT:return n.value?Go(n.value):re.create(I(n.createdAt));case N.JSON_ARRAY:return n.value?Iu(n.value):ae.create(I(n.createdAt));case N.TEXT:return Te.create(Br.create(),I(n.createdAt));case N.TREE:return xu(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 $.of($.valueFromBytes($o(n.type),n.value),I(n.createdAt));case N.INTEGER_CNT:case N.LONG_CNT:return ce.create(Un(n.type),ce.valueFromBytes(Un(n.type),n.value),I(n.createdAt))}}function cn(n){return xe.of(qe.of(I(n.createdAt),n.offset),n.relativeOffset)}function Uo(n){return qe.of(I(n.createdAt),n.offset)}function du(n){const t=Yr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{t.setAttr(r,s.value,I(s.updatedAt))});const e=ir.create(Uo(n.id),t);return e.remove(I(n.removedAt)),e}function Ar(n){return Ie.of(qr(n.parentId),qr(n.leftSiblingId))}function qr(n){return Y.of(I(n.createdAt),n.offset)}function gu(n){if(!n.length)return;const t=[];return n.forEach(e=>{const r=Gs(e.content);t.push(r)}),t}function Gs(n){if(n.length===0)return;const t=[];for(const s of n)t.push(pu(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(),Ae.create(e,ke).getRoot()}function mu(n){const t=Yt.create();for(const[e,r]of Object.entries(n))t.setInternal(e,r.value,I(r.updatedAt),r.isRemoved);return t}function pu(n){const t=qr(n.id),e=ie.create(t,n.type),r=Object.entries(n.attributes);return e.isText?e.value=n.value:r.length&&(e.attrs=mu(n.attributes)),n.insPrevId&&(e.insPrevID=qr(n.insPrevId)),n.insNextId&&(e.insNextID=qr(n.insNextId)),e.removedAt=I(n.removedAt),e}function qo(n){if(n.body.case==="set"){const t=n.body.value;return vr.create(t.key,ts(t.value),I(t.parentCreatedAt),I(t.executedAt))}else if(n.body.case==="add"){const t=n.body.value;return _r.create(I(t.parentCreatedAt),I(t.prevCreatedAt),ts(t.value),I(t.executedAt))}else if(n.body.case==="move"){const t=n.body.value;return rr.create(I(t.parentCreatedAt),I(t.prevCreatedAt),I(t.createdAt),I(t.executedAt))}else if(n.body.case==="remove"){const t=n.body.value;return cr.create(I(t.parentCreatedAt),I(t.createdAt),I(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,I(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),en.create(I(t.parentCreatedAt),cn(t.from),cn(t.to),e,t.content,r,I(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,I(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),tn.create(I(t.parentCreatedAt),cn(t.from),cn(t.to),e,r,I(t.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const t=n.body.value;return Rr.create(I(t.parentCreatedAt),ts(t.value),I(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,I(s))}),rn.create(I(t.parentCreatedAt),Ar(t.from),Ar(t.to),gu(t.contents),t.splitLevel,e,I(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,I(o))}),(r==null?void 0:r.length)>0?Wt.createTreeRemoveStyleOperation(I(t.parentCreatedAt),Ar(t.from),Ar(t.to),s,r,I(t.executedAt)):(Object.entries(t.attributes).forEach(([i,o])=>{e.set(i,o)}),Wt.create(I(t.parentCreatedAt),Ar(t.from),Ar(t.to),s,e,I(t.executedAt)))}else throw new g(d.ErrUnimplemented,"unimplemented operation")}}function yu(n){const t=[];for(const e of n){const r=qo(e);r&&t.push(r)}return t}function zo(n){const t=[];for(const e of n)t.push(Or.create({id:Mo(e.id),operations:yu(e.operations),presenceChange:e.presenceChange?hu(e.presenceChange):void 0,message:e.message}));return t}function vu(n){return xr.of(BigInt(n.serverSeq),n.clientSeq)}function wu(n){return jn.create(n.documentKey,vu(n.checkpoint),n.isRemoved,zo(n.changes),n.snapshot,I(n.minSyncedTicket))}function Ko(n){const t=new Gr;for(const r of n.nodes){const s=Ws(r.element);t.set(r.key,s,s.getPositionedAt())}const e=new re(I(n.createdAt),t);return e.setMovedAt(I(n.movedAt)),e.setRemovedAt(I(n.removedAt)),e}function Vo(n){const t=new Hr;for(const r of n.nodes)t.insert(Ws(r.element));const e=new ae(I(n.createdAt),t);return e.setMovedAt(I(n.movedAt)),e.setRemovedAt(I(n.removedAt)),e}function Tu(n){const t=$.of($.valueFromBytes($o(n.type),n.value),I(n.createdAt));return t.setMovedAt(I(n.movedAt)),t.setRemovedAt(I(n.removedAt)),t}function Au(n){const t=new Br;let e=t.getHead();for(const s of n.nodes){const i=t.insertAfter(e,du(s));s.insPrevId&&i.setInsPrev(t.findNode(Uo(s.insPrevId))),e=i}const r=new Te(t,I(n.createdAt));return r.setMovedAt(I(n.movedAt)),r.setRemovedAt(I(n.removedAt)),r}function bu(n){const t=ce.create(Un(n.type),ce.valueFromBytes(Un(n.type),n.value),I(n.createdAt));return t.setMovedAt(I(n.movedAt)),t.setRemovedAt(I(n.removedAt)),t}function jo(n){const t=Gs(n.nodes);return Ae.create(t,I(n.createdAt))}function Ws(n){if(n.body.case==="jsonObject")return Ko(n.body.value);if(n.body.case==="jsonArray")return Vo(n.body.value);if(n.body.case==="primitive")return Tu(n.body.value);if(n.body.case==="text")return Au(n.body.value);if(n.body.case==="counter")return bu(n.body.value);if(n.body.case==="tree")return jo(n.body.value);throw new g(d.ErrUnimplemented,"unimplemented element")}function Su(n){if(!n)return{root:re.create(ke),presences:new Map};const t=as.fromBinary(n);return{root:Ws(t.root),presences:fu(t.presences)}}function Go(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Ko(t.body.value)}function Wo(n){return Vs(n).toBinary()}function Iu(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Vo(t.body.value)}function ku(n){return Jo(n).toBinary()}function xu(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return jo(t.body.value)}function Eu(n){return Fo(n).toBinary()}function Ho(n){return n?Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function Hs(n){return Ho(n)}function Yo(n){return new Uint8Array(n.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Ys(n){return Yo(n)}function Nu(n){const t=Kn.fromBinary(n);return Mo(t)}function Cu(n){const t=Fs.fromBinary(n);return qo(t)}const W={fromPresence:js,toChangePack:lu,fromChangePack:wu,fromChanges:zo,toTreeNodes:Ks,fromTreeNodes:Gs,objectToBytes:Wo,bytesToObject:Go,bytesToSnapshot:Su,bytesToHex:Ho,hexToBytes:Yo,toHexString:Hs,toUint8Array:Ys,toOperation:Lo,toChangeID:Oo,PbChangeID:Kn,bytesToChangeID:Nu,bytesToOperation:Cu};var ee=(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))(ee||{});let lr=3;function Xo(n){lr=n}const x={trivial:(...n)=>{lr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{lr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{lr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{lr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{lr>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=>lr<=n};function Zo(){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 Pu{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===yn.RealtimeSyncOff?!1:this.syncMode===yn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==yn.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 rs=()=>{};class Du{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 g(d.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(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=rs),s.error===void 0&&(s.error=rs),s.complete===void 0&&(s.complete=rs);const i=Zo(),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){x.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 Ir{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=Ao,this.root=e,this.operations=[],this.previousPresence=be(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(t,e,r,s){return new Ir(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 Or.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 Xr{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 Te||e instanceof Ae)for(const r of e.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Xr(re.create(ke))}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 g(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 sr&&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 sr&&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 sr&&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 Xr(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r);s.element.getRemovedAt()&&t.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),e+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s!==void 0&&t.compare(s)>=0&&(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()}}function Qo(n,t){const e=new Zr(n);return new Proxy(t,e.getHandlers())}class Zr{constructor(t){a(this,"context");a(this,"handlers");this.context=t,this.handlers={set:(e,r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]=${JSON.stringify(s)}`),Zr.setInternal(t,e,r,s),!0),get:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),r==="getID"?()=>e.getCreatedAt():r==="toJSON"||r==="toString"?()=>e.toJSON():r==="toJS"?()=>e.toJS():r==="toJSForTest"?()=>e.toJSForTest():hr(t,e.get(r))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),Zr.deleteInternal(t,e,r),!0)}}static setInternal(t,e,r,s){if(r.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const i=t.issueTimeTicket(),o=qn(t,s,i),c=e.set(r,o,i);t.registerElement(o,e),c&&t.registerRemovedElement(c),t.push(vr.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 g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),c=qn(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(cr.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i))}getHandlers(){return this.handlers}}function Bu(n,t){const e=new U(n,t);return new Proxy(t,e.getHandlers())}function Ru(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Lu(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class U{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 _t(t,c)}:s==="getElementByIndex"?o=>{const c=r.get(o);return _t(t,c)}:s==="getLast"?()=>_t(t,r.getLast()):s==="deleteByID"?o=>{const c=U.deleteInternalByID(t,r,o);return _t(t,c)}:s==="insertAfter"?(o,c)=>{const l=U.insertAfterInternal(t,r,o,c);return _t(t,l)}:s==="insertBefore"?(o,c)=>{const l=U.insertBeforeInternal(t,r,o,c);return _t(t,l)}:s==="moveBefore"?(o,c)=>{U.moveBeforeInternal(t,r,o,c)}:s==="moveAfter"?(o,c)=>{U.moveAfterInternal(t,r,o,c)}:s==="moveFront"?o=>{U.moveFrontInternal(t,r,o)}:s==="moveLast"?o=>{U.moveLastInternal(t,r,o)}:Ru(s)?hr(t,r.get(Number(s))):s==="push"?o=>U.pushInternal(t,r,o):s==="splice"?(o,c,...l)=>U.splice(t,r,o,c,...l):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?U.iteratorInternal.bind(this,t,r):s==="includes"?(o,c)=>U.includes(t,r,o,c):s==="indexOf"?(o,c)=>U.indexOf(t,r,o,c):s==="lastIndexOf"?(o,c)=>U.lastIndexOf(t,r,o,c):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>U.toTestString(r):typeof s=="string"&&Lu(s)?(...o)=>{const c=Array.from(r).map(l=>hr(t,l));return Array.prototype[s].apply(c,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`array[${s}]`),U.deleteInternalByIndex(t,r,Number.parseInt(s)),!0)}}static*iteratorInternal(t,e){for(const r of e)yield _t(t,r)}static buildArrayElements(t,e){const r=[];for(const s of e){const i=t.issueTimeTicket(),o=qn(t,s,i);r.push(o)}return r}static pushInternal(t,e,r){return U.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(rr.create(e.getCreatedAt(),o,s,i))}static moveAfterInternal(t,e,r,s){const i=t.issueTimeTicket();e.moveAfter(r,s,i),t.push(rr.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(rr.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(rr.create(e.getCreatedAt(),i,r,s))}static insertAfterInternal(t,e,r,s){const i=t.issueTimeTicket(),o=qn(t,s,i);return e.insertAfter(r,o),t.registerElement(o,e),t.push(_r.create(e.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(t,e,r,s){return U.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(cr.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(cr.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($.isSupport(r))return Array.from(e).map(h=>hr(t,h)).includes(r,o);for(let l=o;l=i)return-1;if($.isSupport(r))return Array.from(e).map(h=>hr(t,h)).indexOf(r,o);for(let l=o;l=i?i-1:s<0?s+i:s;if(o<0)return-1;if($.isSupport(r))return Array.from(e).map(h=>hr(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 Gn{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 g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`EDIT: f:${t}->${i[0].toTestString()}, t:${e}->${i[1].toTestString()} c:${r}`);const o=s?Pr(s):void 0,c=this.context.issueTimeTicket(),[l,,h,f]=this.text.edit(i,r,c,o);for(const p of h)this.context.registerGCPair(p);return this.context.push(new en(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 g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`STYL: f:${t}->${s[0].toTestString()}, t:${e}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Pr(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 tn(this.text.getCreatedAt(),s[0],s[1],c,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new g(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 g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([xe.fromStruct(t[0]),xe.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(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 g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}}class Wn{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 g(d.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),r=$.of(t,e);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(Rr.create(this.counter.getCreatedAt(),r,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Xs(n,t,e){const{type:r}=n,s=e.issueTimeTicket();if(r===Gt){_o(n);const{value:i}=n,o=ie.create(Y.of(s,0),r,i);t.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let c;if(typeof o=="object"&&!To(o)){const h=Pr(o);c=new Yt;for(const[f,p]of Object.entries(h))c.set(f,p,s)}const l=ie.create(Y.of(s,0),r,void 0,c);t.append(l);for(const h of i)Xs(h,l,e)}}function Ju(n,t){const{type:e}=t,r=n.issueTimeTicket();let s;if(t.type===Gt){const{value:i}=t;s=ie.create(Y.of(r,0),e,i)}else if(t){const{children:i=[]}=t,{attributes:o}=t;let c;if(typeof o=="object"&&!To(o)){const l=Pr(o);c=new Yt;for(const[h,f]of Object.entries(l))c.set(h,f,r)}s=ie.create(Y.of(n.issueTimeTicket(),0),e,void 0,c);for(const l of i)Xs(l,s,n)}return s}function _o(n){if(!n.value.length)throw new g(d.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ji(n){if(!n.length)return!0;if(n[0].type===Gt)for(const e of n){const{type:r}=e;if(r!==Gt)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together");_o(e)}else for(const e of n){const{type:r}=e;if(r===Gt)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Hn{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 ie.create(Y.of(t.issueTimeTicket(),0),Fc);const e=ie.create(Y.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)Xs(r,e,t);return e}getSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(t),i=this.context.issueTimeTicket(),o=e?Pr(e):void 0,[c]=this.tree.style([r,s],o,i);this.context.push(Wt.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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(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?Pr(r):void 0,[l,h]=this.tree.style([s,i],c,o);for(const f of h)this.context.registerGCPair(f);this.context.push(Wt.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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(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(Wt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,c,r,o))}editInternal(t,e,r,s=0){var h;if(r.length!==0&&r[0]&&(Ji(r),r[0].type!==Gt))for(const f of r){const{children:p=[]}=f;Ji(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((h=r[0])==null?void 0:h.type)===Gt){let f="";for(const p of r){const{value:v}=p;f+=v}o.push(ie.create(Y.of(this.context.issueTimeTicket(),0),Gt,f))}else o=r.map(f=>f&&Ju(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(rn.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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(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 g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(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 g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new g(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 g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[Ie.fromStruct(t[0]),Ie.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[Ie.fromStruct(t[0]),Ie.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function Fi(n,t){return Qo(n,t)}function _t(n,t){if(t){if(t instanceof $)return t;if(t instanceof re)return Qo(n,t);if(t instanceof ae)return Bu(n,t);if(t instanceof Te)return new Gn(n,t);if(t instanceof ce){const e=new Wn(ze.IntegerCnt,0);return e.initialize(n,t),e}else if(t instanceof Ae){const e=new Hn;return e.initialize(n,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function hr(n,t){const e=_t(n,t);return e instanceof $?e.getValue():e}function qn(n,t,e){let r;if($.isSupport(t))r=$.of(t,e);else if(Array.isArray(t))r=ae.create(e,U.buildArrayElements(n,t));else if(typeof t=="object")t instanceof Gn?(r=Te.create(Br.create(),e),t.initialize(n,r)):t instanceof Wn?(r=ce.create(t.getValueType(),t.getValue(),e),t.initialize(n,r)):t instanceof Hn?(r=Ae.create(t.buildRoot(n),e),t.initialize(n,r)):r=re.create(e,Zr.buildObjectMembers(n,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const Mi=50;class Fu{constructor(){a(this,"undoStack",[]);a(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=Mi&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=Mi&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Mu="yorkie-devtools-panel",$u="yorkie-devtools-sdk";let br="disconnected";const $i=new Map,pn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=pn);function un(n,t){(t!=null&&t.force||br!=="disconnected")&&window.postMessage({source:$u,...n},"*")}function Uu(n){if(!n.isEnableDevtools()||typeof window>"u"||$i.has(n.getKey()))return;pn.set(n.getKey(),[]);const t=n.subscribe("all",e=>{e.some(r=>r.type!==_.StatusChanged&&r.type!==_.Snapshot&&r.type!==_.LocalChange&&r.type!==_.RemoteChange&&r.type!==_.Initialized&&r.type!==_.Watched&&r.type!==_.Unwatched&&r.type!==_.PresenceChanged)||(pn.get(n.getKey()).push(e),br==="synced"&&un({msg:"doc::sync::partial",docKey:n.getKey(),event:e}))});$i.set(n.getKey(),[t]),un({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var s;if(((s=e.data)==null?void 0:s.source)!==Mu)return;switch(e.data.msg){case"devtools::connect":if(br!=="disconnected")break;br="connected",un({msg:"doc::available",docKey:n.getKey()}),x.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":br="disconnected",x.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":br="synced",un({msg:"doc::sync::full",docKey:n.getKey(),events:pn.get(n.getKey())}),x.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var er=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(er||{}),_=(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))(_||{}),Bs=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Bs||{}),Rs=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Rs||{});class ea{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=Xr.create(),this.changeID=jc,this.checkpoint=Gc,this.localChanges=[],this.eventStream=Ou(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Fu,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Uu(this)}update(t,e){if(this.getStatus()==="removed")throw new g(d.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},e);try{const i=Fi(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(i,new _n(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){x.isEnabled(ee.Trivial)&&x.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),x.isEnabled(ee.Trivial)&&x.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,r,s){if(typeof t=="string"){if(typeof e!="function")throw new g(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==="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 g(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])}applyChangePack(t){for(t.hasSnapshot()?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),J.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();t.hasSnapshot()&&this.applyChanges(this.localChanges,J.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),this.garbageCollect(t.getMinSyncedTicket()),t.getIsRemoved()&&this.applyStatus("removed"),x.isEnabled(ee.Trivial)&&x.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:be(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return jn.create(this.key,e,!1,t)}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=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Fi(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e){const{root:r,presences:s}=W.bytesToSnapshot(e);this.root=new Xr(r),this.presences=s,this.changeID=this.changeID.syncLamport(t),this.clone=void 0,this.publish([{type:"snapshot",source:J.Remote,value:{snapshot:this.isEnableDevtools()?W.bytesToHex(e):void 0,serverSeq:t.toString()}}])}applyChanges(t,e){x.isEnabled(ee.Debug)&&x.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),x.isEnabled(ee.Trivial)&&x.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of t)this.applyChange(r,e);x.isEnabled(ee.Debug)&&x.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 ar.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 ar.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.syncLamport(t.getID().getLamport()),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===mr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(e===mr.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===mr.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($s),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}=t.value;if(!e)return;this.applySnapshot(BigInt(r),W.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Or.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 g(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?be(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?be(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?be(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:be(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:be(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}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ee)){new _n(e,be(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 g(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ee)){new _n(e,be(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])}}function qu(n,t){return e=>async r=>(n&&r.header.set("x-api-key",n),t&&r.header.set("authorization",t),await e(r))}const zu="yorkie-js-sdk",Ku="0.5.1",Vu="Yorkie JS SDK",ju="./src/yorkie.ts",Gu={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Wu=["dist"],Hu={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"},Yu={node:">=18.0.0",npm:">=7.1.0"},Xu={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Zu={name:"hackerwins",email:"susukang98@gmail.com"},Qu="Apache-2.0",_u={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},el="https://github.com/yorkie-team/yorkie-js-sdk#readme",tl={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},rl={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ui={name:zu,version:Ku,description:Vu,main:ju,publishConfig:Gu,files:Wu,scripts:Hu,engines:Yu,repository:Xu,author:Zu,license:Qu,bugs:_u,homepage:el,devDependencies:tl,dependencies:rl};function nl(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Ui.name+"/"+Ui.version),await n(t))}const sl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var yn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(yn||{});const ln={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ns={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ta{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"taskQueue");a(this,"processing",!1);e=e||ln,this.key=e.key?e.key:Zo(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||ln.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||ln.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||ln.retrySyncLoopDelay,this.rpcClient=nc(xc,kc({baseUrl:t,interceptors:[qu(e.apiKey,e.token),nl()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),x.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw x.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),x.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw x.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==er.Detached)throw new g(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(p){p instanceof Error&&(l==null||l(p))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:W.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=W.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()===er.Removed||(t.applyStatus(er.Attached),this.attachmentMap.set(t.getKey(),new Pu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),x.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(i=>{throw x.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(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:W.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=W.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==er.Removed&&t.applyStatus(er.Detached),this.detachInternal(t.getKey()),x.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(s=>{throw x.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(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 g(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),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(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=W.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=W.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),x.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(s=>{throw x.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,r,s){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);if(!sl(r))throw new g(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??ns.maxRetries,c=ns.maxBackoff;let l=0;const h=p=>Math.min(ns.initialRetryInterval*2**p,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(()=>{x.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(p=>{if(x.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(lf(),h(l-1)),x.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw x.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){x.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)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{x.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};x.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 g(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 g(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:_.ConnectionChanged,value:Bs.Connected}]),x.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:_.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:_.ConnectionChanged,value:Bs.Disconnected}]),x.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?r():this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===mr.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(er.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:W.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=W.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:_.SyncStatusChanged,value:Rs.Synced}]),r.getStatus()===er.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return x.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:_.SyncStatusChanged,value:Rs.SyncFailed}]),x.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(t){return t instanceof j?t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable?!0:((Li(t)===d.ErrClientNotActivated||Li(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{x.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const qi={Client:ta,Document:ea,Primitive:$,Text:Gn,Counter:Wn,Tree:Hn,LogLevel:ee,setLogLevel:Xo,IntType:ze.IntegerCnt,LongType:ze.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:ta,Document:ea,Primitive:$,Text:Gn,Counter:Wn,Tree:Hn,LogLevel:ee,setLogLevel:Xo,IntType:ze.IntegerCnt,LongType:ze.LongCnt});const zi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],il=()=>{const n=Math.floor(Math.random()*zi.length);return zi[n]},Ki=["red","yellow","orange","green","blue","purple"],ol=()=>{const n=Math.floor(Math.random()*Ki.length);return Ki[n]};async function al(){const n=new qi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new qi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==_.PresenceChanged&&cl(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:il(),color:ol()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const ss=4,is=(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);x.isEnabled(ee.Debug)&&x.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 ar.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 ar.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.syncLamport(t.getID().getLamport()),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===mr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(e===mr.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===mr.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($s),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}=t.value;if(!e)return;this.applySnapshot(BigInt(r),W.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Or.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 g(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?be(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?be(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?be(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:be(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:be(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}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ee)){new _n(e,be(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 g(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Ir.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ee)){new _n(e,be(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])}}function qu(n,t){return e=>async r=>(n&&r.header.set("x-api-key",n),t&&r.header.set("authorization",t),await e(r))}const zu="yorkie-js-sdk",Ku="0.5.2",Vu="Yorkie JS SDK",ju="./src/yorkie.ts",Gu={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Wu=["dist"],Hu={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"},Yu={node:">=18.0.0",npm:">=7.1.0"},Xu={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Zu={name:"hackerwins",email:"susukang98@gmail.com"},Qu="Apache-2.0",_u={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},el="https://github.com/yorkie-team/yorkie-js-sdk#readme",tl={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},rl={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ui={name:zu,version:Ku,description:Vu,main:ju,publishConfig:Gu,files:Wu,scripts:Hu,engines:Yu,repository:Xu,author:Zu,license:Qu,bugs:_u,homepage:el,devDependencies:tl,dependencies:rl};function nl(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Ui.name+"/"+Ui.version),await n(t))}const sl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var yn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(yn||{});const ln={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ns={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ta{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"taskQueue");a(this,"processing",!1);e=e||ln,this.key=e.key?e.key:Zo(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||ln.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||ln.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||ln.retrySyncLoopDelay,this.rpcClient=nc(xc,kc({baseUrl:t,interceptors:[qu(e.apiKey,e.token),nl()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),x.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw x.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),x.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw x.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==er.Detached)throw new g(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(p){p instanceof Error&&(l==null||l(p))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:W.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=W.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()===er.Removed||(t.applyStatus(er.Attached),this.attachmentMap.set(t.getKey(),new Pu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),x.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(i=>{throw x.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(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:W.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=W.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==er.Removed&&t.applyStatus(er.Detached),this.detachInternal(t.getKey()),x.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(s=>{throw x.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(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 g(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),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(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=W.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=W.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),x.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(s=>{throw x.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,r,s){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);if(!sl(r))throw new g(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??ns.maxRetries,c=ns.maxBackoff;let l=0;const h=p=>Math.min(ns.initialRetryInterval*2**p,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(()=>{x.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(p=>{if(x.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(lf(),h(l-1)),x.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw x.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){x.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)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{x.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};x.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 g(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 g(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:_.ConnectionChanged,value:Bs.Connected}]),x.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:_.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:_.ConnectionChanged,value:Bs.Disconnected}]),x.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?r():this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===mr.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(er.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:W.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=W.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:_.SyncStatusChanged,value:Rs.Synced}]),r.getStatus()===er.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return x.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:_.SyncStatusChanged,value:Rs.SyncFailed}]),x.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(t){return t instanceof j?t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable?!0:((Li(t)===d.ErrClientNotActivated||Li(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{x.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const qi={Client:ta,Document:ea,Primitive:$,Text:Gn,Counter:Wn,Tree:Hn,LogLevel:ee,setLogLevel:Xo,IntType:ze.IntegerCnt,LongType:ze.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:ta,Document:ea,Primitive:$,Text:Gn,Counter:Wn,Tree:Hn,LogLevel:ee,setLogLevel:Xo,IntType:ze.IntegerCnt,LongType:ze.LongCnt});const zi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],il=()=>{const n=Math.floor(Math.random()*zi.length);return zi[n]},Ki=["red","yellow","orange","green","blue","purple"],ol=()=>{const n=Math.floor(Math.random()*Ki.length);return Ki[n]};async function al(){const n=new qi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new qi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==_.PresenceChanged&&cl(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:il(),color:ol()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const ss=4,is=(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 2a44147ea..28c1cf504 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-BIdlKhE_.js b/examples/react-tldraw/assets/index-Dn-3KynT.js similarity index 99% rename from examples/react-tldraw/assets/index-BIdlKhE_.js rename to examples/react-tldraw/assets/index-Dn-3KynT.js index 01366df43..5749ac176 100644 --- a/examples/react-tldraw/assets/index-BIdlKhE_.js +++ b/examples/react-tldraw/assets/index-Dn-3KynT.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 mx(e){var t=Math.clz32(e&-e);return e?31-t:t}at.isLong=qn;var vx={},yx={};function Ol(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=yx[e],r)?r:(n=ct(e,0,!0),i&&(yx[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=vx[e],r)?r:(n=ct(e,e<0?-1:0,!1),i&&(vx[e]=n),n))}at.fromInt=Ol;function wi(e,t){if(isNaN(e))return t?cs:Yi;if(t){if(e<0)return cs;if(e>=IP)return BP}else{if(e<=-Cx)return yr;if(e+1>=Cx)return PP}return e<0?wi(-e,t).neg():ct(e%sd|0,e/sd|0,t)}at.fromNumber=wi;function ct(e,t,n){return new at(e,t,n)}at.fromBits=ct;var rm=Math.pow;function RC(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?cs:Yi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return RC(e.substring(1),t,n).neg();for(var i=wi(rm(n,8)),o=Yi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*sd+(this.low>>>0):this.high*sd+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,f=d.toString(t);if(a=u,a.isZero())return f+s;for(;f.length<6;)f="0"+f;s=""+f+s}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(yr)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,n=31;n>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return qn(t)||(t=lo(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=lo(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(Dc)};he.neg=he.negate;he.add=function(t){qn(t)||(t=lo(t));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=t.high>>>16,s=t.high&65535,u=t.low>>>16,d=t.low&65535,f=0,p=0,g=0,m=0;return m+=o+d,g+=m>>>16,m&=65535,g+=i+u,p+=g>>>16,g&=65535,p+=r+s,f+=p>>>16,p&=65535,f+=n+a,f&=65535,ct(g<<16|m,f<<16|p,this.unsigned)};he.subtract=function(t){return qn(t)||(t=lo(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(qn(t)||(t=lo(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?cs:Yi;if(this.eq(yr))return t.isOdd()?yr:Yi;if(t.eq(yr))return this.isOdd()?yr:Yi;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(bx)&&t.lt(bx))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,f=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*f,m+=v>>>16,v&=65535,m+=o*f,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*f,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*f+i*d+o*u+a*s,p&=65535,ct(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(qn(t)||(t=lo(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?cs:Yi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return cs;if(t.gt(this.shru(1)))return TP;o=cs}else{if(this.eq(yr)){if(t.eq(Dc)||t.eq(hy))return yr;if(t.eq(yr))return Dc;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(Yi)?t.isNegative()?Dc:hy:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?cs:Yi;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=Yi}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:rm(2,s-48),d=wi(r),f=d.mul(t);f.isNegative()||f.gt(i);)r-=u,d=wi(r,this.unsigned),f=d.mul(t);d.isZero()&&(d=Dc),o=o.add(d),i=i.sub(f)}return o};he.div=he.divide;he.modulo=function(t){if(qn(t)||(t=lo(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?mx(this.low):mx(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return qn(t)||(t=lo(t)),ct(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return qn(t)||(t=lo(t)),ct(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return qn(t)||(t=lo(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 En=(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))(En||{});class Gt extends $h{constructor(n,r){super(r);k(this,"valueType");k(this,"value");this.valueType=Gt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Gt(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(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Lo(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Gt.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 Gt.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(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class im extends DP{constructor(n){super(n);k(this,"prev");k(this,"next");this.value=n}static createAfter(n,r){const i=new im(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 lh{constructor(){k(this,"dummyHead");k(this,"last");k(this,"nodeMapByIndex");k(this,"nodeMapByCreatedAt");const t=Gt.of(0,eo);t.setRemovedAt(eo),this.dummyHead=new im(t),this.last=this.dummyHead,this.nodeMapByIndex=new uh,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new lh}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=im.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Ur extends mu{constructor(n,r){super(n);k(this,"elements");this.elements=r}static create(n,r){if(!r)return new Ur(n,lh.create());const i=lh.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new Ur(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 mu&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:Nc(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,f,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),f=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):eo:P0;if(m.canStyle(i,E)){const w=f.get(v),C=m.getCreatedAt();(!w||C.after(w))&&f.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:Nc(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[f,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Nc(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new Ii(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 Fh extends ao{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 Fh(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ii))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Lh extends ao{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 Lh(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ii))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const dKe=2,hKe="root",gs="text";function i0(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===gs}get paddedSize(){return this.size+(this.isText?0:dKe)}isAncestorOf(t){return pKe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function pKe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var an=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(an||{});function MP(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),MP(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function $P(e,t,n=0){for(const r of e.children)$P(r,t,n+1);t(e,n)}function g1(e,t,n=0){for(const r of e._children)g1(r,t,n+1);t(e,n)}function fy(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return fy(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 fy(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function RP(e){return e.isText||e.children.length===0?e:RP(e.children[0])}function gKe(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 yKe(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 qi{constructor(t,n){k(this,"parentID");k(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new qi(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],qi.of(r.id,Rn.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return qi.of(Rn.of(jr.fromStruct(t.parentID.createdAt),t.parentID.offset),Rn.of(jr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Rn{constructor(t,n){k(this,"createdAt");k(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new Rn(t,n)}static fromStruct(t){return Rn.of(jr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr(Rn.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr(Rn.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new ks);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function py(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(py)};return e.attrs&&(t.attributes=Nc((n=e.attrs)==null?void 0:n.toObject())),t}function FC(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()}="${Lo(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>FC(n)).join("")}`}function LP(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(LP),size:e.size,isRemoved:e.isRemoved}}class Ti extends $h{constructor(n,r){super(r);k(this,"indexTree");k(this,"nodeMapByID");this.indexTree=new mKe(n),this.nodeMapByID=new FP(Rn.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Ti(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,f=s?0:d.indexOf(a)+1;for(let p=f;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):eo:P0;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const A=v.setAttrs(r,i),I=A.reduce((D,[,$])=>($&&(D[$.getKey()]=p[$.getKey()]),D),{}),B=v.parent,T=v.prevSibling||v.parent;Object.keys(I).length>0&&f.push({type:"style",from:this.toIndex(B,T),to:this.toIndex(v,v),fromPath:this.toPath(B,T),toPath:this.toPath(v,v),actor:i.getActorID(),value:I});for(const[D]of A)D&&m.push({parent:v,child:D})}}),[g,m,f]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),f=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):eo:P0;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new ks);for(const I of r){const B=m.attrs.remove(I,i);for(const T of B)g.push({parent:m,child:T})}const b=m.parent,A=m.prevSibling||m.parent;f.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,A),to:this.toIndex(m,m),fromPath:this.toPath(b,A),toPath:this.toPath(m,m),value:r})}}),[p,g,f]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[f,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,f,p,([I,B],T)=>{if(B===an.Start&&!T)for(const O of I.children)w.push(O);const D=I.getCreatedAt().getActorID(),$=s?s.has(D)?s.get(D):eo:P0;if(I.canDelete(o,$)||v.includes(I.parent)){const O=C.get(D),H=I.getCreatedAt();(!O||H.after(O))&&C.set(D,H),(B===an.Text||B===an.Start)&&v.push(I),E.push([I,B])}});const b=this.makeDeletionChanges(E,o),A=[];for(const I of v)I.remove(o),I.isRemoved&&A.push({parent:this,child:I});for(const I of w)I.removedAt||u.append(I);if(i>0){let I=0,B=u,T=d;for(;I{u.isRemoved&&(D.remove(o),A.push({parent:this,child:D})),this.nodeMapByID.put(D.id,D)}),T.isRemoved||I.push(T);if(I.length){const T=I.map(D=>py(D));b.length&&b[b.length-1].from===g?b[b.length-1].value=T:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:T})}}return[b,A,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return qi.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 FC(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,f;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),f=qi.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?Nc((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:f};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===an.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?an.Text:an.Start]:[n,an.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,an.End];const s=o[a+1];return[s,s.isText?an.Text:an.Start]}findLeftToken([n,r]){if(r===an.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?an.Text:an.End]}return[n,an.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,an.Start];const s=o[a-1];return[s,s.isText?an.Text:an.End]}}class Oh extends ao{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 Oh(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>jr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:f,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>FC(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class nu{constructor(t,n,r,i){k(this,"clientSeq");k(this,"serverSeq");k(this,"lamport");k(this,"actor");this.clientSeq=t,this.serverSeq=i,this.lamport=n,this.actor=r}static of(t,n,r,i){return new nu(t,n,r,i)}next(){return new nu(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(t){return t>this.lamport?new nu(this.clientSeq,t,this.actor):new nu(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(t){return jr.of(this.lamport,t,this.actor)}setActor(t){return new nu(this.clientSeq,this.lamport,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const CKe=new nu(0,0n,MC);class ud{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 ud({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===Du.Put?n.set(this.id.getActorID(),Vi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:Cn.bytesToHex(Cn.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>Cn.bytesToHex(Cn.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return ud.create({id:Cn.bytesToChangeID(Cn.hexToBytes(n)),operations:r==null?void 0:r.map(a=>Cn.bytesToOperation(Cn.hexToBytes(a))),presenceChange:i,message:o})}}class m1{constructor(t,n,r,i,o,a){k(this,"documentKey");k(this,"checkpoint");k(this,"isRemoved");k(this,"changes");k(this,"snapshot");k(this,"minSyncedTicket");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a}static create(t,n,r,i,o,a){return new m1(t,n,r,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class zc{constructor(t,n){k(this,"serverSeq");k(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new zc(t,n)}increaseClientSeq(t){return t===0?this:new zc(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 zc.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 bKe=new zc(0n,0);class No{constructor(t,n){k(this,"createdAt");k(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new No(t,n)}static fromStruct(t){return No.of(jr.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 No(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 wKe=No.of(eo,0);class to{constructor(t,n){k(this,"id");k(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new to(t,n)}static fromStruct(t){const n=No.fromStruct(t.id);return to.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return No.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 vu extends DP{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 vu(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const f=d.getCreatedAt().getActorID();(!a.has(f)||d.getID().getCreatedAt().after(a.get(f)))&&a.set(f,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const f=d.getCreatedAt().getActorID(),p=i?r.has(f)?r.get(f):eo:P0;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var Uo=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))(Uo||{});class Kr extends $h{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=wx(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=at.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Kr(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(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Kr.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!!Kr.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===En.Long?this.value=this.value+n.getValue().toInt():this.value=at.fromNumber(this.value+wx(n.getValue())).toInt(),this}}class cd extends ao{constructor(n,r,i){super(n,i);k(this,"value");this.value=r}static create(n,r,i){return new cd(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Kr))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===En.Long?n.getValue().multiply(-1):n.getValue()*-1;return cd.create(this.getParentCreatedAt(),Gt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ms extends ao{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 ms(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ms(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:f,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:f,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function SKe(e){const t=new BC,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function xKe(e){if(e.type===Du.Put)return new ah({type:Dl.PUT,presence:SKe(e.presence)});if(e.type===Du.Clear)return new ah({type:Dl.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function AKe(e){return new xP({serverSeq:e.getServerSeq(),clientSeq:e.getClientSeq()})}function OP(e){return new p1({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:jC(e.getActorID())})}function Te(e){if(e)return new De({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:jC(e.getActorID())})}function _P(e){switch(e){case En.Null:return Ve.NULL;case En.Boolean:return Ve.BOOLEAN;case En.Integer:return Ve.INTEGER;case En.Long:return Ve.LONG;case En.Double:return Ve.DOUBLE;case En.String:return Ve.STRING;case En.Bytes:return Ve.BYTES;case En.Date:return Ve.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function NP(e){switch(e){case Uo.IntegerCnt:return Ve.INTEGER_CNT;case Uo.LongCnt:return Ve.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function Zv(e){if(e instanceof wr)return new ci({type:Ve.JSON_OBJECT,createdAt:Te(e.getCreatedAt()),value:ZP(e)});if(e instanceof Ur)return new ci({type:Ve.JSON_ARRAY,createdAt:Te(e.getCreatedAt()),value:eVe(e)});if(e instanceof Ii)return new ci({type:Ve.TEXT,createdAt:Te(e.getCreatedAt())});if(e instanceof Gt)return new ci({type:_P(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Kr)return new ci({type:NP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Ti)return new ci({type:Ve.TREE,createdAt:Te(e.getCreatedAt()),value:nVe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function kKe(e){return new ih({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function Ep(e){return new As({createdAt:Te(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function Cp(e){return new kl({parentId:B0(e.getParentID()),leftSiblingId:B0(e.getLeftSiblingID())})}function B0(e){return new gu({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function zP(e){const t=new PC;if(e instanceof Il){const n=e,r=new Ng;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.key=n.getKey(),r.value=Zv(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof Rh){const n=e,r=new zg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.value=Zv(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof ou){const n=e,r=new Hg;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 Iu){const n=e,r=new jg;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 Fh){const n=e,r=new Ug;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Ep(n.getFromPos()),r.to=Ep(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 Lh){const n=e,r=new Kg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Ep(n.getFromPos()),r.to=Ep(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 cd){const n=e,r=new Vg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.value=Zv(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof Oh){const n=e,r=new Gg,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=Te(a);r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Cp(n.getFromPos()),r.to=Cp(n.getToPos()),r.contents=$Ke(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=Te(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ms){const n=e,r=new Jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=Cp(n.getFromPos()),r.to=Cp(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(W.ErrUnimplemented,"unimplemented operation");return t}function DKe(e){const t=[];for(const n of e)t.push(zP(n));return t}function IKe(e){const t=new wP({id:OP(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=DKe(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=xKe(e.getPresenceChange())),t}function TKe(e){const t=[];for(const n of e)t.push(IKe(n));return t}function PKe(e){const t=[];for(const n of e)t.push(new SP({key:n.getStrKey(),element:OC(n.getValue())}));return t}function BKe(e){const t=[];for(const n of e)t.push(new em({element:OC(n.getValue())}));return t}function MKe(e){const t=[];for(const n of e){const r=new tm;r.id=kKe(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 od;s.value=a.getValue(),s.updatedAt=Te(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function $Ke(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new nm({content:LC(n)}));return t}function RKe(e){const t={};for(const n of e)t[n.getKey()]=new od({value:n.getValue(),updatedAt:Te(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function LC(e){if(!e)return[];const t=[];return g1(e,(n,r)=>{const i=new oh({id:B0(n.id),type:n.type,removedAt:Te(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=B0(n.insPrevID)),n.insNextID&&(i.insNextId=B0(n.insNextID)),n.attrs&&(i.attributes=RKe(n.attrs)),t.push(i)}),t}function FKe(e){const t=new Sr;return t.body.case="jsonObject",t.body.value=new Wg({nodes:PKe(e.getRHT()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function HP(e){const t=new Sr;return t.body.case="jsonArray",t.body.value=new Yg({nodes:BKe(e.getElements()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function LKe(e){const t=new Sr;return t.body.case="primitive",t.body.value=new qg({type:_P(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function OKe(e){const t=new Sr;return t.body.case="text",t.body.value=new Xg({nodes:MKe(e.getRGATreeSplit()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function _Ke(e){const t=new Sr;return t.body.case="counter",t.body.value=new Zg({type:NP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function jP(e){const t=new Sr;return t.body.case="tree",t.body.value=new Qg({nodes:LC(e.getRoot()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function OC(e){if(e instanceof wr)return FKe(e);if(e instanceof Ur)return HP(e);if(e instanceof Gt)return LKe(e);if(e instanceof Ii)return OKe(e);if(e instanceof Kr)return _Ke(e);if(e instanceof Ti)return jP(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function NKe(e){return new Ms({documentKey:e.getDocumentKey(),checkpoint:AKe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:TKe(e.getChanges()),snapshot:e.getSnapshot(),minSyncedTicket:Te(e.getMinSyncedTicket())})}function Sx(e){const t=e.findDetails(nKe);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function UP(e){return nu.of(e.clientSeq,BigInt(e.lamport),HC(e.actorId),BigInt(e.serverSeq))}function Pe(e){if(e)return jr.of(BigInt(e.lamport),e.delimiter,HC(e.actorId))}function _C(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function zKe(e){const t=e.type;if(t===Dl.PUT){const n=_C(e.presence);return{type:Du.Put,presence:n}}if(t===Dl.CLEAR)return{type:Du.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function HKe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,_C(r))}),t}function KP(e){switch(e){case Ve.NULL:return En.Null;case Ve.BOOLEAN:return En.Boolean;case Ve.INTEGER:return En.Integer;case Ve.LONG:return En.Long;case Ve.DOUBLE:return En.Double;case Ve.STRING:return En.String;case Ve.BYTES:return En.Bytes;case Ve.DATE:return En.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function om(e){switch(e){case Ve.INTEGER_CNT:return Uo.IntegerCnt;case Ve.LONG_CNT:return Uo.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function Qv(e){switch(e.type){case Ve.JSON_OBJECT:return e.value?XP(e.value):wr.create(Pe(e.createdAt));case Ve.JSON_ARRAY:return e.value?QKe(e.value):Ur.create(Pe(e.createdAt));case Ve.TEXT:return Ii.create(ld.create(),Pe(e.createdAt));case Ve.TREE:return tVe(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 Gt.of(Gt.valueFromBytes(KP(e.type),e.value),Pe(e.createdAt));case Ve.INTEGER_CNT:case Ve.LONG_CNT:return Kr.create(om(e.type),Kr.valueFromBytes(om(e.type),e.value),Pe(e.createdAt))}}function bp(e){return to.of(No.of(Pe(e.createdAt),e.offset),e.relativeOffset)}function VP(e){return No.of(Pe(e.createdAt),e.offset)}function jKe(e){const t=ch.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Pe(i.updatedAt))});const n=vu.create(VP(e.id),t);return n.remove(Pe(e.removedAt)),n}function cc(e){return qi.of(M0(e.parentId),M0(e.leftSiblingId))}function M0(e){return Rn.of(Pe(e.createdAt),e.offset)}function UKe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=NC(n.content);t.push(r)}),t}function NC(e){if(e.length===0)return;const t=[];for(const i of e)t.push(VKe(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(),Ti.create(n,eo).getRoot()}function KKe(e){const t=ks.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Pe(r.updatedAt),r.isRemoved);return t}function VKe(e){const t=M0(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=KKe(e.attributes)),e.insPrevId&&(n.insPrevID=M0(e.insPrevId)),e.insNextId&&(n.insNextID=M0(e.insNextId)),n.removedAt=Pe(e.removedAt),n}function GP(e){if(e.body.case==="set"){const t=e.body.value;return Il.create(t.key,Qv(t.value),Pe(t.parentCreatedAt),Pe(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return Rh.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),Qv(t.value),Pe(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return ou.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 Iu.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)}),Fh.create(Pe(t.parentCreatedAt),bp(t.from),bp(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)}),Lh.create(Pe(t.parentCreatedAt),bp(t.from),bp(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 cd.create(Pe(t.parentCreatedAt),Qv(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))}),Oh.create(Pe(t.parentCreatedAt),cc(t.from),cc(t.to),UKe(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?ms.createTreeRemoveStyleOperation(Pe(t.parentCreatedAt),cc(t.from),cc(t.to),i,r,Pe(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ms.create(Pe(t.parentCreatedAt),cc(t.from),cc(t.to),i,n,Pe(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function GKe(e){const t=[];for(const n of e){const r=GP(n);r&&t.push(r)}return t}function JP(e){const t=[];for(const n of e)t.push(ud.create({id:UP(n.id),operations:GKe(n.operations),presenceChange:n.presenceChange?zKe(n.presenceChange):void 0,message:n.message}));return t}function JKe(e){return zc.of(BigInt(e.serverSeq),e.clientSeq)}function WKe(e){return m1.create(e.documentKey,JKe(e.checkpoint),e.isRemoved,JP(e.changes),e.snapshot,Pe(e.minSyncedTicket))}function WP(e){const t=new sh;for(const r of e.nodes){const i=zC(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 YP(e){const t=new lh;for(const r of e.nodes)t.insert(zC(r.element));const n=new Ur(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function YKe(e){const t=Gt.of(Gt.valueFromBytes(KP(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function qKe(e){const t=new ld;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,jKe(i));i.insPrevId&&o.setInsPrev(t.findNode(VP(i.insPrevId))),n=o}const r=new Ii(t,Pe(e.createdAt));return r.setMovedAt(Pe(e.movedAt)),r.setRemovedAt(Pe(e.removedAt)),r}function XKe(e){const t=Kr.create(om(e.type),Kr.valueFromBytes(om(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function qP(e){const t=NC(e.nodes);return Ti.create(t,Pe(e.createdAt))}function zC(e){if(e.body.case==="jsonObject")return WP(e.body.value);if(e.body.case==="jsonArray")return YP(e.body.value);if(e.body.case==="primitive")return YKe(e.body.value);if(e.body.case==="text")return qKe(e.body.value);if(e.body.case==="counter")return XKe(e.body.value);if(e.body.case==="tree")return qP(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function ZKe(e){if(!e)return{root:wr.create(eo),presences:new Map};const t=U3.fromBinary(e);return{root:zC(t.root),presences:HKe(t.presences)}}function XP(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return WP(t.body.value)}function ZP(e){return OC(e).toBinary()}function QKe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return YP(t.body.value)}function eVe(e){return HP(e).toBinary()}function tVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return qP(t.body.value)}function nVe(e){return jP(e).toBinary()}function QP(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function HC(e){return QP(e)}function eB(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function jC(e){return eB(e)}function rVe(e){const t=p1.fromBinary(e);return UP(t)}function iVe(e){const t=PC.fromBinary(e);return GP(t)}const Cn={fromPresence:_C,toChangePack:NKe,fromChangePack:WKe,fromChanges:JP,toTreeNodes:LC,fromTreeNodes:NC,objectToBytes:ZP,bytesToObject:XP,bytesToSnapshot:ZKe,bytesToHex:QP,hexToBytes:eB,toHexString:HC,toUint8Array:jC,toOperation:zP,toChangeID:OP,PbChangeID:p1,bytesToChangeID:rVe,bytesToOperation: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 el=3;function tB(e){el=e}const $e={trivial:(...e)=>{el>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{el>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{el>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{el>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{el>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=>el<=e};function nB(){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 oVe{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===Jp.RealtimeSyncOff?!1:this.syncMode===Jp.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Jp.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 e2=()=>{};class aVe{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(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=e2),i.error===void 0&&(i.error=e2),i.complete===void 0&&(i.complete=e2);const o=nB(),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 Ic{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=kP,this.root=n,this.operations=[],this.previousPresence=Vi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new Ic(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 ud.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 dh{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 Ii||n instanceof Ti)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new dh(wr.create(eo))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof mu&&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 mu&&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 mu&&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 dh(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&t.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&t.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function rB(e,t){const n=new hh(e);return new Proxy(t,n.getHandlers())}class hh{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)}`),hh.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():tl(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),hh.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=am(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(Il.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=am(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(Iu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function uVe(e,t){const n=new qt(e,t);return new Proxy(t,n.getHandlers())}function lVe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function cVe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class qt{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 Ys(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return Ys(t,s)}:i==="getLast"?()=>Ys(t,r.getLast()):i==="deleteByID"?a=>{const s=qt.deleteInternalByID(t,r,a);return Ys(t,s)}:i==="insertAfter"?(a,s)=>{const u=qt.insertAfterInternal(t,r,a,s);return Ys(t,u)}:i==="insertBefore"?(a,s)=>{const u=qt.insertBeforeInternal(t,r,a,s);return Ys(t,u)}:i==="moveBefore"?(a,s)=>{qt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{qt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{qt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{qt.moveLastInternal(t,r,a)}:lVe(i)?tl(t,r.get(Number(i))):i==="push"?a=>qt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>qt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?qt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>qt.includes(t,r,a,s):i==="indexOf"?(a,s)=>qt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>qt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>qt.toTestString(r):typeof i=="string"&&cVe(i)?(...a)=>{const s=Array.from(r).map(u=>tl(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}]`),qt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield Ys(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=am(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return qt.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(ou.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(ou.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(ou.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(ou.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=am(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(Rh.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return qt.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(Iu.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(Iu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let f=s;f=o)return!1;if(Gt.isSupport(r))return Array.from(n).map(d=>tl(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>tl(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>tl(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 v1{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(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?ad(i):void 0,s=this.context.issueTimeTicket(),[u,,d,f]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new Fh(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(f)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=ad(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 Lh(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([to.fromStruct(t[0]),to.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class y1{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(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Gt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(cd.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function UC(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===gs){iB(e);const{value:o}=e,a=Nr.create(Rn.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!AP(a)){const d=ad(a);s=new ks;for(const[f,p]of Object.entries(d))s.set(f,p,i)}const u=Nr.create(Rn.of(i,0),r,void 0,s);t.append(u);for(const d of o)UC(d,u,n)}}function dVe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===gs){const{value:o}=t;i=Nr.create(Rn.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!AP(a)){const u=ad(a);s=new ks;for(const[d,f]of Object.entries(u))s.set(d,f,r)}i=Nr.create(Rn.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)UC(u,i,e)}return i}function iB(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function xx(e){if(!e.length)return!0;if(e[0].type===gs)for(const n of e){const{type:r}=n;if(r!==gs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");iB(n)}else for(const n of e){const{type:r}=n;if(r===gs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class E1{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(Rn.of(t.issueTimeTicket(),0),hKe);const n=Nr.create(Rn.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)UC(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?ad(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ms.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?ad(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const f of d)this.context.registerGCPair(f);this.context.push(ms.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ms.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(xx(r),r[0].type!==gs))for(const f of r){const{children:p=[]}=f;xx(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===gs){let f="";for(const p of r){const{value:g}=p;f+=g}a.push(Nr.create(Rn.of(this.context.issueTimeTicket(),0),gs,f))}else a=r.map(f=>f&&dVe(this.context,f)).filter(f=>f);const[,s,u]=this.tree.edit([t,n],a.length?a.map(f=>f==null?void 0:f.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const f of s)this.context.registerGCPair(f);return this.context.push(Oh.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[qi.fromStruct(t[0]),qi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[qi.fromStruct(t[0]),qi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Ax(e,t){return rB(e,t)}function Ys(e,t){if(t){if(t instanceof Gt)return t;if(t instanceof wr)return rB(e,t);if(t instanceof Ur)return uVe(e,t);if(t instanceof Ii)return new v1(e,t);if(t instanceof Kr){const n=new y1(Uo.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Ti){const n=new E1;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function tl(e,t){const n=Ys(e,t);return n instanceof Gt?n.getValue():n}function am(e,t,n){let r;if(Gt.isSupport(t))r=Gt.of(t,n);else if(Array.isArray(t))r=Ur.create(n,qt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof v1?(r=Ii.create(ld.create(),n),t.initialize(e,r)):t instanceof y1?(r=Kr.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof E1?(r=Ti.create(t.buildRoot(e),n),t.initialize(e,r)):r=wr.create(n,hh.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const kx=50;class hVe{constructor(){k(this,"undoStack",[]);k(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=kx&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=kx&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const fVe="yorkie-devtools-panel",pVe="yorkie-devtools-sdk";let hc="disconnected";const Dx=new Map,Gp=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Gp);function wp(e,t){(t!=null&&t.force||hc!=="disconnected")&&window.postMessage({source:pVe,...e},"*")}function gVe(e){if(!e.isEnableDevtools()||typeof window>"u"||Dx.has(e.getKey()))return;Gp.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==Un.StatusChanged&&r.type!==Un.Snapshot&&r.type!==Un.LocalChange&&r.type!==Un.RemoteChange&&r.type!==Un.Initialized&&r.type!==Un.Watched&&r.type!==Un.Unwatched&&r.type!==Un.PresenceChanged)||(Gp.get(e.getKey()).push(n),hc==="synced"&&wp({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Dx.set(e.getKey(),[t]),wp({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==fVe)return;switch(n.data.msg){case"devtools::connect":if(hc!=="disconnected")break;hc="connected",wp({msg:"doc::available",docKey:e.getKey()}),$e.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":hc="disconnected",$e.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":hc="synced",wp({msg:"doc::sync::full",docKey:e.getKey(),events:Gp.get(e.getKey())}),$e.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var qs=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(qs||{}),Un=(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))(Un||{}),gy=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(gy||{}),my=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(my||{});class KC{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=dh.create(),this.changeID=CKe,this.checkpoint=bKe,this.localChanges=[],this.eventStream=sVe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new hVe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},gVe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Ax(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new Xv(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(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const f of u.value.operations)this.isSameElementOrChildOf(f.path,o)&&d.push(f);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}applyChangePack(t){for(t.hasSnapshot()?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),xt.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();t.hasSnapshot()&&this.applyChanges(this.localChanges,xt.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),this.garbageCollect(t.getMinSyncedTicket()),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:Vi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return m1.create(this.key,n,!1,t)}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ax(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n){const{root:r,presences:i}=Cn.bytesToSnapshot(n);this.root=new dh(r),this.presences=i,this.changeID=this.changeID.syncLamport(t),this.clone=void 0,this.publish([{type:"snapshot",source:xt.Remote,value:{snapshot:this.isEnableDevtools()?Cn.bytesToHex(n):void 0,serverSeq:t.toString()}}])}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.syncLamport(t.getID().getLamport()),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===gl.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===gl.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===gl.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(MC),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}=t.value;if(!n)return;this.applySnapshot(BigInt(r),Cn.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=ud.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Vi(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?Vi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Vi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Vi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Vi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof ao)){new Xv(n,Vi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,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(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof ao)){new Xv(n,Vi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,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])}}function mVe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const vVe="yorkie-js-sdk",yVe="0.5.1",EVe="Yorkie JS SDK",CVe="./src/yorkie.ts",bVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},wVe=["dist"],SVe={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"},xVe={node:">=18.0.0",npm:">=7.1.0"},AVe={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},kVe={name:"hackerwins",email:"susukang98@gmail.com"},DVe="Apache-2.0",IVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},TVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",PVe={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},BVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ix={name:vVe,version:yVe,description:EVe,main:CVe,publishConfig:bVe,files:wVe,scripts:SVe,engines:xVe,repository:AVe,author:kVe,license:DVe,bugs:IVe,homepage:TVe,devDependencies:PVe,dependencies:BVe};function MVe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Ix.name+"/"+Ix.version),await e(t))}const $Ve=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Jp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Jp||{});const Sp={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},t2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class VC{constructor(t,n){k(this,"id");k(this,"key");k(this,"status");k(this,"attachmentMap");k(this,"apiKey");k(this,"conditions");k(this,"syncLoopDuration");k(this,"reconnectStreamDelay");k(this,"retrySyncLoopDelay");k(this,"rpcClient");k(this,"taskQueue");k(this,"processing",!1);n=n||Sp,this.key=n.key?n.key:nB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Sp.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Sp.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Sp.retrySyncLoopDelay,this.rpcClient=MUe(tKe,eKe({baseUrl:t,interceptors:[mVe(n.apiKey,n.token),MVe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw $e.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==qs.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var f;const{topic:a,payload:s}=o.value,u=(f=o.options)==null?void 0:f.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:Cn.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=Cn.fromChangePack(o.changePack);return t.applyChangePack(a),t.getStatus()===qs.Removed||(t.applyStatus(qs.Attached),this.attachmentMap.set(t.getKey(),new oVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:Cn.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=Cn.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==qs.Removed&&t.applyStatus(qs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=Cn.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=Cn.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!$Ve(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??t2.maxRetries,s=t2.maxBackoff;let u=0;const d=p=>Math.min(t2.initialRetryInterval*2**p,s),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uf(),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 f()}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)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:Un.ConnectionChanged,value:gy.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:Un.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:Un.ConnectionChanged,value:gy.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===gl.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(qs.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:Cn.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=Cn.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:Un.SyncStatusChanged,value:my.Synced}]),r.getStatus()===qs.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(a=>{throw r.publish([{type:Un.SyncStatusChanged,value:my.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof hn?t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable?!0:((Sx(t)===W.ErrClientNotActivated||Sx(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Uo.IntegerCnt,Uo.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:VC,Document:KC,Primitive:Gt,Text:v1,Counter:y1,Tree:E1,LogLevel:or,setLogLevel:tB,IntType:Uo.IntegerCnt,LongType:Uo.LongCnt});var vy={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(dc,function(){var n=null,r={};C();var i=[],o=function(D){if(D=D||{},D.seed!==void 0&&D.seed!==null&&D.seed===parseInt(D.seed,10))n=D.seed;else if(typeof D.seed=="string")n=B(D.seed);else{if(D.seed!==void 0&&D.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var $,O,H;if(D.count!==null&&D.count!==void 0){for(var K=D.count,Z=[],X=0;XZ.length;){var pe=o(D);n!==null&&(D.seed=n),Z.push(pe)}return D.count=K,Z}return $=a(D),O=s($,D),H=u($,O,D),d([$,O,H],D)};function a(D){if(i.length>0){var $=T(D.hue),O=v($),H=($[1]-$[0])/i.length,K=parseInt((O-$[0])/H);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var Z=($[0]+K*H)%359,X=($[0]+(K+1)*H)%359;return $=[Z,X],O=v($),O<0&&(O=360+O),O}else{var $=p(D.hue);return O=v($),O<0&&(O=360+O),O}}function s(D,$){if($.hue==="monochrome")return 0;if($.luminosity==="random")return v([0,100]);var O=g(D),H=O[0],K=O[1];switch($.luminosity){case"bright":H=55;break;case"dark":H=K-10;break;case"light":K=55;break}return v([H,K])}function u(D,$,O){var H=f(D,$),K=100;switch(O.luminosity){case"dark":K=H+20;break;case"light":H=(K+H)/2;break;case"random":H=0,K=100;break}return v([H,K])}function d(D,$){switch($.format){case"hsvArray":return D;case"hslArray":return I(D);case"hsl":var O=I(D);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var H=I(D),X=$.alpha||Math.random();return"hsla("+H[0]+", "+H[1]+"%, "+H[2]+"%, "+X+")";case"rgbArray":return b(D);case"rgb":var K=b(D);return"rgb("+K.join(", ")+")";case"rgba":var Z=b(D),X=$.alpha||Math.random();return"rgba("+Z.join(", ")+", "+X+")";default:return E(D)}}function f(D,$){for(var O=m(D).lowerBounds,H=0;H=K&&$<=X){var me=(pe-Z)/(X-K),Ce=Z-me*K;return me*$+Ce}}return 0}function p(D){if(typeof parseInt(D)=="number"){var $=parseInt(D);if($<360&&$>0)return[$,$]}if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=A(D)[0];return[H,H]}}return[0,360]}function g(D){return m(D).saturationRange}function m(D){D>=334&&D<=360&&(D-=360);for(var $ in r){var O=r[$];if(O.hueRange&&D>=O.hueRange[0]&&D<=O.hueRange[1])return r[$]}return"Color not found"}function v(D){if(n===null){var $=.618033988749895,O=Math.random();return O+=$,O%=1,Math.floor(D[0]+O*(D[1]+1-D[0]))}else{var H=D[1]||1,K=D[0]||0;n=(n*9301+49297)%233280;var Z=n/233280;return Math.floor(K+Z*(H-K))}}function E(D){var $=b(D);function O(K){var Z=K.toString(16);return Z.length==1?"0"+Z:Z}var H="#"+O($[0])+O($[1])+O($[2]);return H}function w(D,$,O){var H=O[0][0],K=O[O.length-1][0],Z=O[O.length-1][1],X=O[0][1];r[D]={hueRange:$,lowerBounds:O,saturationRange:[H,K],brightnessRange:[Z,X]}}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(D){var $=D[0];$===0&&($=1),$===360&&($=359),$=$/360;var O=D[1]/100,H=D[2]/100,K=Math.floor($*6),Z=$*6-K,X=H*(1-O),pe=H*(1-Z*O),me=H*(1-(1-Z)*O),Ce=256,J=256,U=256;switch(K){case 0:Ce=H,J=me,U=X;break;case 1:Ce=pe,J=H,U=X;break;case 2:Ce=X,J=H,U=me;break;case 3:Ce=X,J=pe,U=H;break;case 4:Ce=me,J=X,U=H;break;case 5:Ce=H,J=X,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(J*255),Math.floor(U*255)];return ne}function A(D){D=D.replace(/^#/,""),D=D.length===3?D.replace(/(.)/g,"$1$1"):D;var $=parseInt(D.substr(0,2),16)/255,O=parseInt(D.substr(2,2),16)/255,H=parseInt(D.substr(4,2),16)/255,K=Math.max($,O,H),Z=K-Math.min($,O,H),X=K?Z/K:0;switch(K){case $:return[60*((O-H)/Z%6)||0,X,K];case O:return[60*((H-$)/Z+2)||0,X,K];case H:return[60*(($-O)/Z+4)||0,X,K]}}function I(D){var $=D[0],O=D[1]/100,H=D[2]/100,K=(2-O)*H;return[$,Math.round(O*H/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(D){for(var $=0,O=0;O!==D.length&&!($>=Number.MAX_SAFE_INTEGER);O++)$+=D.charCodeAt(O);return $}function T(D){if(isNaN(D)){if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=A(D)[0];return m(H).hueRange}}}else{var $=parseInt(D);if($<360&&$>0)return m(D).hueRange}return[0,360]}return o})})(vy,vy.exports);var RVe=vy.exports;const FVe=fh(RVe),Tx=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 LVe{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.syncLamport(t.getID().getLamport()),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===gl.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===gl.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===gl.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(MC),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}=t.value;if(!n)return;this.applySnapshot(BigInt(r),Cn.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=ud.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Vi(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?Vi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Vi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Vi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Vi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof ao)){new Xv(n,Vi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,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(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Ic.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof ao)){new Xv(n,Vi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const f=n.issueTimeTicket();d.setExecutedAt(f),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,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])}}function mVe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const vVe="yorkie-js-sdk",yVe="0.5.2",EVe="Yorkie JS SDK",CVe="./src/yorkie.ts",bVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},wVe=["dist"],SVe={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"},xVe={node:">=18.0.0",npm:">=7.1.0"},AVe={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},kVe={name:"hackerwins",email:"susukang98@gmail.com"},DVe="Apache-2.0",IVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},TVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",PVe={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},BVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ix={name:vVe,version:yVe,description:EVe,main:CVe,publishConfig:bVe,files:wVe,scripts:SVe,engines:xVe,repository:AVe,author:kVe,license:DVe,bugs:IVe,homepage:TVe,devDependencies:PVe,dependencies:BVe};function MVe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Ix.name+"/"+Ix.version),await e(t))}const $Ve=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Jp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Jp||{});const Sp={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},t2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class VC{constructor(t,n){k(this,"id");k(this,"key");k(this,"status");k(this,"attachmentMap");k(this,"apiKey");k(this,"conditions");k(this,"syncLoopDuration");k(this,"reconnectStreamDelay");k(this,"retrySyncLoopDelay");k(this,"rpcClient");k(this,"taskQueue");k(this,"processing",!1);n=n||Sp,this.key=n.key?n.key:nB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Sp.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Sp.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Sp.retrySyncLoopDelay,this.rpcClient=MUe(tKe,eKe({baseUrl:t,interceptors:[mVe(n.apiKey,n.token),MVe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw $e.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==qs.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var f;const{topic:a,payload:s}=o.value,u=(f=o.options)==null?void 0:f.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:Cn.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=Cn.fromChangePack(o.changePack);return t.applyChangePack(a),t.getStatus()===qs.Removed||(t.applyStatus(qs.Attached),this.attachmentMap.set(t.getKey(),new oVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:Cn.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=Cn.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==qs.Removed&&t.applyStatus(qs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=Cn.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=Cn.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!$Ve(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??t2.maxRetries,s=t2.maxBackoff;let u=0;const d=p=>Math.min(t2.initialRetryInterval*2**p,s),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uf(),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 f()}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)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:Un.ConnectionChanged,value:gy.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:Un.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:Un.ConnectionChanged,value:gy.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===gl.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(qs.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:Cn.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=Cn.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:Un.SyncStatusChanged,value:my.Synced}]),r.getStatus()===qs.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(a=>{throw r.publish([{type:Un.SyncStatusChanged,value:my.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof hn?t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable?!0:((Sx(t)===W.ErrClientNotActivated||Sx(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Uo.IntegerCnt,Uo.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:VC,Document:KC,Primitive:Gt,Text:v1,Counter:y1,Tree:E1,LogLevel:or,setLogLevel:tB,IntType:Uo.IntegerCnt,LongType:Uo.LongCnt});var vy={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(dc,function(){var n=null,r={};C();var i=[],o=function(D){if(D=D||{},D.seed!==void 0&&D.seed!==null&&D.seed===parseInt(D.seed,10))n=D.seed;else if(typeof D.seed=="string")n=B(D.seed);else{if(D.seed!==void 0&&D.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var $,O,H;if(D.count!==null&&D.count!==void 0){for(var K=D.count,Z=[],X=0;XZ.length;){var pe=o(D);n!==null&&(D.seed=n),Z.push(pe)}return D.count=K,Z}return $=a(D),O=s($,D),H=u($,O,D),d([$,O,H],D)};function a(D){if(i.length>0){var $=T(D.hue),O=v($),H=($[1]-$[0])/i.length,K=parseInt((O-$[0])/H);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var Z=($[0]+K*H)%359,X=($[0]+(K+1)*H)%359;return $=[Z,X],O=v($),O<0&&(O=360+O),O}else{var $=p(D.hue);return O=v($),O<0&&(O=360+O),O}}function s(D,$){if($.hue==="monochrome")return 0;if($.luminosity==="random")return v([0,100]);var O=g(D),H=O[0],K=O[1];switch($.luminosity){case"bright":H=55;break;case"dark":H=K-10;break;case"light":K=55;break}return v([H,K])}function u(D,$,O){var H=f(D,$),K=100;switch(O.luminosity){case"dark":K=H+20;break;case"light":H=(K+H)/2;break;case"random":H=0,K=100;break}return v([H,K])}function d(D,$){switch($.format){case"hsvArray":return D;case"hslArray":return I(D);case"hsl":var O=I(D);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var H=I(D),X=$.alpha||Math.random();return"hsla("+H[0]+", "+H[1]+"%, "+H[2]+"%, "+X+")";case"rgbArray":return b(D);case"rgb":var K=b(D);return"rgb("+K.join(", ")+")";case"rgba":var Z=b(D),X=$.alpha||Math.random();return"rgba("+Z.join(", ")+", "+X+")";default:return E(D)}}function f(D,$){for(var O=m(D).lowerBounds,H=0;H=K&&$<=X){var me=(pe-Z)/(X-K),Ce=Z-me*K;return me*$+Ce}}return 0}function p(D){if(typeof parseInt(D)=="number"){var $=parseInt(D);if($<360&&$>0)return[$,$]}if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=A(D)[0];return[H,H]}}return[0,360]}function g(D){return m(D).saturationRange}function m(D){D>=334&&D<=360&&(D-=360);for(var $ in r){var O=r[$];if(O.hueRange&&D>=O.hueRange[0]&&D<=O.hueRange[1])return r[$]}return"Color not found"}function v(D){if(n===null){var $=.618033988749895,O=Math.random();return O+=$,O%=1,Math.floor(D[0]+O*(D[1]+1-D[0]))}else{var H=D[1]||1,K=D[0]||0;n=(n*9301+49297)%233280;var Z=n/233280;return Math.floor(K+Z*(H-K))}}function E(D){var $=b(D);function O(K){var Z=K.toString(16);return Z.length==1?"0"+Z:Z}var H="#"+O($[0])+O($[1])+O($[2]);return H}function w(D,$,O){var H=O[0][0],K=O[O.length-1][0],Z=O[O.length-1][1],X=O[0][1];r[D]={hueRange:$,lowerBounds:O,saturationRange:[H,K],brightnessRange:[Z,X]}}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(D){var $=D[0];$===0&&($=1),$===360&&($=359),$=$/360;var O=D[1]/100,H=D[2]/100,K=Math.floor($*6),Z=$*6-K,X=H*(1-O),pe=H*(1-Z*O),me=H*(1-(1-Z)*O),Ce=256,J=256,U=256;switch(K){case 0:Ce=H,J=me,U=X;break;case 1:Ce=pe,J=H,U=X;break;case 2:Ce=X,J=H,U=me;break;case 3:Ce=X,J=pe,U=H;break;case 4:Ce=me,J=X,U=H;break;case 5:Ce=H,J=X,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(J*255),Math.floor(U*255)];return ne}function A(D){D=D.replace(/^#/,""),D=D.length===3?D.replace(/(.)/g,"$1$1"):D;var $=parseInt(D.substr(0,2),16)/255,O=parseInt(D.substr(2,2),16)/255,H=parseInt(D.substr(4,2),16)/255,K=Math.max($,O,H),Z=K-Math.min($,O,H),X=K?Z/K:0;switch(K){case $:return[60*((O-H)/Z%6)||0,X,K];case O:return[60*((H-$)/Z+2)||0,X,K];case H:return[60*(($-O)/Z+4)||0,X,K]}}function I(D){var $=D[0],O=D[1]/100,H=D[2]/100,K=(2-O)*H;return[$,Math.round(O*H/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(D){for(var $=0,O=0;O!==D.length&&!($>=Number.MAX_SAFE_INTEGER);O++)$+=D.charCodeAt(O);return $}function T(D){if(isNaN(D)){if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=A(D)[0];return m(H).hueRange}}}else{var $=parseInt(D);if($<360&&$>0)return m(D).hueRange}return[0,360]}return o})})(vy,vy.exports);var RVe=vy.exports;const FVe=fh(RVe),Tx=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 LVe{constructor(t){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:o,seed:a}=t;this.dictionaries=i,this.separator=r,this.length=n,this.style=o,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries. Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let t=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let i;t?(i=(a=>{if(typeof a=="string"){const s=a.split("").map(d=>d.charCodeAt(0)).reduce((d,f)=>d+f,1),u=Math.floor(Number(s));return Tx(u)}return Tx(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 Px={separator:"_",dictionaries:[]},OVe=e=>{const t=[...e&&e.dictionaries||Px.dictionaries],n={...Px,...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 LVe(n).generate()};var _Ve=["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"],sm={exports:{}};/** * @license * Lodash diff --git a/examples/react-tldraw/index.html b/examples/react-tldraw/index.html index 7a2021180..ee1804844 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-0iJGe1Ls.js b/examples/react-todomvc/assets/index-DIeJWN1h.js similarity index 99% rename from examples/react-todomvc/assets/index-0iJGe1Ls.js rename to examples/react-todomvc/assets/index-DIeJWN1h.js index fb8d17cf4..19bd8bb24 100644 --- a/examples/react-todomvc/assets/index-0iJGe1Ls.js +++ b/examples/react-todomvc/assets/index-DIeJWN1h.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 V(t,e,n){this.low=t|0,this.high=e|0,this.unsigned=!!n}V.prototype.__isLong__;Object.defineProperty(V.prototype,"__isLong__",{value:!0});function Re(t){return(t&&t.__isLong__)===!0}function qh(t){var e=Math.clz32(t&-t);return t?31-e:e}V.isLong=Re;var Vh={},Kh={};function xi(t,e){var n,r,i;return e?(t>>>=0,(i=0<=t&&t<256)&&(r=Kh[t],r)?r:(n=W(t,0,!0),i&&(Kh[t]=n),n)):(t|=0,(i=-128<=t&&t<128)&&(r=Vh[t],r)?r:(n=W(t,t<0?-1:0,!1),i&&(Vh[t]=n),n))}V.fromInt=xi;function wt(t,e){if(isNaN(t))return e?fr:Dt;if(e){if(t<0)return fr;if(t>=_p)return Qp}else{if(t<=-Hh)return je;if(t+1>=Hh)return Yp}return t<0?wt(-t,e).neg():W(t%cs|0,t/cs|0,e)}V.fromNumber=wt;function W(t,e,n){return new V(t,e,n)}V.fromBits=W;var fl=Math.pow;function Kf(t,e,n){if(t.length===0)throw Error("empty string");if(typeof e=="number"?(n=e,e=!1):e=!!e,t==="NaN"||t==="Infinity"||t==="+Infinity"||t==="-Infinity")return e?fr:Dt;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return Kf(t.substring(1),e,n).neg();for(var i=wt(fl(n,8)),s=Dt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*cs+(this.low>>>0):this.high*cs+(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(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,n=31;n>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 Re(e)||(e=Jt(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(Re(e)||(e=Jt(e)),this.eq(e))return 0;var n=this.isNegative(),r=e.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(qi)};C.neg=C.negate;C.add=function(e){Re(e)||(e=Jt(e));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=n+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=Jt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=Jt(e)),vt){var n=vt.mul(this.low,this.high,e.low,e.high);return W(n,vt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?fr:Dt;if(this.eq(je))return e.isOdd()?je:Dt;if(e.eq(je))return this.isOdd()?je:Dt;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(_h)&&e.lt(_h))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,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=Jt(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 n=(this.unsigned?vt.div_u:vt.div_s)(this.low,this.high,e.low,e.high);return W(n,vt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?fr:Dt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return fr;if(e.gt(this.shru(1)))return Gp;s=fr}else{if(this.eq(je)){if(e.eq(qi)||e.eq($c))return je;if(e.eq(je))return qi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Dt)?e.isNegative()?qi:$c:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?fr:Dt;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=Dt}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:fl(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=qi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=Jt(e)),vt){var n=(this.unsigned?vt.rem_u:vt.rem_s)(this.low,this.high,e.low,e.high);return W(n,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 W(~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?qh(this.low):qh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=Jt(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=Jt(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=Jt(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var n;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(n=32-e,W(this.low<>>n,this.high<>>n,this.unsigned)):(e-=32,n=32-e,W(this.high<>>n,this.low<>>n,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var n;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(n=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,n=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,n=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};V.fromBytes=function(e,n,r){return r?V.fromBytesLE(e,n):V.fromBytesBE(e,n)};V.fromBytesLE=function(e,n){return new V(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,n)};V.fromBytesBE=function(e,n){return new V(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],n)};var ye=(t=>(t[t.Null=0]="Null",t[t.Boolean=1]="Boolean",t[t.Integer=2]="Integer",t[t.Long=3]="Long",t[t.Double=4]="Double",t[t.String=5]="String",t[t.Bytes=6]="Bytes",t[t.Date=7]="Date",t))(ye||{});class ie extends xo{constructor(n,r){super(r);u(this,"valueType");u(this,"value");this.valueType=ie.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new ie(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return V.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(V.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Zt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=ie.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 V)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return ie.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=V.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class dl extends Hp{constructor(n){super(n);u(this,"prev");u(this,"next");this.value=n}static createAfter(n,r){const i=new dl(r),s=n.next;return n.next=i,i.prev=n,i.next=s,s&&(s.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class yo{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=ie.of(0,Bt);e.setRemovedAt(Bt),this.dummyHead=new dl(e),this.last=this.dummyHead,this.nodeMapByIndex=new po,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new yo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,n){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(n);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=dl.createAfter(i,n);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,n,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(n.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const n=this.nodeMapByCreatedAt.get(e.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(e){const n=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!n)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(e){if(e>=this.length)return;const[n,r]=this.nodeMapByIndex.find(e);let i=n;if(e===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let n=this.nodeMapByCreatedAt.get(e.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(e,n){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,n){const r=this.getByIndex(e);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Kr{constructor(n,r){super(n);u(this,"elements");this.elements=r}static create(n,r){if(!r)return new tt(n,yo.create());const i=yo.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof Kr&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:Qi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(n,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):Bt:Vs;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Qi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:Qi(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new At(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 No extends Mt{constructor(n,r,i,s,o,a,l){super(n,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(n,r,i,s,o,a,l){return new No(n,r,i,s,o,a,l)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof At))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${n}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Po extends Mt{constructor(n,r,i,s,o,a){super(n,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(n,r,i,s,o,a){return new Po(n,r,i,s,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof At))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)n.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const b1=2,F1="root",hr="text";function Ns(t,e){let n=0;const r=t.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const n=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*n,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===hr}get paddedSize(){return this.size+(this.isText?0:b1)}isAncestorOf(e){return J1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e+1];if(n)return n}get prevSibling(){const e=this.parent.findOffset(this),n=this.parent.children[e-1];if(n)return n}splitText(e,n){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+n);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const n of e)n.parent=this,n.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const n of e)n.parent=this}insertBefore(e,n){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,n){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,n){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,n),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(n,1),e.parent=void 0}splitElement(e,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,n){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,n){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(n,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const n=this._children.indexOf(e);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let n=e;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function J1(t,e){if(t===e)return!1;for(;e.parent;){if(e.parent===t)return!0;e=e.parent}return!1}var he=(t=>(t.Start="Start",t.End="End",t.Text="Text",t))(he||{});function Xp(t,e,n,r){if(e>n)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${n}`);if(e>t.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${t.size}`);if(n>t.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${n} > ${t.size}`);if(e===n)return;let i=0;for(const s of t.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),Xp(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function Zp(t,e,n=0){for(const r of t.children)Zp(r,e,n+1);e(t,n)}function Ll(t,e,n=0){for(const r of t._children)Ll(r,e,n+1);e(t,n)}function zc(t,e,n=!0){if(e>t.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${t.size}`);if(t.isText)return{node:t,offset:e};let r=0,i=0;for(const s of t.children){if(n&&s.isText&&s.size>=e-i)return zc(s,e-i,n);if(e===i)return{node:t,offset:r};if(!n&&s.paddedSize===e-i)return{node:t,offset:r+1};if(s.paddedSize>e-i)return zc(s,e-i-1,n);i+=s.paddedSize,r+=1}return{node:t,offset:r}}function ey(t){return t.isText||t.children.length===0?t:ey(t.children[0])}function $1(t,e){if(t.sizet===e?0:t0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,s=n;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,n){for(;n;){const r=this.comparator(e,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(e,n,r){if(!r)return this.counter+=1,new j1(e,n,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,n,r.left):i>0?r.right=this.putInternal(e,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,n){if(this.comparator(n,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,n);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(n,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(n,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,n)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const n=e.right;return e.right=n.left,n.left=e,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(e){const n=e.left;return e.left=n.right,n.right=e,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Ot{constructor(e,n){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=n}static of(e,n){return new Ot(e,n)}static fromTreePos(e){const{offset:n}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Ot.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(e){return Ot.of(Ee.of(et.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(et.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const n=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(n);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,n){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new Ee(e,n)}static fromStruct(e){return Ee.of(et.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=n,s}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Xe(Ee.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Xe(Ee.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=n.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,n.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new Sr);const i=new Array;for(const[s,o]of Object.entries(n))i.push(this.attrs.set(s,o,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function Uc(t){var n;if(t.isText){const r=t;return{type:r.type,value:r.value}}const e={type:t.type,children:t.children.map(Uc)};return t.attrs&&(e.attributes=Qi((n=t.attrs)==null?void 0:n.toObject())),e}function Wf(t){if(t.isText)return t.value;let e="";return t.attrs&&t.attrs.size()&&(e=" "+Array.from(t.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Zt(n.getValue())}"`}).join(" ")),`<${t.type}${e}>${t.children.map(n=>Wf(n)).join("")}`}function ny(t){if(t.isText){const e=t;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:t.type,children:t.children.map(ny),size:t.size,isRemoved:t.isRemoved}}class It extends xo{constructor(n,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new z1(n),this.nodeMapByID=new ty(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new It(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,s]=n.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,n.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Bt:Vs;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(n,r,i,s){const[o,a]=this.findNodesAndSplitText(n[0],i),[l,c]=this.findNodesAndSplitText(n[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):Bt:Vs;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Sr);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(n,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(n[0],s),[d,h]=this.findNodesAndSplitText(n[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===he.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):Bt:Vs;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===he.Text||x===he.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>Uc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(n,r,i,s,o){const a=this.findPos(n[0]),l=this.findPos(n[1]);this.edit([a,l],r,i,s,o)}move(n,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var s;(s=n.parent)==null||s.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Ot.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 Wf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;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=Ot.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Qi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===he.Start){const l=n.allChildren;return l.length>0?[l[0],l[0].isText?he.Text:he.Start]:[n,he.End]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===s.length-1)return[i,he.End];const a=s[o+1];return[a,a.isText?he.Text:he.Start]}findLeftToken([n,r]){if(r===he.End){const l=n.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?he.Text:he.End]}return[n,he.Start]}const i=n.parent,s=i.allChildren,o=s.indexOf(n);if(i&&o===0)return[i,he.Start];const a=s[o-1];return[a,a.isText?he.Text:he.End]}}class Do extends Mt{constructor(n,r,i,s,o,a,l){super(n,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(n,r,i,s,o,a,l){return new Do(n,r,i,s,o,a,l)}execute(n){var l;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>et.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)n.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,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()}`,s=this.contents||[];return`${n}.EDIT(${r},${i},${s.map(o=>Wf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Or{constructor(e,n,r,i){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=n,this.actor=r}static of(e,n,r,i){return new Or(e,n,r,i)}next(){return new Or(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new Or(this.clientSeq,e,this.actor):new Or(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return et.of(this.lamport,e,this.actor)}setActor(e){return new Or(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const V1=new Or(0,0n,qf);class fs{constructor({id:e,operations:n,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:e,operations:n,presenceChange:r,message:i}){return new fs({id:e,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const n of this.operations)n.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,n,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Yr.Put?n.set(this.id.getActorID(),Ct(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:ve.bytesToHex(ve.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ve.bytesToHex(ve.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:n,operations:r,presenceChange:i,message:s}=e;return fs.create({id:ve.bytesToChangeID(ve.hexToBytes(n)),operations:r==null?void 0:r.map(o=>ve.bytesToOperation(ve.hexToBytes(o))),presenceChange:i,message:s})}}class Bl{constructor(e,n,r,i,s,o){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,n,r,i,s,o){return new Bl(e,n,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Xi{constructor(e,n){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=n}static of(e,n){return new Xi(e,n)}increaseClientSeq(e){return e===0?this:new Xi(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const n=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return Xi.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const K1=new Xi(0n,0);class nn{constructor(e,n){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=n}static of(e,n){return new nn(e,n)}static fromStruct(e){return nn.of(et.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new nn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const W1=nn.of(Bt,0);class bt{constructor(e,n){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=n}static of(e,n){return new bt(e,n)}static fromStruct(e){const n=nn.fromStruct(e.id);return bt.of(n,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return nn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Wr extends Hp{constructor(n,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new Wr(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==e.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(e){const n=this.treeByID.floorEntry(e);if(n&&!(!n.key.equals(e)&&!n.key.hasSameCreatedAt(e)))return n.value}findBetween(e,n){const r=[];let i=e;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(e,n){if(n>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return e;if(n===e.getContentLength())return e.getNext();const r=e.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,n,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,n,r),o=new Map,a=new Map,l=this.makeChanges(s,n);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(n)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,n,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):Bt:Vs;c.canDelete(n,h)?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,n){const r=[];let i,s;for(let o=0;ot<0?Math.ceil(t):Math.floor(t);var rn=(t=>(t[t.IntegerCnt=0]="IntegerCnt",t[t.LongCnt=1]="LongCnt",t))(rn||{});class nt extends xo{constructor(n,r,i){super(i);u(this,"valueType");u(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=V.fromNumber(r).toInt():this.value=Gh(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=V.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new nt(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return V.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=nt.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof V?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!nt.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.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()===ye.Long?this.value=this.value+n.getValue().toInt():this.value=V.fromNumber(this.value+Gh(n.getValue())).toInt(),this}}class hs extends Mt{constructor(n,r,i){super(n,i);u(this,"value");this.value=r}static create(n,r,i){return new hs(n,r,i)}execute(n){const r=n.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:n.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===ye.Long?n.getValue().multiply(-1):n.getValue()*-1;return hs.create(this.getParentCreatedAt(),ie.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class gr extends Mt{constructor(n,r,i,s,o,a,l){super(n,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(n,r,i,s,o,a){return new gr(n,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(n,r,i,s,o,a){return new gr(n,r,i,s,new Map,o,a)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)n.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function H1(t){const e=new jf,n=e.data;for(const[r,i]of Object.entries(t))n[r]=JSON.stringify(i);return e}function _1(t){if(t.type===Yr.Put)return new go({type:Ti.PUT,presence:H1(t.presence)});if(t.type===Yr.Clear)return new go({type:Ti.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function G1(t){return new Vp({serverSeq:t.getServerSeq(),clientSeq:t.getClientSeq()})}function ry(t){return new Rl({clientSeq:t.getClientSeq(),lamport:t.getLamport(),actorId:Zf(t.getActorID())})}function F(t){if(t)return new b({lamport:t.getLamport(),delimiter:t.getDelimiter(),actorId:Zf(t.getActorID())})}function iy(t){switch(t){case ye.Null:return $.NULL;case ye.Boolean:return $.BOOLEAN;case ye.Integer:return $.INTEGER;case ye.Long:return $.LONG;case ye.Double:return $.DOUBLE;case ye.String:return $.STRING;case ye.Bytes:return $.BYTES;case ye.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${t}`)}}function sy(t){switch(t){case rn.IntegerCnt:return $.INTEGER_CNT;case rn.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${t}`)}}function vu(t){if(t instanceof We)return new lt({type:$.JSON_OBJECT,createdAt:F(t.getCreatedAt()),value:vy(t)});if(t instanceof tt)return new lt({type:$.JSON_ARRAY,createdAt:F(t.getCreatedAt()),value:IS(t)});if(t instanceof At)return new lt({type:$.TEXT,createdAt:F(t.getCreatedAt())});if(t instanceof ie)return new lt({type:iy(t.getType()),createdAt:F(t.getCreatedAt()),value:t.toBytes()});if(t instanceof nt)return new lt({type:sy(t.getType()),createdAt:F(t.getCreatedAt()),value:t.toBytes()});if(t instanceof It)return new lt({type:$.TREE,createdAt:F(t.getCreatedAt()),value:xS(t)});throw new k(S.ErrUnimplemented,"unimplemented element")}function Y1(t){return new fo({createdAt:F(t.getCreatedAt()),offset:t.getOffset()})}function Qo(t){return new wr({createdAt:F(t.getID().getCreatedAt()),offset:t.getID().getOffset(),relativeOffset:t.getRelativeOffset()})}function Xo(t){return new ki({parentId:Ks(t.getParentID()),leftSiblingId:Ks(t.getLeftSiblingID())})}function Ks(t){return new Vr({createdAt:F(t.getCreatedAt()),offset:t.getOffset()})}function oy(t){const e=new Uf;if(t instanceof Ai){const n=t,r=new Ha;r.parentCreatedAt=F(n.getParentCreatedAt()),r.key=n.getKey(),r.value=vu(n.getValue()),r.executedAt=F(n.getExecutedAt()),e.body.case="set",e.body.value=r}else if(t instanceof Co){const n=t,r=new _a;r.parentCreatedAt=F(n.getParentCreatedAt()),r.prevCreatedAt=F(n.getPrevCreatedAt()),r.value=vu(n.getValue()),r.executedAt=F(n.getExecutedAt()),e.body.case="add",e.body.value=r}else if(t instanceof Br){const n=t,r=new Ga;r.parentCreatedAt=F(n.getParentCreatedAt()),r.prevCreatedAt=F(n.getPrevCreatedAt()),r.createdAt=F(n.getCreatedAt()),r.executedAt=F(n.getExecutedAt()),e.body.case="move",e.body.value=r}else if(t instanceof Qr){const n=t,r=new Ya;r.parentCreatedAt=F(n.getParentCreatedAt()),r.createdAt=F(n.getCreatedAt()),r.executedAt=F(n.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(t instanceof No){const n=t,r=new Qa;r.parentCreatedAt=F(n.getParentCreatedAt()),r.from=Qo(n.getFromPos()),r.to=Qo(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=n.getContent();const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=F(n.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(t instanceof Po){const n=t,r=new Xa;r.parentCreatedAt=F(n.getParentCreatedAt()),r.from=Qo(n.getFromPos()),r.to=Qo(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of n.getAttributes())s[o]=a;r.executedAt=F(n.getExecutedAt()),e.body.case="style",e.body.value=r}else if(t instanceof hs){const n=t,r=new Za;r.parentCreatedAt=F(n.getParentCreatedAt()),r.value=vu(n.getValue()),r.executedAt=F(n.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(t instanceof Do){const n=t,r=new el,i=r.createdAtMapByActor;for(const[s,o]of n.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(n.getParentCreatedAt()),r.from=Xo(n.getFromPos()),r.to=Xo(n.getToPos()),r.contents=rS(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=F(n.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(t instanceof gr){const n=t,r=new tl;r.parentCreatedAt=F(n.getParentCreatedAt()),r.from=Xo(n.getFromPos()),r.to=Xo(n.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=F(a);const s=n.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of n.getAttributes())o[a]=l}r.executedAt=F(n.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function Q1(t){const e=[];for(const n of t)e.push(oy(n));return e}function X1(t){const e=new jp({id:ry(t.getID()),message:t.getMessage()});return t.hasOperations()&&(e.operations=Q1(t.getOperations())),t.hasPresenceChange()&&(e.presenceChange=_1(t.getPresenceChange())),e}function Z1(t){const e=[];for(const n of t)e.push(X1(n));return e}function eS(t){const e=[];for(const n of t)e.push(new qp({key:n.getStrKey(),element:_f(n.getValue())}));return e}function tS(t){const e=[];for(const n of t)e.push(new ll({element:_f(n.getValue())}));return e}function nS(t){const e=[];for(const n of t){const r=new ul;r.id=Y1(n.getID()),r.value=n.getValue().getContent(),r.removedAt=F(n.getRemovedAt());const i=r.attributes,s=n.getValue().getAttrs();for(const o of s){const a=new ls;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function rS(t){const e=[];if(!t||!t.length)return e;for(const n of t)e.push(new cl({content:Hf(n)}));return e}function iS(t){const e={};for(const n of t)e[n.getKey()]=new ls({value:n.getValue(),updatedAt:F(n.getUpdatedAt()),isRemoved:n.isRemoved()});return e}function Hf(t){if(!t)return[];const e=[];return Ll(t,(n,r)=>{const i=new ho({id:Ks(n.id),type:n.type,removedAt:F(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=Ks(n.insPrevID)),n.insNextID&&(i.insNextId=Ks(n.insNextID)),n.attrs&&(i.attributes=iS(n.attrs)),e.push(i)}),e}function sS(t){const e=new He;return e.body.case="jsonObject",e.body.value=new nl({nodes:eS(t.getRHT()),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function ay(t){const e=new He;return e.body.case="jsonArray",e.body.value=new rl({nodes:tS(t.getElements()),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function oS(t){const e=new He;return e.body.case="primitive",e.body.value=new il({type:iy(t.getType()),value:t.toBytes(),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function aS(t){const e=new He;return e.body.case="text",e.body.value=new sl({nodes:nS(t.getRGATreeSplit()),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function lS(t){const e=new He;return e.body.case="counter",e.body.value=new ol({type:sy(t.getType()),value:t.toBytes(),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function ly(t){const e=new He;return e.body.case="tree",e.body.value=new al({nodes:Hf(t.getRoot()),createdAt:F(t.getCreatedAt()),movedAt:F(t.getMovedAt()),removedAt:F(t.getRemovedAt())}),e}function _f(t){if(t instanceof We)return sS(t);if(t instanceof tt)return ay(t);if(t instanceof ie)return oS(t);if(t instanceof At)return aS(t);if(t instanceof nt)return lS(t);if(t instanceof It)return ly(t);throw new k(S.ErrUnimplemented,"unimplemented element")}function uS(t){return new Tr({documentKey:t.getDocumentKey(),checkpoint:G1(t.getCheckpoint()),isRemoved:t.getIsRemoved(),changes:Z1(t.getChanges()),snapshot:t.getSnapshot(),minSyncedTicket:F(t.getMinSyncedTicket())})}function Yh(t){const e=t.findDetails(x1);for(const n of e)if(n.metadata.code)return n.metadata.code;return""}function uy(t){return Or.of(t.clientSeq,BigInt(t.lamport),Xf(t.actorId),BigInt(t.serverSeq))}function M(t){if(t)return et.of(BigInt(t.lamport),t.delimiter,Xf(t.actorId))}function Gf(t){const e={};return Object.entries(t.data).forEach(([n,r])=>{e[n]=JSON.parse(r)}),e}function cS(t){const e=t.type;if(e===Ti.PUT){const n=Gf(t.presence);return{type:Yr.Put,presence:n}}if(e===Ti.CLEAR)return{type:Yr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function fS(t){const e=new Map;return Object.entries(t).forEach(([n,r])=>{e.set(n,Gf(r))}),e}function cy(t){switch(t){case $.NULL:return ye.Null;case $.BOOLEAN:return ye.Boolean;case $.INTEGER:return ye.Integer;case $.LONG:return ye.Long;case $.DOUBLE:return ye.Double;case $.STRING:return ye.String;case $.BYTES:return ye.Bytes;case $.DATE:return ye.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${t}`)}function hl(t){switch(t){case $.INTEGER_CNT:return rn.IntegerCnt;case $.LONG_CNT:return rn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${t}`)}function wu(t){switch(t.type){case $.JSON_OBJECT:return t.value?yy(t.value):We.create(M(t.createdAt));case $.JSON_ARRAY:return t.value?AS(t.value):tt.create(M(t.createdAt));case $.TEXT:return At.create(ds.create(),M(t.createdAt));case $.TREE:return ES(t.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return ie.of(ie.valueFromBytes(cy(t.type),t.value),M(t.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return nt.create(hl(t.type),nt.valueFromBytes(hl(t.type),t.value),M(t.createdAt))}}function Zo(t){return bt.of(nn.of(M(t.createdAt),t.offset),t.relativeOffset)}function fy(t){return nn.of(M(t.createdAt),t.offset)}function dS(t){const e=vo.create(t.value);Object.entries(t.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const n=Wr.create(fy(t.id),e);return n.remove(M(t.removedAt)),n}function Pi(t){return Ot.of(Ws(t.parentId),Ws(t.leftSiblingId))}function Ws(t){return Ee.of(M(t.createdAt),t.offset)}function hS(t){if(!t.length)return;const e=[];return t.forEach(n=>{const r=Yf(n.content);e.push(r)}),e}function Yf(t){if(t.length===0)return;const e=[];for(const i of t)e.push(mS(i));const n=e[e.length-1],r=new Map;r.set(t[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(t[i].depth-1).prepend(e[i]),r.set(t[i].depth,e[i]);return n.updateDescendantsSize(),It.create(n,Bt).getRoot()}function gS(t){const e=Sr.create();for(const[n,r]of Object.entries(t))e.setInternal(n,r.value,M(r.updatedAt),r.isRemoved);return e}function mS(t){const e=Ws(t.id),n=Xe.create(e,t.type),r=Object.entries(t.attributes);return n.isText?n.value=t.value:r.length&&(n.attrs=gS(t.attributes)),t.insPrevId&&(n.insPrevID=Ws(t.insPrevId)),t.insNextId&&(n.insNextID=Ws(t.insNextId)),n.removedAt=M(t.removedAt),n}function dy(t){if(t.body.case==="set"){const e=t.body.value;return Ai.create(e.key,wu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(t.body.case==="add"){const e=t.body.value;return Co.create(M(e.parentCreatedAt),M(e.prevCreatedAt),wu(e.value),M(e.executedAt))}else if(t.body.case==="move"){const e=t.body.value;return Br.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(t.body.case==="remove"){const e=t.body.value;return Qr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(t.body.case==="edit"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),No.create(M(e.parentCreatedAt),Zo(e.from),Zo(e.to),n,e.content,r,M(e.executedAt))}else if(t.body.case==="style"){const e=t.body.value,n=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{n.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Po.create(M(e.parentCreatedAt),Zo(e.from),Zo(e.to),n,r,M(e.executedAt))}else{if(t.body.case==="select")return;if(t.body.case==="increase"){const e=t.body.value;return hs.create(M(e.parentCreatedAt),wu(e.value),M(e.executedAt))}else if(t.body.case==="treeEdit"){const e=t.body.value,n=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{n.set(r,M(i))}),Do.create(M(e.parentCreatedAt),Pi(e.from),Pi(e.to),hS(e.contents),e.splitLevel,n,M(e.executedAt))}else if(t.body.case==="treeStyle"){const e=t.body.value,n=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?gr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Pi(e.from),Pi(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{n.set(s,o)}),gr.create(M(e.parentCreatedAt),Pi(e.from),Pi(e.to),i,n,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function pS(t){const e=[];for(const n of t){const r=dy(n);r&&e.push(r)}return e}function hy(t){const e=[];for(const n of t)e.push(fs.create({id:uy(n.id),operations:pS(n.operations),presenceChange:n.presenceChange?cS(n.presenceChange):void 0,message:n.message}));return e}function yS(t){return Xi.of(BigInt(t.serverSeq),t.clientSeq)}function vS(t){return Bl.create(t.documentKey,yS(t.checkpoint),t.isRemoved,hy(t.changes),t.snapshot,M(t.minSyncedTicket))}function gy(t){const e=new mo;for(const r of t.nodes){const i=Qf(r.element);e.set(r.key,i,i.getPositionedAt())}const n=new We(M(t.createdAt),e);return n.setMovedAt(M(t.movedAt)),n.setRemovedAt(M(t.removedAt)),n}function my(t){const e=new yo;for(const r of t.nodes)e.insert(Qf(r.element));const n=new tt(M(t.createdAt),e);return n.setMovedAt(M(t.movedAt)),n.setRemovedAt(M(t.removedAt)),n}function wS(t){const e=ie.of(ie.valueFromBytes(cy(t.type),t.value),M(t.createdAt));return e.setMovedAt(M(t.movedAt)),e.setRemovedAt(M(t.removedAt)),e}function SS(t){const e=new ds;let n=e.getHead();for(const i of t.nodes){const s=e.insertAfter(n,dS(i));i.insPrevId&&s.setInsPrev(e.findNode(fy(i.insPrevId))),n=s}const r=new At(e,M(t.createdAt));return r.setMovedAt(M(t.movedAt)),r.setRemovedAt(M(t.removedAt)),r}function kS(t){const e=nt.create(hl(t.type),nt.valueFromBytes(hl(t.type),t.value),M(t.createdAt));return e.setMovedAt(M(t.movedAt)),e.setRemovedAt(M(t.removedAt)),e}function py(t){const e=Yf(t.nodes);return It.create(e,M(t.createdAt))}function Qf(t){if(t.body.case==="jsonObject")return gy(t.body.value);if(t.body.case==="jsonArray")return my(t.body.value);if(t.body.case==="primitive")return wS(t.body.value);if(t.body.case==="text")return SS(t.body.value);if(t.body.case==="counter")return kS(t.body.value);if(t.body.case==="tree")return py(t.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function TS(t){if(!t)return{root:We.create(Bt),presences:new Map};const e=pc.fromBinary(t);return{root:Qf(e.root),presences:fS(e.presences)}}function yy(t){if(!t)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(t);return gy(e.body.value)}function vy(t){return _f(t).toBinary()}function AS(t){if(!t)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(t);return my(e.body.value)}function IS(t){return ay(t).toBinary()}function ES(t){if(!t)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(t);return py(e.body.value)}function xS(t){return ly(t).toBinary()}function wy(t){return t?Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function Xf(t){return wy(t)}function Sy(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Zf(t){return Sy(t)}function CS(t){const e=Rl.fromBinary(t);return uy(e)}function NS(t){const e=Uf.fromBinary(t);return dy(e)}const ve={fromPresence:Gf,toChangePack:uS,fromChangePack:vS,fromChanges:hy,toTreeNodes:Hf,fromTreeNodes:Yf,objectToBytes:vy,bytesToObject:yy,bytesToSnapshot:TS,bytesToHex:wy,hexToBytes:Sy,toHexString:Xf,toUint8Array:Zf,toOperation:oy,toChangeID:ry,PbChangeID:Rl,bytesToChangeID:CS,bytesToOperation:NS};var be=(t=>(t[t.Trivial=0]="Trivial",t[t.Debug=1]="Debug",t[t.Info=2]="Info",t[t.Warn=3]="Warn",t[t.Error=4]="Error",t[t.Fatal=5]="Fatal",t))(be||{});let si=3;function ky(t){si=t}const J={trivial:(...t)=>{si>0||typeof console<"u"&&console.log("YORKIE T:",...t)},debug:(...t)=>{si>1||typeof console<"u"&&console.log("YORKIE D:",...t)},info:(...t)=>{si>2||typeof console<"u"&&console.log("YORKIE I:",...t)},warn:(...t)=>{si>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:(...t)=>{si>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:(...t)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...t):console.log("YORKIE F:",...t))},isEnabled:t=>si<=t};function Ty(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class PS{constructor(e,n,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=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Sa.RealtimeSyncOff?!1:this.syncMode===Sa.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Sa.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Su=()=>{};class DS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(n){this.error(n)}}next(e){this.forEachObserver(n=>{n.next(e)})}error(e){this.forEachObserver(n=>{n.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,n,r){let i;if(!e)throw new 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:n,complete:r},i.next===void 0&&(i.next=Su),i.error===void 0&&(i.error=Su),i.complete===void 0&&(i.complete=Su);const s=Ty(),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 n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let n=0;ne}}class Vi{constructor(e,n,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=Wp,this.root=n,this.operations=[],this.previousPresence=Ct(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,n,r,i){return new Vi(e,n,r,i)}push(e){this.operations.push(e)}registerElement(e,n){this.root.registerElement(e,n)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return fs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,n){for(const r of Object.keys(e))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const n of this.reversePresenceKeys)e[n]=this.previousPresence[n];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class wo{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(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof At||n instanceof It)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new wo(We.create(Bt))}findByCreatedAt(e){const n=this.elementPairMapByCreatedAt.get(e.toIDString());if(n)return n.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let n=this.elementPairMapByCreatedAt.get(e.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),s=n.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,n){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:n,element:e}),e instanceof Kr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let n=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),n++};return r(e),e instanceof Kr&&e.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const n of this.gcElementSetByCreatedAt){e.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof Kr&&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 wo(this.rootObject.deepcopy())}garbageCollect(e){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Ay(t,e){const n=new So(t);return new Proxy(e,n.getHandlers())}class So{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(n,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),So.setInternal(e,n,r,i),!0),get:(n,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():oi(e,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),So.deleteInternal(e,n,r),!0)}}static setInternal(e,n,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=gl(e,i,s),a=n.set(r,o,s);e.registerElement(o,n),a&&e.registerRemovedElement(a),e.push(Ai.create(r,o.deepcopy(),n.getCreatedAt(),s))}static buildObjectMembers(e,n){const r={};for(const[i,s]of Object.entries(n)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=gl(e,s,o);r[i]=a}return r}static deleteInternal(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByKey(r,i);s&&(e.push(Qr.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function RS(t,e){const n=new ae(t,e);return new Proxy(e,n.getHandlers())}function LS(t){return typeof t=="string"||t instanceof String?!isNaN(t):!1}function BS(t){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(t)}class ae{constructor(e,n){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=n,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Er(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Er(e,a)}:i==="getLast"?()=>Er(e,r.getLast()):i==="deleteByID"?o=>{const a=ae.deleteInternalByID(e,r,o);return Er(e,a)}:i==="insertAfter"?(o,a)=>{const l=ae.insertAfterInternal(e,r,o,a);return Er(e,l)}:i==="insertBefore"?(o,a)=>{const l=ae.insertBeforeInternal(e,r,o,a);return Er(e,l)}: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)}:LS(i)?oi(e,r.get(Number(i))):i==="push"?o=>ae.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ae.splice(e,r,o,a,...l):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"&&BS(i)?(...o)=>{const a=Array.from(r).map(l=>oi(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),ae.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,n){for(const r of n)yield Er(e,r)}static buildArrayElements(e,n){const r=[];for(const i of n){const s=e.issueTimeTicket(),o=gl(e,i,s);r.push(o)}return r}static pushInternal(e,n,r){return ae.insertAfterInternal(e,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(e,n,r,i){const s=e.issueTimeTicket(),o=n.getPrevCreatedAt(r);n.moveAfter(o,i,s),e.push(Br.create(n.getCreatedAt(),o,i,s))}static moveAfterInternal(e,n,r,i){const s=e.issueTimeTicket();n.moveAfter(r,i,s),e.push(Br.create(n.getCreatedAt(),r,i,s))}static moveFrontInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getHead();n.moveAfter(s.getCreatedAt(),r,i),e.push(Br.create(n.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,n,r){const i=e.issueTimeTicket(),s=n.getLastCreatedAt();n.moveAfter(s,r,i),e.push(Br.create(n.getCreatedAt(),s,r,i))}static insertAfterInternal(e,n,r,i){const s=e.issueTimeTicket(),o=gl(e,i,s);return n.insertAfter(r,o),e.registerElement(o,n),e.push(Co.create(n.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,n,r,i){return ae.insertAfterInternal(e,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,n,r){const i=e.issueTimeTicket(),s=n.deleteByIndex(r,i);if(s)return e.push(Qr.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,n,r){const i=e.issueTimeTicket(),s=n.delete(r,i);return e.push(Qr.create(n.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,n,r,i,...s){const o=n.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(ie.isSupport(r))return Array.from(n).map(c=>oi(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(ie.isSupport(r))return Array.from(n).map(c=>oi(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ie.isSupport(r))return Array.from(n).map(c=>oi(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=n.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class bl{constructor(e,n){u(this,"context");u(this,"text");this.context=e,this.text=n}initialize(e,n){this.context=e,this.text=n}getID(){return this.text.getID()}edit(e,n,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,n);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${n}->${s[1].toTestString()} c:${r}`);const o=i?us(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 No(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,n){return this.edit(e,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,n,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,n);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=us(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 Po(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 n=this.text.indexRangeToPosRange(e[0],e[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([bt.fromStruct(e[0]),bt.fromStruct(e[1])]);return[n[0],n[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,n){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,n)}}class Fl{constructor(e,n){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=n}initialize(e,n){this.valueType=n.getValueType(),this.context=e,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=ie.of(e,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(hs.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ed(t,e,n){const{type:r}=t,i=n.issueTimeTicket();if(r===hr){Iy(t);const{value:s}=t,o=Xe.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=t,{attributes:o}=t;let a;if(typeof o=="object"&&!Kp(o)){const c=us(o);a=new Sr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Xe.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)ed(c,l,n)}}function bS(t,e){const{type:n}=e,r=t.issueTimeTicket();let i;if(e.type===hr){const{value:s}=e;i=Xe.create(Ee.of(r,0),n,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Kp(o)){const l=us(o);a=new Sr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Xe.create(Ee.of(t.issueTimeTicket(),0),n,void 0,a);for(const l of s)ed(l,i,t)}return i}function Iy(t){if(!t.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function Qh(t){if(!t.length)return!0;if(t[0].type===hr)for(const n of t){const{type:r}=n;if(r!==hr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Iy(n)}else for(const n of t){const{type:r}=n;if(r===hr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Ml{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,n){this.context=e,this.tree=n}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ee.of(e.issueTimeTicket(),0),F1);const n=Xe.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ed(r,n,e);return n}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,n){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=n?us(n):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(gr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,n,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),a=r?us(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(gr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,n,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(n),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(gr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,n,r,i=0){var c;if(r.length!==0&&r[0]&&(Qh(r),r[0].type!==hr))for(const d of r){const{children:h=[]}=d;Qh(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===hr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Xe.create(Ee.of(this.context.issueTimeTicket(),0),hr,d))}else o=r.map(d=>d&&bS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,n],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(Do.create(this.tree.getCreatedAt(),e,n,o.length?o:void 0,i,l,s)),!0}editByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,n,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==n.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!n.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(n);return this.editInternal(s,o,r,i)}edit(e,n,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,n,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>n)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(n);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new 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 n=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new 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 n=[Ot.fromStruct(e[0]),Ot.fromStruct(e[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const n=[Ot.fromStruct(e[0]),Ot.fromStruct(e[1])];return this.tree.posRangeToPathRange(n)}}function Xh(t,e){return Ay(t,e)}function Er(t,e){if(e){if(e instanceof ie)return e;if(e instanceof We)return Ay(t,e);if(e instanceof tt)return RS(t,e);if(e instanceof At)return new bl(t,e);if(e instanceof nt){const n=new Fl(rn.IntegerCnt,0);return n.initialize(t,e),n}else if(e instanceof It){const n=new Ml;return n.initialize(t,e),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function oi(t,e){const n=Er(t,e);return n instanceof ie?n.getValue():n}function gl(t,e,n){let r;if(ie.isSupport(e))r=ie.of(e,n);else if(Array.isArray(e))r=tt.create(n,ae.buildArrayElements(t,e));else if(typeof e=="object")e instanceof bl?(r=At.create(ds.create(),n),e.initialize(t,r)):e instanceof Fl?(r=nt.create(e.getValueType(),e.getValue(),n),e.initialize(t,r)):e instanceof Ml?(r=It.create(e.buildRoot(t),n),e.initialize(t,r)):r=We.create(n,So.buildObjectMembers(t,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const Zh=50;class FS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Zh&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Zh&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const MS="yorkie-devtools-panel",JS="yorkie-devtools-sdk";let Di="disconnected";const eg=new Map,wa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=wa);function ea(t,e){(e!=null&&e.force||Di!=="disconnected")&&window.postMessage({source:JS,...t},"*")}function $S(t){if(!t.isEnableDevtools()||typeof window>"u"||eg.has(t.getKey()))return;wa.set(t.getKey(),[]);const e=t.subscribe("all",n=>{n.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(wa.get(t.getKey()).push(n),Di==="synced"&&ea({msg:"doc::sync::partial",docKey:t.getKey(),event:n}))});eg.set(t.getKey(),[e]),ea({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==MS)return;switch(n.data.msg){case"devtools::connect":if(Di!=="disconnected")break;Di="connected",ea({msg:"doc::available",docKey:t.getKey()}),J.info(`[YD] Devtools connected. Doc: ${t.getKey()}`);break;case"devtools::disconnect":Di="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${t.getKey()}`);break;case"devtools::subscribe":Di="synced",ea({msg:"doc::sync::full",docKey:t.getKey(),events:wa.get(t.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${t.getKey()}`);break}})}var xr=(t=>(t.Detached="detached",t.Attached="attached",t.Removed="removed",t))(xr||{}),$e=(t=>(t.StatusChanged="status-changed",t.ConnectionChanged="connection-changed",t.SyncStatusChanged="sync-status-changed",t.Snapshot="snapshot",t.LocalChange="local-change",t.RemoteChange="remote-change",t.Initialized="initialized",t.Watched="watched",t.Unwatched="unwatched",t.PresenceChanged="presence-changed",t.Broadcast="broadcast",t.LocalBroadcast="local-broadcast",t))($e||{}),jc=(t=>(t.Connected="connected",t.Disconnected="disconnected",t))(jc||{}),qc=(t=>(t.Synced="synced",t.SyncFailed="sync-failed",t))(qc||{});class Ey{constructor(e,n){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=n||{},this.key=e,this.status="detached",this.root=wo.create(),this.changeID=V1,this.checkpoint=K1,this.localChanges=[],this.eventStream=OS(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new FS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},$S(this)}update(e,n){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const s=Xh(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new yu(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.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(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,n,r,i){if(typeof e=="string"){if(typeof n!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=n;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=n;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=n;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=n;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=n;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=n;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=n;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=n;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=n;return this.eventStream.subscribe(a,r,i)}const s=e,o=n;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const 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=n,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,n){if(n===e)return!0;const r=e.split(".");return n.split(".").every((s,o)=>s===r[o])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.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:Ct(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(e.length);return Bl.create(this.key,n,!1,e)}setActor(e){for(const n of this.localChanges)n.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Xh(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,n){const{root:r,presences:i}=ve.bytesToSnapshot(n);this.root=new wo(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{snapshot:this.isEnableDevtools()?ve.bytesToHex(n):void 0,serverSeq:e.toString()}}])}applyChanges(e,n){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,n);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,n){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,n);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Yr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Yr.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,n);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(n===Y.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const n=e.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:n,publisher:r}=e.body.value,i=[];if(n===mi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===mi.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(n===mi.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(qf),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:n,serverSeq:r}=e.value;if(!n)return;this.applySnapshot(BigInt(r),ve.hexToBytes(n));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const n=fs.fromStruct(e.rawChange);this.applyChange(n,e.source)}if(e.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of e.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(e.type==="watched"){const{clientID:n,presence:r}=e.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(e.type==="unwatched"){const{clientID:n}=e.value;this.removeOnlineClient(n),this.presences.delete(n)}if(e.type==="presence-changed"){const{clientID:n,presence:r}=e.value;this.presences.set(n,r)}}applyTransactionEvent(e){for(const n of e)this.applyDocEvent(n)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const n=e.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Ct(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const n=this.presences.get(e);return n?Ct(n):void 0}getPresenceForTest(e){const n=this.presences.get(e);return n?Ct(n):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Ct(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&e.push({clientID:n,presence:Ct(this.presences.get(n))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==e).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new 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 n=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Mt)){new yu(n,Ct(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=n.issueTimeTicket();c.setExecutedAt(d),n.push(c)}const r=n.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=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source: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 n=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Mt)){new yu(n,Ct(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=n.issueTimeTicket();c.setExecutedAt(d),n.push(c)}const r=n.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=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source: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,n,r){const i={type:"local-broadcast",value:{topic:e,payload:n},options:r};this.publish([i])}}function zS(t,e){return n=>async r=>(t&&r.header.set("x-api-key",t),e&&r.header.set("authorization",e),await n(r))}const US="yorkie-js-sdk",jS="0.5.1",qS="Yorkie JS SDK",VS="./src/yorkie.ts",KS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},WS=["dist"],HS={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"},_S={node:">=18.0.0",npm:">=7.1.0"},GS={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},YS={name:"hackerwins",email:"susukang98@gmail.com"},QS="Apache-2.0",XS={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ZS="https://github.com/yorkie-team/yorkie-js-sdk#readme",ek={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},tk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},tg={name:US,version:jS,description:qS,main:VS,publishConfig:KS,files:WS,scripts:HS,engines:_S,repository:GS,author:YS,license:QS,bugs:XS,homepage:ZS,devDependencies:ek,dependencies:tk};function nk(){return t=>async e=>(e.header.set("x-yorkie-user-agent",tg.name+"/"+tg.version),await t(e))}const rk=t=>{try{if(JSON.stringify(t)===void 0)return!1}catch{return!1}return!0};var Sa=(t=>(t.Manual="manual",t.Realtime="realtime",t.RealtimePushOnly="realtime-pushonly",t.RealtimeSyncOff="realtime-syncoff",t))(Sa||{});const ta={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ku={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class xy{constructor(e,n){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);n=n||ta,this.key=n.key?n.key:Ty(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||ta.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||ta.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||ta.retrySyncLoopDelay,this.rpcClient=n1(E1,I1({baseUrl:e,interceptors:[zS(n.apiKey,n.token),nk()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,n={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==xr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(n.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var 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=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ve.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ve.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===xr.Removed||(e.applyStatus(xr.Attached),this.attachmentMap.set(e.getKey(),new PS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,n={}){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:ve.toChangePack(e.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==xr.Removed&&e.applyStatus(xr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,n){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===n?e:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),e):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const n=this.attachmentMap.get(e.getKey());if(!n)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=ve.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,n,r,i){if(!this.isActive())throw new 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(!rk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??ku.maxRetries,a=ku.maxBackoff;let l=0;const c=h=>Math.min(ku.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${n}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(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 n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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 n=this.attachmentMap.get(e);if(!n)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,n.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:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return n.doc.publish([{type:$e.ConnectionChanged,value:jc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(n,c),c.body.case==="initialization"&&o([s,i])}catch(c){n.doc.resetOnlineClients(),n.doc.publish([{type:$e.Initialized,source:Y.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:$e.ConnectionChanged,value:jc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,n){if(n.body.case==="event"&&n.body.value.type===mi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[e,n]of this.attachmentMap)this.detachInternal(e),n.doc.applyStatus(xr.Detached)}detachInternal(e){const n=this.attachmentMap.get(e);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,n){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:ve.toChangePack(s),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ve.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:qc.Synced}]),r.getStatus()===xr.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(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:qc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof me?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((Yh(e)===S.ErrClientNotActivated||Yh(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((n,r)=>{this.taskQueue.push(()=>e().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const ng={Client:xy,Document:Ey,Primitive:ie,Text:bl,Counter:Fl,Tree:Ml,LogLevel:be,setLogLevel:ky,IntType:rn.IntegerCnt,LongType:rn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:xy,Document:Ey,Primitive:ie,Text:bl,Counter:Fl,Tree:Ml,LogLevel:be,setLogLevel:ky,IntType:rn.IntegerCnt,LongType:rn.LongCnt});var Cy={exports:{}};/*! +`));for(const r of e)this.applyChange(r,n);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,n){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,n);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Yr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Yr.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,n);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(n===Y.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:n,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const n=e.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:n,publisher:r}=e.body.value,i=[];if(n===mi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(n===mi.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(n===mi.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(qf),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:n,serverSeq:r}=e.value;if(!n)return;this.applySnapshot(BigInt(r),ve.hexToBytes(n));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const n=fs.fromStruct(e.rawChange);this.applyChange(n,e.source)}if(e.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of e.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(e.type==="watched"){const{clientID:n,presence:r}=e.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(e.type==="unwatched"){const{clientID:n}=e.value;this.removeOnlineClient(n),this.presences.delete(n)}if(e.type==="presence-changed"){const{clientID:n,presence:r}=e.value;this.presences.set(n,r)}}applyTransactionEvent(e){for(const n of e)this.applyDocEvent(n)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const n=e.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Ct(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const n=this.presences.get(e);return n?Ct(n):void 0}getPresenceForTest(e){const n=this.presences.get(e);return n?Ct(n):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Ct(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&e.push({clientID:n,presence:Ct(this.presences.get(n))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==e).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new 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 n=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Mt)){new yu(n,Ct(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=n.issueTimeTicket();c.setExecutedAt(d),n.push(c)}const r=n.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=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source: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 n=Vi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Mt)){new yu(n,Ct(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=n.issueTimeTicket();c.setExecutedAt(d),n.push(c)}const r=n.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=n.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source: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,n,r){const i={type:"local-broadcast",value:{topic:e,payload:n},options:r};this.publish([i])}}function zS(t,e){return n=>async r=>(t&&r.header.set("x-api-key",t),e&&r.header.set("authorization",e),await n(r))}const US="yorkie-js-sdk",jS="0.5.2",qS="Yorkie JS SDK",VS="./src/yorkie.ts",KS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},WS=["dist"],HS={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"},_S={node:">=18.0.0",npm:">=7.1.0"},GS={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},YS={name:"hackerwins",email:"susukang98@gmail.com"},QS="Apache-2.0",XS={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ZS="https://github.com/yorkie-team/yorkie-js-sdk#readme",ek={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},tk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},tg={name:US,version:jS,description:qS,main:VS,publishConfig:KS,files:WS,scripts:HS,engines:_S,repository:GS,author:YS,license:QS,bugs:XS,homepage:ZS,devDependencies:ek,dependencies:tk};function nk(){return t=>async e=>(e.header.set("x-yorkie-user-agent",tg.name+"/"+tg.version),await t(e))}const rk=t=>{try{if(JSON.stringify(t)===void 0)return!1}catch{return!1}return!0};var Sa=(t=>(t.Manual="manual",t.Realtime="realtime",t.RealtimePushOnly="realtime-pushonly",t.RealtimeSyncOff="realtime-syncoff",t))(Sa||{});const ta={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},ku={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class xy{constructor(e,n){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);n=n||ta,this.key=n.key?n.key:Ty(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||ta.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||ta.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||ta.retrySyncLoopDelay,this.rpcClient=n1(E1,I1({baseUrl:e,interceptors:[zS(n.apiKey,n.token),nk()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,n={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==xr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(n.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var 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=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ve.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ve.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===xr.Removed||(e.applyStatus(xr.Attached),this.attachmentMap.set(e.getKey(),new PS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,n={}){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:ve.toChangePack(e.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==xr.Removed&&e.applyStatus(xr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,n){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===n?e:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),e):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const n=this.attachmentMap.get(e.getKey());if(!n)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=ve.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,n,r,i){if(!this.isActive())throw new 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(!rk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??ku.maxRetries,a=ku.maxBackoff;let l=0;const c=h=>Math.min(ku.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${n}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(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 n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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 n=this.attachmentMap.get(e);if(!n)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,n.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:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return n.doc.publish([{type:$e.ConnectionChanged,value:jc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(n,c),c.body.case==="initialization"&&o([s,i])}catch(c){n.doc.resetOnlineClients(),n.doc.publish([{type:$e.Initialized,source:Y.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:$e.ConnectionChanged,value:jc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,n){if(n.body.case==="event"&&n.body.value.type===mi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[e,n]of this.attachmentMap)this.detachInternal(e),n.doc.applyStatus(xr.Detached)}detachInternal(e){const n=this.attachmentMap.get(e);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,n){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:ve.toChangePack(s),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ve.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:qc.Synced}]),r.getStatus()===xr.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(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:qc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof me?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((Yh(e)===S.ErrClientNotActivated||Yh(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((n,r)=>{this.taskQueue.push(()=>e().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const ng={Client:xy,Document:Ey,Primitive:ie,Text:bl,Counter:Fl,Tree:Ml,LogLevel:be,setLogLevel:ky,IntType:rn.IntegerCnt,LongType:rn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:xy,Document:Ey,Primitive:ie,Text:bl,Counter:Fl,Tree:Ml,LogLevel:be,setLogLevel:ky,IntType:rn.IntegerCnt,LongType:rn.LongCnt});var Cy={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 917bb7ab9..2d4a489c2 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-BXKIYS9E.js b/examples/simultaneous-cursors/assets/index-CfPS2aDQ.js similarity index 99% rename from examples/simultaneous-cursors/assets/index-BXKIYS9E.js rename to examples/simultaneous-cursors/assets/index-CfPS2aDQ.js index 60542785f..a8b6bbabf 100644 --- a/examples/simultaneous-cursors/assets/index-BXKIYS9E.js +++ b/examples/simultaneous-cursors/assets/index-CfPS2aDQ.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 V(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}V.prototype.__isLong__;Object.defineProperty(V.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Kh(n){var e=Math.clz32(n&-n);return n?31-e:e}V.isLong=Re;var Wh={},_h={};function Ci(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=_h[n],r)?r:(t=W(n,0,!0),i&&(_h[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Wh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Wh[n]=t),t))}V.fromInt=Ci;function St(n,e){if(isNaN(n))return e?dr:Ot;if(e){if(n<0)return dr;if(n>=Yp)return Zp}else{if(n<=-Gh)return qe;if(n+1>=Gh)return Xp}return n<0?St(-n,e).neg():W(n%fs|0,n/fs|0,e)}V.fromNumber=St;function W(n,e,t){return new V(n,e,t)}V.fromBits=W;var dl=Math.pow;function Hf(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?dr:Ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Hf(n.substring(1),e,t).neg();for(var i=St(dl(t,8)),s=Ot,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*fs+(this.low>>>0):this.high*fs+(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(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 Re(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(Re(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(qe)?qe:this.not().add(Vi)};C.neg=C.negate;C.add=function(e){Re(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,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=$t(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=$t(e)),wt){var t=wt.mul(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?dr:Ot;if(this.eq(qe))return e.isOdd()?qe:Ot;if(e.eq(qe))return this.isOdd()?qe: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(Yh)&&e.lt(Yh))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,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=$t(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 W(t,wt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?dr:Ot;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return dr;if(e.gt(this.shru(1)))return Qp;s=dr}else{if(this.eq(qe)){if(e.eq(Vi)||e.eq(jc))return qe;if(e.eq(qe))return Vi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Ot)?e.isNegative()?Vi:jc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(qe))return this.unsigned?dr: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:dl(2,a-48),c=St(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=St(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=Vi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=$t(e)),wt){var t=(this.unsigned?wt.rem_u:wt.rem_s)(this.low,this.high,e.low,e.high);return W(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 W(~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?Kh(this.low):Kh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=$t(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=$t(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=$t(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(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]};V.fromBytes=function(e,t,r){return r?V.fromBytesLE(e,t):V.fromBytesBE(e,t)};V.fromBytesLE=function(e,t){return new V(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};V.fromBytesBE=function(e,t){return new V(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ye=(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))(ye||{});class re extends Co{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=re.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new re(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 V.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(V.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=re.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 V)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return re.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=V.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class hl extends Gp{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new hl(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 vo{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=re.of(0,Ft);e.setRemovedAt(Ft),this.dummyHead=new hl(e),this.last=this.dummyHead,this.nodeMapByIndex=new yo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new vo}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=hl.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 nt extends Kr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new nt(t,vo.create());const i=vo.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new nt(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 Kr&&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({...m,value:m.value?{attributes:Xi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):Ft:Ks;if(m.canStyle(i,I)){const D=d.get(w),y=m.getCreatedAt();(!D||y.after(D))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Xi(r)}});for(const[D,y]of Object.entries(r)){const[g]=m.getValue().setAttr(D,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}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:Xi(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 Po 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 Po(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,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 Do 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 Do(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,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 F1=2,b1="root",gr="text";function Ps(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===gr}get paddedSize(){return this.size+(this.isText?0:F1)}isAncestorOf(e){return J1(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 J1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var he=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(he||{});function ey(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),ey(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function ty(n,e,t=0){for(const r of n.children)ty(r,e,t+1);e(n,t)}function Bl(n,e,t=0){for(const r of n._children)Bl(r,e,t+1);e(n,t)}function qc(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 qc(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 qc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function ny(n){return n.isText||n.children.length===0?n:ny(n.children[0])}function $1(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 j1(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,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Rt.of(Ee.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.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 Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.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(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ze(Ee.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){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new kr);const i=new Array;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 Vc(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(Vc)};return n.attrs&&(e.attributes=Xi((t=n.attrs)==null?void 0:t.toObject())),e}function Gf(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=>Gf(t)).join("")}`}function iy(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(iy),size:n.size,isRemoved:n.isRemoved}}class Et extends Co{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new z1(t),this.nodeMapByID=new ry(Ee.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 I=w.getCreatedAt().getActorID(),D=s?s.has(I)?s.get(I):Ft:Ks;if(w.canStyle(i,D)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):Ft:Ks;if(m.canStyle(i,I)&&r){const D=h.get(w),y=m.getCreatedAt();(!D||y.after(D))&&h.set(w,y),m.attrs||(m.attrs=new kr);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],D=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===he.Start&&!N)for(const _ of T.children)D.push(_);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):Ft:Ks;if(T.canDelete(s,B)||w.includes(T.parent)){const _=y.get(P),U=T.getCreatedAt();(!_||U.after(_))&&y.set(P,U),(x===he.Text||x===he.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of D)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>Vc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}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 Gf(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 m,w,I,D;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 p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Xi((D=i.attrs)==null?void 0:D.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(D,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(D,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===he.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?he.Text:he.Start]:[t,he.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,he.End];const a=s[o+1];return[a,a.isText?he.Text:he.Start]}findLeftToken([t,r]){if(r===he.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?he.Text:he.End]}return[t,he.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,he.Start];const a=s[o-1];return[a,a.isText?he.Text:he.End]}}class Oo 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 Oo(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>tt.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}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=>Gf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Rr{constructor(e,t,r,i){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.actor=r}static of(e,t,r,i){return new Rr(e,t,r,i)}next(){return new Rr(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new Rr(this.clientSeq,e,this.actor):new Rr(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new Rr(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const V1=new Rr(0,0n,Wf);class ds{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 ds({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);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Yr.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:ve.bytesToHex(ve.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>ve.bytesToHex(ve.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return ds.create({id:ve.bytesToChangeID(ve.hexToBytes(t)),operations:r==null?void 0:r.map(o=>ve.bytesToOperation(ve.hexToBytes(o))),presenceChange:i,message:s})}}class Fl{constructor(e,t,r,i,s,o){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=s,this.minSyncedTicket=o}static create(e,t,r,i,s,o){return new Fl(e,t,r,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class Zi{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new Zi(e,t)}increaseClientSeq(e){return e===0?this:new Zi(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 Zi.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 K1=new Zi(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(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 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 W1=rn.of(Ft,0);class bt{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new bt(e,t)}static fromStruct(e){const t=rn.fromStruct(e.id);return bt.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 Wr extends Gp{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 Wr(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){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):Ft:Ks;c.canDelete(t,h)?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 rt extends Co{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=V.fromNumber(r).toInt():this.value=Qh(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=V.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new rt(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 V.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=rt.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 V?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!!rt.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()===ye.Long?this.value=this.value+t.getValue().toInt():this.value=V.fromNumber(this.value+Qh(t.getValue())).toInt(),this}}class gs extends Jt{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new gs(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 rt))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()===ye.Long?t.getValue().multiply(-1):t.getValue()*-1;return gs.create(this.getParentCreatedAt(),re.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class mr 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 mr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new mr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,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 _1(n){const e=new Kf,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function H1(n){if(n.type===Yr.Put)return new mo({type:Ai.PUT,presence:_1(n.presence)});if(n.type===Yr.Clear)return new mo({type:Ai.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function G1(n){return new Wp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function sy(n){return new Ll({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:nd(n.getActorID())})}function b(n){if(n)return new F({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:nd(n.getActorID())})}function oy(n){switch(n){case ye.Null:return $.NULL;case ye.Boolean:return $.BOOLEAN;case ye.Integer:return $.INTEGER;case ye.Long:return $.LONG;case ye.Double:return $.DOUBLE;case ye.String:return $.STRING;case ye.Bytes:return $.BYTES;case ye.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function ay(n){switch(n){case sn.IntegerCnt:return $.INTEGER_CNT;case sn.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function wu(n){if(n instanceof _e)return new ut({type:$.JSON_OBJECT,createdAt:b(n.getCreatedAt()),value:Sy(n)});if(n instanceof nt)return new ut({type:$.JSON_ARRAY,createdAt:b(n.getCreatedAt()),value:IS(n)});if(n instanceof It)return new ut({type:$.TEXT,createdAt:b(n.getCreatedAt())});if(n instanceof re)return new ut({type:oy(n.getType()),createdAt:b(n.getCreatedAt()),value:n.toBytes()});if(n instanceof rt)return new ut({type:ay(n.getType()),createdAt:b(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Et)return new ut({type:$.TREE,createdAt:b(n.getCreatedAt()),value:xS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function Y1(n){return new ho({createdAt:b(n.getCreatedAt()),offset:n.getOffset()})}function Xo(n){return new Sr({createdAt:b(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function Zo(n){return new Ti({parentId:Ws(n.getParentID()),leftSiblingId:Ws(n.getLeftSiblingID())})}function Ws(n){return new Vr({createdAt:b(n.getCreatedAt()),offset:n.getOffset()})}function ly(n){const e=new Vf;if(n instanceof Ii){const t=n,r=new Ha;r.parentCreatedAt=b(t.getParentCreatedAt()),r.key=t.getKey(),r.value=wu(t.getValue()),r.executedAt=b(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof No){const t=n,r=new Ga;r.parentCreatedAt=b(t.getParentCreatedAt()),r.prevCreatedAt=b(t.getPrevCreatedAt()),r.value=wu(t.getValue()),r.executedAt=b(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Fr){const t=n,r=new Ya;r.parentCreatedAt=b(t.getParentCreatedAt()),r.prevCreatedAt=b(t.getPrevCreatedAt()),r.createdAt=b(t.getCreatedAt()),r.executedAt=b(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Qr){const t=n,r=new Qa;r.parentCreatedAt=b(t.getParentCreatedAt()),r.createdAt=b(t.getCreatedAt()),r.executedAt=b(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Po){const t=n,r=new Xa;r.parentCreatedAt=b(t.getParentCreatedAt()),r.from=Xo(t.getFromPos()),r.to=Xo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=b(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=b(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Do){const t=n,r=new Za;r.parentCreatedAt=b(t.getParentCreatedAt()),r.from=Xo(t.getFromPos()),r.to=Xo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=b(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=b(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof gs){const t=n,r=new el;r.parentCreatedAt=b(t.getParentCreatedAt()),r.value=wu(t.getValue()),r.executedAt=b(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Oo){const t=n,r=new tl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=b(o);r.parentCreatedAt=b(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos()),r.contents=rS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=b(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof mr){const t=n,r=new nl;r.parentCreatedAt=b(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=b(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=b(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function Q1(n){const e=[];for(const t of n)e.push(ly(t));return e}function X1(n){const e=new Vp({id:sy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=Q1(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=H1(n.getPresenceChange())),e}function Z1(n){const e=[];for(const t of n)e.push(X1(t));return e}function eS(n){const e=[];for(const t of n)e.push(new Kp({key:t.getStrKey(),element:Qf(t.getValue())}));return e}function tS(n){const e=[];for(const t of n)e.push(new ul({element:Qf(t.getValue())}));return e}function nS(n){const e=[];for(const t of n){const r=new cl;r.id=Y1(t.getID()),r.value=t.getValue().getContent(),r.removedAt=b(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new us;a.value=o.getValue(),a.updatedAt=b(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function rS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new fl({content:Yf(t)}));return e}function iS(n){const e={};for(const t of n)e[t.getKey()]=new us({value:t.getValue(),updatedAt:b(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Yf(n){if(!n)return[];const e=[];return Bl(n,(t,r)=>{const i=new go({id:Ws(t.id),type:t.type,removedAt:b(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Ws(t.insPrevID)),t.insNextID&&(i.insNextId=Ws(t.insNextID)),t.attrs&&(i.attributes=iS(t.attrs)),e.push(i)}),e}function sS(n){const e=new He;return e.body.case="jsonObject",e.body.value=new rl({nodes:eS(n.getRHT()),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function uy(n){const e=new He;return e.body.case="jsonArray",e.body.value=new il({nodes:tS(n.getElements()),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function oS(n){const e=new He;return e.body.case="primitive",e.body.value=new sl({type:oy(n.getType()),value:n.toBytes(),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function aS(n){const e=new He;return e.body.case="text",e.body.value=new ol({nodes:nS(n.getRGATreeSplit()),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function lS(n){const e=new He;return e.body.case="counter",e.body.value=new al({type:ay(n.getType()),value:n.toBytes(),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function cy(n){const e=new He;return e.body.case="tree",e.body.value=new ll({nodes:Yf(n.getRoot()),createdAt:b(n.getCreatedAt()),movedAt:b(n.getMovedAt()),removedAt:b(n.getRemovedAt())}),e}function Qf(n){if(n instanceof _e)return sS(n);if(n instanceof nt)return uy(n);if(n instanceof re)return oS(n);if(n instanceof It)return aS(n);if(n instanceof rt)return lS(n);if(n instanceof Et)return cy(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function uS(n){return new Ar({documentKey:n.getDocumentKey(),checkpoint:G1(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:Z1(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:b(n.getMinSyncedTicket())})}function Xh(n){const e=n.findDetails(x1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function fy(n){return Rr.of(n.clientSeq,BigInt(n.lamport),td(n.actorId),BigInt(n.serverSeq))}function M(n){if(n)return tt.of(BigInt(n.lamport),n.delimiter,td(n.actorId))}function Xf(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function cS(n){const e=n.type;if(e===Ai.PUT){const t=Xf(n.presence);return{type:Yr.Put,presence:t}}if(e===Ai.CLEAR)return{type:Yr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function fS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,Xf(r))}),e}function dy(n){switch(n){case $.NULL:return ye.Null;case $.BOOLEAN:return ye.Boolean;case $.INTEGER:return ye.Integer;case $.LONG:return ye.Long;case $.DOUBLE:return ye.Double;case $.STRING:return ye.String;case $.BYTES:return ye.Bytes;case $.DATE:return ye.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function gl(n){switch(n){case $.INTEGER_CNT:return sn.IntegerCnt;case $.LONG_CNT:return sn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Su(n){switch(n.type){case $.JSON_OBJECT:return n.value?wy(n.value):_e.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?AS(n.value):nt.create(M(n.createdAt));case $.TEXT:return It.create(hs.create(),M(n.createdAt));case $.TREE:return ES(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return re.of(re.valueFromBytes(dy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return rt.create(gl(n.type),rt.valueFromBytes(gl(n.type),n.value),M(n.createdAt))}}function ea(n){return bt.of(rn.of(M(n.createdAt),n.offset),n.relativeOffset)}function hy(n){return rn.of(M(n.createdAt),n.offset)}function dS(n){const e=wo.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Wr.create(hy(n.id),e);return t.remove(M(n.removedAt)),t}function Di(n){return Rt.of(_s(n.parentId),_s(n.leftSiblingId))}function _s(n){return Ee.of(M(n.createdAt),n.offset)}function hS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=Zf(t.content);e.push(r)}),e}function Zf(n){if(n.length===0)return;const e=[];for(const i of n)e.push(mS(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,Ft).getRoot()}function gS(n){const e=kr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function mS(n){const e=_s(n.id),t=Ze.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=gS(n.attributes)),n.insPrevId&&(t.insPrevID=_s(n.insPrevId)),n.insNextId&&(t.insNextID=_s(n.insNextId)),t.removedAt=M(n.removedAt),t}function gy(n){if(n.body.case==="set"){const e=n.body.value;return Ii.create(e.key,Su(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return No.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Su(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 Qr.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)}),Po.create(M(e.parentCreatedAt),ea(e.from),ea(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)}),Do.create(M(e.parentCreatedAt),ea(e.from),ea(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 gs.create(M(e.parentCreatedAt),Su(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))}),Oo.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),hS(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?mr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),mr.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function pS(n){const e=[];for(const t of n){const r=gy(t);r&&e.push(r)}return e}function my(n){const e=[];for(const t of n)e.push(ds.create({id:fy(t.id),operations:pS(t.operations),presenceChange:t.presenceChange?cS(t.presenceChange):void 0,message:t.message}));return e}function yS(n){return Zi.of(BigInt(n.serverSeq),n.clientSeq)}function vS(n){return Fl.create(n.documentKey,yS(n.checkpoint),n.isRemoved,my(n.changes),n.snapshot,M(n.minSyncedTicket))}function py(n){const e=new po;for(const r of n.nodes){const i=ed(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new _e(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function yy(n){const e=new vo;for(const r of n.nodes)e.insert(ed(r.element));const t=new nt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function wS(n){const e=re.of(re.valueFromBytes(dy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function SS(n){const e=new hs;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,dS(i));i.insPrevId&&s.setInsPrev(e.findNode(hy(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 kS(n){const e=rt.create(gl(n.type),rt.valueFromBytes(gl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function vy(n){const e=Zf(n.nodes);return Et.create(e,M(n.createdAt))}function ed(n){if(n.body.case==="jsonObject")return py(n.body.value);if(n.body.case==="jsonArray")return yy(n.body.value);if(n.body.case==="primitive")return wS(n.body.value);if(n.body.case==="text")return SS(n.body.value);if(n.body.case==="counter")return kS(n.body.value);if(n.body.case==="tree")return vy(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function TS(n){if(!n)return{root:_e.create(Ft),presences:new Map};const e=wc.fromBinary(n);return{root:ed(e.root),presences:fS(e.presences)}}function wy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return py(e.body.value)}function Sy(n){return Qf(n).toBinary()}function AS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return yy(e.body.value)}function IS(n){return uy(n).toBinary()}function ES(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return vy(e.body.value)}function xS(n){return cy(n).toBinary()}function ky(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function td(n){return ky(n)}function Ty(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function nd(n){return Ty(n)}function CS(n){const e=Ll.fromBinary(n);return fy(e)}function NS(n){const e=Vf.fromBinary(n);return gy(e)}const ve={fromPresence:Xf,toChangePack:uS,fromChangePack:vS,fromChanges:my,toTreeNodes:Yf,fromTreeNodes:Zf,objectToBytes:Sy,bytesToObject:wy,bytesToSnapshot:TS,bytesToHex:ky,hexToBytes:Ty,toHexString:td,toUint8Array:nd,toOperation:ly,toChangeID:sy,PbChangeID:Ll,bytesToChangeID:CS,bytesToOperation:NS};var Fe=(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))(Fe||{});let oi=3;function Ay(n){oi=n}const J={trivial:(...n)=>{oi>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{oi>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{oi>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{oi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{oi>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=>oi<=n};function Iy(){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 PS{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===ka.RealtimeSyncOff?!1:this.syncMode===ka.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==ka.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 ku=()=>{};class DS{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=ku),i.error===void 0&&(i.error=ku),i.complete===void 0&&(i.complete=ku);const s=Iy(),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 Ki{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=Hp,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 Ki(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 ds.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 So{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 So(_e.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 Kr&&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 Kr&&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 Kr&&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 So(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r);i.element.getRemovedAt()&&e.compare(i.element.getRemovedAt())>=0&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i!==void 0&&e.compare(i)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Ey(n,e){const t=new ko(n);return new Proxy(e,t.getHandlers())}class ko{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(Fe.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),ko.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(Fe.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():ai(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(Fe.Trivial)&&J.trivial(`obj[${r}]`),ko.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=ml(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ii.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=ml(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(Qr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function RS(n,e){const t=new oe(n,e);return new Proxy(e,t.getHandlers())}function LS(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function BS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class oe{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 xr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return xr(e,a)}:i==="getLast"?()=>xr(e,r.getLast()):i==="deleteByID"?o=>{const a=oe.deleteInternalByID(e,r,o);return xr(e,a)}:i==="insertAfter"?(o,a)=>{const l=oe.insertAfterInternal(e,r,o,a);return xr(e,l)}:i==="insertBefore"?(o,a)=>{const l=oe.insertBeforeInternal(e,r,o,a);return xr(e,l)}:i==="moveBefore"?(o,a)=>{oe.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{oe.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{oe.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{oe.moveLastInternal(e,r,o)}:LS(i)?ai(e,r.get(Number(i))):i==="push"?o=>oe.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>oe.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?oe.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>oe.includes(e,r,o,a):i==="indexOf"?(o,a)=>oe.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>oe.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>oe.toTestString(r):typeof i=="string"&&BS(i)?(...o)=>{const a=Array.from(r).map(l=>ai(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(Fe.Trivial)&&J.trivial(`array[${i}]`),oe.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield xr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=ml(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return oe.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=ml(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(No.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return oe.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(Qr.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(Qr.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(re.isSupport(r))return Array.from(t).map(c=>ai(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(re.isSupport(r))return Array.from(t).map(c=>ai(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(re.isSupport(r))return Array.from(t).map(c=>ai(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 bl{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(Fe.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?cs(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 Po(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(Fe.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=cs(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 Do(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([bt.fromStruct(e[0]),bt.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 Ml{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=re.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(gs.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 rd(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===gr){xy(n);const{value:s}=n,o=Ze.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!_p(o)){const c=cs(o);a=new kr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Ze.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)rd(c,l,t)}}function FS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===gr){const{value:s}=e;i=Ze.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!_p(o)){const l=cs(o);a=new kr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Ze.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)rd(l,i,n)}return i}function xy(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function Zh(n){if(!n.length)return!0;if(n[0].type===gr)for(const t of n){const{type:r}=t;if(r!==gr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");xy(t)}else for(const t of n){const{type:r}=t;if(r===gr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Jl{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 Ze.create(Ee.of(e.issueTimeTicket(),0),b1);const t=Ze.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)rd(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?cs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(mr.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?cs(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(mr.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(mr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(Zh(r),r[0].type!==gr))for(const d of r){const{children:h=[]}=d;Zh(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===gr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Ze.create(Ee.of(this.context.issueTimeTicket(),0),gr,d))}else o=r.map(d=>d&&FS(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(Oo.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 eg(n,e){return Ey(n,e)}function xr(n,e){if(e){if(e instanceof re)return e;if(e instanceof _e)return Ey(n,e);if(e instanceof nt)return RS(n,e);if(e instanceof It)return new bl(n,e);if(e instanceof rt){const t=new Ml(sn.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Et){const t=new Jl;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ai(n,e){const t=xr(n,e);return t instanceof re?t.getValue():t}function ml(n,e,t){let r;if(re.isSupport(e))r=re.of(e,t);else if(Array.isArray(e))r=nt.create(t,oe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof bl?(r=It.create(hs.create(),t),e.initialize(n,r)):e instanceof Ml?(r=rt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof Jl?(r=Et.create(e.buildRoot(n),t),e.initialize(n,r)):r=_e.create(t,ko.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const tg=50;class bS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=tg&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=tg&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const MS="yorkie-devtools-panel",JS="yorkie-devtools-sdk";let Oi="disconnected";const ng=new Map,Sa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Sa);function ta(n,e){(e!=null&&e.force||Oi!=="disconnected")&&window.postMessage({source:JS,...n},"*")}function $S(n){if(!n.isEnableDevtools()||typeof window>"u"||ng.has(n.getKey()))return;Sa.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(Sa.get(n.getKey()).push(t),Oi==="synced"&&ta({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ng.set(n.getKey(),[e]),ta({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==MS)return;switch(t.data.msg){case"devtools::connect":if(Oi!=="disconnected")break;Oi="connected",ta({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Oi="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Oi="synced",ta({msg:"doc::sync::full",docKey:n.getKey(),events:Sa.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Cr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Cr||{}),$e=(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))($e||{}),Kc=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Kc||{}),Wc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Wc||{});class Cy{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=So.create(),this.changeID=V1,this.checkpoint=K1,this.localChanges=[],this.eventStream=OS(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new bS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},$S(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=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=eg(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new vu(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(Fe.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(Fe.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==="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])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(Fe.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 Fl.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return eg(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:r,presences:i}=ve.bytesToSnapshot(t);this.root=new So(r),this.presences=i,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{snapshot:this.isEnableDevtools()?ve.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){J.isEnabled(Fe.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(Fe.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);J.isEnabled(Fe.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 Yr.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 Yr.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.syncLamport(e.getID().getLamport()),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===pi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===pi.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===pi.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(Wf),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}=e.value;if(!t)return;this.applySnapshot(BigInt(r),ve.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.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}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=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new vu(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=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new vu(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])}}function zS(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const US="yorkie-js-sdk",jS="0.5.1",qS="Yorkie JS SDK",VS="./src/yorkie.ts",KS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},WS=["dist"],_S={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"},HS={node:">=18.0.0",npm:">=7.1.0"},GS={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},YS={name:"hackerwins",email:"susukang98@gmail.com"},QS="Apache-2.0",XS={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ZS="https://github.com/yorkie-team/yorkie-js-sdk#readme",ek={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},tk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},rg={name:US,version:jS,description:qS,main:VS,publishConfig:KS,files:WS,scripts:_S,engines:HS,repository:GS,author:YS,license:QS,bugs:XS,homepage:ZS,devDependencies:ek,dependencies:tk};function nk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",rg.name+"/"+rg.version),await n(e))}const rk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var ka=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(ka||{});const na={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Tu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ny{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||na,this.key=t.key?t.key:Iy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||na.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||na.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||na.retrySyncLoopDelay,this.rpcClient=n1(E1,I1({baseUrl:e,interceptors:[zS(t.apiKey,t.token),nk()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Cr.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:ve.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ve.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===Cr.Removed||(e.applyStatus(Cr.Attached),this.attachmentMap.set(e.getKey(),new PS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),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:ve.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Cr.Removed&&e.applyStatus(Cr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),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(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),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=ve.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=ve.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,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(!rk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Tu.maxRetries,a=Tu.maxBackoff;let l=0;const c=h=>Math.min(Tu.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(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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:$e.ConnectionChanged,value:Kc.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:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===pi.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(Cr.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:ve.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ve.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Wc.Synced}]),r.getStatus()===Cr.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(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Wc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof me?e.code===H.Canceled||e.code===H.Unknown||e.code===H.ResourceExhausted||e.code===H.Unavailable?!0:((Xh(e)===S.ErrClientNotActivated||Xh(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Py={Client:Ny,Document:Cy,Primitive:re,Text:bl,Counter:Ml,Tree:Jl,LogLevel:Fe,setLogLevel:Ay,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ny,Document:Cy,Primitive:re,Text:bl,Counter:Ml,Tree:Jl,LogLevel:Fe,setLogLevel:Ay,IntType:sn.IntegerCnt,LongType:sn.LongCnt});class ik{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const sk=({xPos:n,yPos:e})=>{const[t,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,c)=>{const d=new ik(l,c);s.push(d),o(s),t.push(d),r(t)};return Ue.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 p=0;ph)s.shift();else{c.lineWidth=5,c.lineJoin="round";const I=0,D=0,y=0;c.strokeStyle=`rgb(${I},${D},${y})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(m.x,m.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),Ue.useEffect(()=>{a(n,e)},[n,e]),ue.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},ok="_goUp0_1lnal_1",ak="_goUpAnimation0_1lnal_1",lk="_fadeOut_1lnal_1",uk="_goUp1_1lnal_16",ck="_goUpAnimation1_1lnal_1",fk="_goUp2_1lnal_31",dk="_goUpAnimation2_1lnal_1",hk="_leftRight0_1lnal_46",gk="_leftRightAnimation0_1lnal_1",mk="_leftRight1_1lnal_60",pk="_leftRightAnimation1_1lnal_1",yk="_leftRight2_1lnal_74",vk="_leftRightAnimation2_1lnal_1",Au={goUp0:ok,goUpAnimation0:ak,fadeOut:lk,goUp1:uk,goUpAnimation1:ck,goUp2:fk,goUpAnimation2:dk,leftRight0:hk,leftRightAnimation0:gk,leftRight1:mk,leftRightAnimation1:pk,leftRight2:yk,leftRightAnimation2:vk};function wk({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ue.jsx("div",{className:"single-animation-container",children:ue.jsx("div",{className:`absolute select-none pointer-events-none ${Au.disappear} text-${t%5+2}xl ${Au["goUp"+t%3]}`,style:{left:n,top:e},children:ue.jsx("div",{className:Au["leftRight"+t%3],children:ue.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ue.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function ig(n,e){const t=Ue.useRef(n);Ue.useEffect(()=>{t.current=n},[n]),Ue.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const Sk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return ig(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),ig(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ue.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ue.jsx(wk,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},kk=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ue.jsxs(ue.Fragment,{children:[ue.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ue.jsx(Sk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ue.jsx(sk,{xPos:e,yPos:t})]}),Tk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ue.jsxs("div",{className:"cursor-selector-container",children:[ue.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ue.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ue.jsx("div",{className:"num-users-container",children:ue.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Iu=new Py.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),ri=new Py.Document("simultaneous-cursors",{enableDevtools:!0}),Ak=()=>{const[n,e]=Ue.useState([]),t=r=>{ri.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Iu.activate(),ri.subscribe("presence",a=>{e(ri.getPresences())}),await Iu.attach(ri,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Iu.deactivate()})})();const i=()=>{ri.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{ri.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{ri.update((l,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)}},[]),ue.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ue.jsx(kk,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ue.jsx(Tk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Eu.createRoot(document.getElementById("root")).render(ue.jsx(Ak,{})); +`));for(const r of e)this.applyChange(r,t);J.isEnabled(Fe.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 Yr.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 Yr.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.syncLamport(e.getID().getLamport()),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===pi.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===pi.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===pi.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(Wf),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}=e.value;if(!t)return;this.applySnapshot(BigInt(r),ve.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.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}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=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new vu(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=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new vu(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])}}function zS(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const US="yorkie-js-sdk",jS="0.5.2",qS="Yorkie JS SDK",VS="./src/yorkie.ts",KS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},WS=["dist"],_S={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"},HS={node:">=18.0.0",npm:">=7.1.0"},GS={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},YS={name:"hackerwins",email:"susukang98@gmail.com"},QS="Apache-2.0",XS={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ZS="https://github.com/yorkie-team/yorkie-js-sdk#readme",ek={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},tk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},rg={name:US,version:jS,description:qS,main:VS,publishConfig:KS,files:WS,scripts:_S,engines:HS,repository:GS,author:YS,license:QS,bugs:XS,homepage:ZS,devDependencies:ek,dependencies:tk};function nk(){return n=>async e=>(e.header.set("x-yorkie-user-agent",rg.name+"/"+rg.version),await n(e))}const rk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var ka=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(ka||{});const na={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Tu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ny{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||na,this.key=t.key?t.key:Iy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||na.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||na.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||na.retrySyncLoopDelay,this.rpcClient=n1(E1,I1({baseUrl:e,interceptors:[zS(t.apiKey,t.token),nk()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Cr.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:ve.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=ve.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===Cr.Removed||(e.applyStatus(Cr.Attached),this.attachmentMap.set(e.getKey(),new PS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),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:ve.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=ve.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Cr.Removed&&e.applyStatus(Cr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),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(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),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=ve.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=ve.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,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(!rk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Tu.maxRetries,a=Tu.maxBackoff;let l=0;const c=h=>Math.min(Tu.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(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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:$e.ConnectionChanged,value:Kc.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:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===pi.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(Cr.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:ve.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=ve.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Wc.Synced}]),r.getStatus()===Cr.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(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Wc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof me?e.code===H.Canceled||e.code===H.Unknown||e.code===H.ResourceExhausted||e.code===H.Unavailable?!0:((Xh(e)===S.ErrClientNotActivated||Xh(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Py={Client:Ny,Document:Cy,Primitive:re,Text:bl,Counter:Ml,Tree:Jl,LogLevel:Fe,setLogLevel:Ay,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ny,Document:Cy,Primitive:re,Text:bl,Counter:Ml,Tree:Jl,LogLevel:Fe,setLogLevel:Ay,IntType:sn.IntegerCnt,LongType:sn.LongCnt});class ik{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const sk=({xPos:n,yPos:e})=>{const[t,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,c)=>{const d=new ik(l,c);s.push(d),o(s),t.push(d),r(t)};return Ue.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 p=0;ph)s.shift();else{c.lineWidth=5,c.lineJoin="round";const I=0,D=0,y=0;c.strokeStyle=`rgb(${I},${D},${y})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(m.x,m.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),Ue.useEffect(()=>{a(n,e)},[n,e]),ue.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},ok="_goUp0_1lnal_1",ak="_goUpAnimation0_1lnal_1",lk="_fadeOut_1lnal_1",uk="_goUp1_1lnal_16",ck="_goUpAnimation1_1lnal_1",fk="_goUp2_1lnal_31",dk="_goUpAnimation2_1lnal_1",hk="_leftRight0_1lnal_46",gk="_leftRightAnimation0_1lnal_1",mk="_leftRight1_1lnal_60",pk="_leftRightAnimation1_1lnal_1",yk="_leftRight2_1lnal_74",vk="_leftRightAnimation2_1lnal_1",Au={goUp0:ok,goUpAnimation0:ak,fadeOut:lk,goUp1:uk,goUpAnimation1:ck,goUp2:fk,goUpAnimation2:dk,leftRight0:hk,leftRightAnimation0:gk,leftRight1:mk,leftRightAnimation1:pk,leftRight2:yk,leftRightAnimation2:vk};function wk({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ue.jsx("div",{className:"single-animation-container",children:ue.jsx("div",{className:`absolute select-none pointer-events-none ${Au.disappear} text-${t%5+2}xl ${Au["goUp"+t%3]}`,style:{left:n,top:e},children:ue.jsx("div",{className:Au["leftRight"+t%3],children:ue.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ue.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function ig(n,e){const t=Ue.useRef(n);Ue.useEffect(()=>{t.current=n},[n]),Ue.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const Sk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return ig(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),ig(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ue.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ue.jsx(wk,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},kk=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ue.jsxs(ue.Fragment,{children:[ue.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ue.jsx(Sk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ue.jsx(sk,{xPos:e,yPos:t})]}),Tk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ue.jsxs("div",{className:"cursor-selector-container",children:[ue.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ue.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ue.jsx("div",{className:"num-users-container",children:ue.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Iu=new Py.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),ri=new Py.Document("simultaneous-cursors",{enableDevtools:!0}),Ak=()=>{const[n,e]=Ue.useState([]),t=r=>{ri.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Iu.activate(),ri.subscribe("presence",a=>{e(ri.getPresences())}),await Iu.attach(ri,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Iu.deactivate()})})();const i=()=>{ri.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{ri.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{ri.update((l,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)}},[]),ue.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ue.jsx(kk,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ue.jsx(Tk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Eu.createRoot(document.getElementById("root")).render(ue.jsx(Ak,{})); diff --git a/examples/simultaneous-cursors/index.html b/examples/simultaneous-cursors/index.html index 86c67b48b..e357b9906 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-DWRqngRf.js b/examples/vanilla-codemirror6/assets/index-DB4O8pnL.js similarity index 99% rename from examples/vanilla-codemirror6/assets/index-DWRqngRf.js rename to examples/vanilla-codemirror6/assets/index-DB4O8pnL.js index 58576df52..098bf5bbb 100644 --- a/examples/vanilla-codemirror6/assets/index-DWRqngRf.js +++ b/examples/vanilla-codemirror6/assets/index-DB4O8pnL.js @@ -20,7 +20,7 @@ var dS=Object.defineProperty;var pS=(n,e,t)=>e in n?dS(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 je(n){return(n&&n.__isLong__)===!0}function kd(n){var e=Math.clz32(n&-n);return n?31-e:e}Y.isLong=je;var xd={},Td={};function Xr(n,e){var t,i,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(i=Td[n],i)?i:(t=ee(n,0,!0),r&&(Td[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(i=xd[n],i)?i:(t=ee(n,n<0?-1:0,!1),r&&(xd[n]=t),t))}Y.fromInt=Xr;function Ct(n,e){if(isNaN(n))return e?In:Ft;if(e){if(n<0)return In;if(n>=zm)return Jm}else{if(n<=-Pd)return tt;if(n+1>=Pd)return Gm}return n<0?Ct(-n,e).neg():ee(n%cs|0,n/cs|0,e)}Y.fromNumber=Ct;function ee(n,e,t){return new Y(n,e,t)}Y.fromBits=ee;var ml=Math.pow;function Fu(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?In:Ft;if(t=t||10,t<2||360)throw Error("interior hyphen");if(i===0)return Fu(n.substring(1),e,t).neg();for(var r=Ct(ml(t,8)),s=Ft,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*cs+(this.low>>>0):this.high*cs+(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 je(e)||(e=Kt(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(je(e)||(e=Kt(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(_r)};C.neg=C.negate;C.add=function(e){je(e)||(e=Kt(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,ee(f<<16|p,c<<16|u,this.unsigned)};C.subtract=function(e){return je(e)||(e=Kt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(je(e)||(e=Kt(e)),$t){var t=$t.mul(this.low,this.high,e.low,e.high);return ee(t,$t.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?In: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(Ad)&&e.lt(Ad))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,ee(p<<16|g,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(je(e)||(e=Kt(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 ee(t,$t.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?In:Ft;var i,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return In;if(e.gt(this.shru(1)))return _m;s=In}else{if(this.eq(tt)){if(e.eq(_r)||e.eq(Nc))return tt;if(e.eq(tt))return _r;var o=this.shr(1);return i=o.div(e).shl(1),i.eq(Ft)?e.isNegative()?_r:Nc:(r=this.sub(e.mul(i)),s=i.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?In: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:ml(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=_r),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(je(e)||(e=Kt(e)),$t){var t=(this.unsigned?$t.rem_u:$t.rem_s)(this.low,this.high,e.low,e.high);return ee(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 ee(~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?kd(this.low):kd(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return je(e)||(e=Kt(e)),ee(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return je(e)||(e=Kt(e)),ee(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return je(e)||(e=Kt(e)),ee(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low<>>32-e,this.unsigned):ee(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):ee(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?ee(this.high,0,this.unsigned):ee(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,ee(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,ee(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?ee(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:ee(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 Ae=(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))(Ae||{});class pe extends No{constructor(t,i){super(i);d(this,"valueType");d(this,"value");this.valueType=pe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,i){return new pe(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?`"${Si(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=pe.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 pe.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 Ol extends Fm{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,i){const r=new Ol(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 uo{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=pe.of(0,_t);e.setRemovedAt(_t),this.dummyHead=new Ol(e),this.last=this.dummyHead,this.nodeMapByIndex=new co,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new uo}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=Ol.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 pt extends nr{constructor(t,i){super(t);d(this,"elements");this.elements=i}static create(t,i){if(!i)return new pt(t,uo.create());const r=uo.create();for(const s of i)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new pt(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 nr&&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({...p,value:p.value?{attributes:Kr(p.value.getAttributes()),content:p.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,i,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const p of h){const g=p.getCreatedAt().getActorID(),y=s!=null&&s.size?s.has(g)?s.get(g):_t:Gs;if(p.canStyle(r,y)){const O=c.get(g),S=p.getCreatedAt();(!O||S.after(O))&&c.set(g,S),u.push(p)}}const f=[];for(const p of u){if(p.isRemoved())continue;const[g,y]=this.rgaTreeSplit.findIndexesFromRange(p.createPosRange());l.push({type:"style",actor:r.getActorID(),from:g,to:y,value:{attributes:Kr(i)}});for(const[O,S]of Object.entries(i)){const[k]=p.getValue().setAttr(O,S,r);k!==void 0&&f.push({parent:p.getValue(),child:k})}}return[c,f,l]}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:Kr(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Bt(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 qo extends Jt{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 qo(t,i,r,s,o,a,l)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Bt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),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 Mo extends Jt{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 Mo(t,i,r,s,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Bt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),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 F1=2,z1="root",Rn="text";function Is(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===Rn}get paddedSize(){return this.size+(this.isText?0:F1)}isAncestorOf(e){return G1(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 G1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ke=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ke||{});function Ym(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),Ym(s,Math.max(0,o),Math.min(a,s.size),i),h&&i([s,"End"],h)}r+=s.paddedSize}}function Hm(n,e,t=0){for(const i of n.children)Hm(i,e,t+1);e(n,t)}function Hl(n,e,t=0){for(const i of n._children)Hl(i,e,t+1);e(n,t)}function Bc(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 Bc(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 Bc(s,e-r-1,t);r+=s.paddedSize,i+=1}return{node:n,offset:i}}function Km(n){return n.isText||n.children.length===0?n:Km(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(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 K1(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 zt{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new zt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node: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],zt.of(i.id,Me.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return zt.of(Me.of(dt.fromStruct(e.parentID.createdAt),e.parentID.offset),Me.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 Me{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Me(e,t)}static fromStruct(e){return Me.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(Me.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(Me.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){return!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,i){return this.isText?!1:!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,i){this.attrs||(this.attrs=new qn);const r=new Array;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 qc(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(qc)};return n.attrs&&(e.attributes=Kr((t=n.attrs)==null?void 0:t.toObject())),e}function zu(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()}="${Si(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>zu(t)).join("")}`}function tO(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(tO),size:n.size,isRemoved:n.isRemoved}}class qt extends No{constructor(t,i){super(i);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new Y1(t),this.nodeMapByID=new eO(Me.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,i){return new qt(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=g.getCreatedAt().getActorID(),O=s?s.has(y)?s.get(y):_t:Gs;if(g.canStyle(r,O)&&i){const S=f.get(y),k=g.getCreatedAt();(!S||k.after(S))&&f.set(y,k);const $=g.setAttrs(i,r),x=$.reduce((R,[,j])=>(j&&(R[j.getKey()]=u[j.getKey()]),R),{}),Q=g.parent,A=g.prevSibling||g.parent;Object.keys(x).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(g,g),fromPath:this.toPath(Q,A),toPath:this.toPath(g,g),actor:r.getActorID(),value:x});for(const[R]of $)R&&p.push({parent:g,child:R})}}),[f,p,c]}removeStyle(t,i,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([p])=>{const g=p.getCreatedAt().getActorID(),y=s?s.has(g)?s.get(g):_t:Gs;if(p.canStyle(r,y)&&i){const O=u.get(g),S=p.getCreatedAt();(!O||S.after(O))&&u.set(g,S),p.attrs||(p.attrs=new qn);for(const x of i){const Q=p.attrs.remove(x,r);for(const A of Q)f.push({parent:p,child:A})}const k=p.parent,$=p.prevSibling||p.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(p,p),fromPath:this.toPath(k,$),toPath:this.toPath(p,p),value:i})}}),[u,f,c]}edit(t,i,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),p=this.toPath(l,h),g=[],y=[],O=[],S=new Map;this.traverseInPosRange(l,h,c,u,([x,Q],A)=>{if(Q===ke.Start&&!A)for(const W of x.children)O.push(W);const R=x.getCreatedAt().getActorID(),j=a?a.has(R)?a.get(R):_t:Gs;if(x.canDelete(s,j)||g.includes(x.parent)){const W=S.get(R),G=x.getCreatedAt();(!W||G.after(W))&&S.set(R,G),(Q===ke.Text||Q===ke.Start)&&g.push(x),y.push([x,Q])}});const k=this.makeDeletionChanges(y,s),$=[];for(const x of g)x.remove(s),x.isRemoved&&$.push({parent:this,child:x});for(const x of O)x.removedAt||l.append(x);if(r>0){let x=0,Q=l,A=h;for(;x{l.isRemoved&&(R.remove(s),$.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),A.isRemoved||x.push(A);if(x.length){const A=x.map(R=>qc(R));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:p,toPath:p,actor:s.getActorID(),value:A})}}return[k,$,S]}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 zt.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 zu(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,y,O;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=zt.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:(y=r.insNextID)==null?void 0:y.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?Kr((O=r.attrs)==null?void 0:O.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(O,p)):r.push({type:"content",from:S,to:k,fromPath:this.toPath(y,u),toPath:this.toPath(O,p),actor:i.getActorID()}))}return r.reverse()}findRightToken([t,i]){if(i===ke.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ke.Text:ke.Start]:[t,ke.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,ke.End];const a=s[o+1];return[a,a.isText?ke.Text:ke.Start]}findLeftToken([t,i]){if(i===ke.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?ke.Text:ke.End]}return[t,ke.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,ke.Start];const a=s[o-1];return[a,a.isText?ke.Text:ke.End]}}class Xo extends Jt{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 Xo(t,i,r,s,o,a,l)}execute(t){var l;const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=i,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>dt.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g}))}}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=>zu(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Jn{constructor(e,t,i,r){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");this.clientSeq=e,this.serverSeq=r,this.lamport=t,this.actor=i}static of(e,t,i,r){return new Jn(e,t,i,r)}next(){return new Jn(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new Jn(this.clientSeq,e,this.actor):new Jn(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return dt.of(this.lamport,e,this.actor)}setActor(e){return new Jn(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const tw=new Jn(0,0n,Wu);class us{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 us({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);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===hr.Put?t.set(this.id.getActorID(),Zt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:$e.bytesToHex($e.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>$e.bytesToHex($e.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:i,presenceChange:r,message:s}=e;return us.create({id:$e.bytesToChangeID($e.hexToBytes(t)),operations:i==null?void 0:i.map(o=>$e.bytesToOperation($e.hexToBytes(o))),presenceChange:r,message:s})}}class Kl{constructor(e,t,i,r,s,o){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=i,this.changes=r,this.snapshot=s,this.minSyncedTicket=o}static create(e,t,i,r,s,o){return new Kl(e,t,i,r,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class es{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new es(e,t)}increaseClientSeq(e){return e===0?this:new es(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 es.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 iw=new es(0n,0);class xi{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new xi(e,t)}static fromStruct(e){return xi.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 xi(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 nw=xi.of(_t,0);class Gt{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Gt(e,t)}static fromStruct(e){const t=xi.fromStruct(e.id);return Gt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return xi.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 rr extends Fm{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 rr(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){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,i),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,i){const r=!!i,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?i.has(c)?i.get(c):_t:Gs;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const i=[];let r,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Qi=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Qi||{});class gt extends No{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=$d(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 gt(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=gt.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!!gt.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()===Ae.Long?this.value=this.value+t.getValue().toInt():this.value=Y.fromNumber(this.value+$d(t.getValue())).toInt(),this}}class ds extends Jt{constructor(t,i,r){super(t,r);d(this,"value");this.value=i}static create(t,i,r){return new ds(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 gt))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()===Ae.Long?t.getValue().multiply(-1):t.getValue()*-1;return ds.create(this.getParentCreatedAt(),pe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class En extends Jt{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 En(t,i,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,i,r,s,o,a){return new En(t,i,r,s,new Map,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=i;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),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 rw(n){const e=new Zu,t=e.data;for(const[i,r]of Object.entries(n))t[i]=JSON.stringify(r);return e}function sw(n){if(n.type===hr.Put)return new lo({type:Er.PUT,presence:rw(n.presence)});if(n.type===hr.Clear)return new lo({type:Er.CLEAR});throw new v(w.ErrUnimplemented,"unimplemented type")}function ow(n){return new Zm({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function iO(n){return new Yl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ef(n.getActorID())})}function L(n){if(n)return new M({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ef(n.getActorID())})}function nO(n){switch(n){case Ae.Null:return F.NULL;case Ae.Boolean:return F.BOOLEAN;case Ae.Integer:return F.INTEGER;case Ae.Long:return F.LONG;case Ae.Double:return F.DOUBLE;case Ae.String:return F.STRING;case Ae.Bytes:return F.BYTES;case Ae.Date:return F.DATE;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function rO(n){switch(n){case Qi.IntegerCnt:return F.INTEGER_CNT;case Qi.LongCnt:return F.LONG_CNT;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function Th(n){if(n instanceof nt)return new Ot({type:F.JSON_OBJECT,createdAt:L(n.getCreatedAt()),value:OO(n)});if(n instanceof pt)return new Ot({type:F.JSON_ARRAY,createdAt:L(n.getCreatedAt()),value:Nw(n)});if(n instanceof Bt)return new Ot({type:F.TEXT,createdAt:L(n.getCreatedAt())});if(n instanceof pe)return new Ot({type:nO(n.getType()),createdAt:L(n.getCreatedAt()),value:n.toBytes()});if(n instanceof gt)return new Ot({type:rO(n.getType()),createdAt:L(n.getCreatedAt()),value:n.toBytes()});if(n instanceof qt)return new Ot({type:F.TREE,createdAt:L(n.getCreatedAt()),value:qw(n)});throw new v(w.ErrUnimplemented,"unimplemented element")}function aw(n){return new ao({createdAt:L(n.getCreatedAt()),offset:n.getOffset()})}function Ho(n){return new Bn({createdAt:L(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function Ko(n){return new Rr({parentId:Js(n.getParentID()),leftSiblingId:Js(n.getLeftSiblingID())})}function Js(n){return new ir({createdAt:L(n.getCreatedAt()),offset:n.getOffset()})}function sO(n){const e=new Vu;if(n instanceof Dr){const t=n,i=new Ka;i.parentCreatedAt=L(t.getParentCreatedAt()),i.key=t.getKey(),i.value=Th(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="set",e.body.value=i}else if(n instanceof Bo){const t=n,i=new el;i.parentCreatedAt=L(t.getParentCreatedAt()),i.prevCreatedAt=L(t.getPrevCreatedAt()),i.value=Th(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="add",e.body.value=i}else if(n instanceof Hn){const t=n,i=new tl;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 cr){const t=n,i=new il;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 qo){const t=n,i=new nl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=Ho(t.getFromPos()),i.to=Ho(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 Mo){const t=n,i=new rl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=Ho(t.getFromPos()),i.to=Ho(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 ds){const t=n,i=new sl;i.parentCreatedAt=L(t.getParentCreatedAt()),i.value=Th(t.getValue()),i.executedAt=L(t.getExecutedAt()),e.body.case="increase",e.body.value=i}else if(n instanceof Xo){const t=n,i=new ol,r=i.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=L(o);i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=Ko(t.getFromPos()),i.to=Ko(t.getToPos()),i.contents=pw(t.getContents()),i.splitLevel=t.getSplitLevel(),i.executedAt=L(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=i}else if(n instanceof En){const t=n,i=new al;i.parentCreatedAt=L(t.getParentCreatedAt()),i.from=Ko(t.getFromPos()),i.to=Ko(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 lw(n){const e=[];for(const t of n)e.push(sO(t));return e}function hw(n){const e=new Lm({id:iO(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=lw(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=sw(n.getPresenceChange())),e}function cw(n){const e=[];for(const t of n)e.push(hw(t));return e}function uw(n){const e=[];for(const t of n)e.push(new Vm({key:t.getStrKey(),element:Gu(t.getValue())}));return e}function fw(n){const e=[];for(const t of n)e.push(new pl({element:Gu(t.getValue())}));return e}function dw(n){const e=[];for(const t of n){const i=new Um;i.id=aw(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 ls;a.value=o.getValue(),a.updatedAt=L(o.getUpdatedAt()),r[o.getKey()]=a}e.push(i)}return e}function pw(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new gl({content:_u(t)}));return e}function gw(n){const e={};for(const t of n)e[t.getKey()]=new ls({value:t.getValue(),updatedAt:L(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function _u(n){if(!n)return[];const e=[];return Hl(n,(t,i)=>{const r=new Uu({id:Js(t.id),type:t.type,removedAt:L(t.removedAt),depth:i});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Js(t.insPrevID)),t.insNextID&&(r.insNextId=Js(t.insNextID)),t.attrs&&(r.attributes=gw(t.attrs)),e.push(r)}),e}function mw(n){const e=new rt;return e.body.case="jsonObject",e.body.value=new ll({nodes:uw(n.getRHT()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function oO(n){const e=new rt;return e.body.case="jsonArray",e.body.value=new hl({nodes:fw(n.getElements()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function Ow(n){const e=new rt;return e.body.case="primitive",e.body.value=new cl({type:nO(n.getType()),value:n.toBytes(),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function yw(n){const e=new rt;return e.body.case="text",e.body.value=new ul({nodes:dw(n.getRGATreeSplit()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function bw(n){const e=new rt;return e.body.case="counter",e.body.value=new fl({type:rO(n.getType()),value:n.toBytes(),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function aO(n){const e=new rt;return e.body.case="tree",e.body.value=new dl({nodes:_u(n.getRoot()),createdAt:L(n.getCreatedAt()),movedAt:L(n.getMovedAt()),removedAt:L(n.getRemovedAt())}),e}function Gu(n){if(n instanceof nt)return mw(n);if(n instanceof pt)return oO(n);if(n instanceof pe)return Ow(n);if(n instanceof Bt)return yw(n);if(n instanceof gt)return bw(n);if(n instanceof qt)return aO(n);throw new v(w.ErrUnimplemented,"unimplemented element")}function Sw(n){return new Un({documentKey:n.getDocumentKey(),checkpoint:ow(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:cw(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:L(n.getMinSyncedTicket())})}function Cd(n){const e=n.findDetails(q1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function lO(n){return Jn.of(n.clientSeq,BigInt(n.lamport),Ku(n.actorId),BigInt(n.serverSeq))}function V(n){if(n)return dt.of(BigInt(n.lamport),n.delimiter,Ku(n.actorId))}function Ju(n){const e={};return Object.entries(n.data).forEach(([t,i])=>{e[t]=JSON.parse(i)}),e}function ww(n){const e=n.type;if(e===Er.PUT){const t=Ju(n.presence);return{type:hr.Put,presence:t}}if(e===Er.CLEAR)return{type:hr.Clear};throw new v(w.ErrInvalidType,`unsupported type: ${e}`)}function vw(n){const e=new Map;return Object.entries(n).forEach(([t,i])=>{e.set(t,Ju(i))}),e}function hO(n){switch(n){case F.NULL:return Ae.Null;case F.BOOLEAN:return Ae.Boolean;case F.INTEGER:return Ae.Integer;case F.LONG:return Ae.Long;case F.DOUBLE:return Ae.Double;case F.STRING:return Ae.String;case F.BYTES:return Ae.Bytes;case F.DATE:return Ae.Date}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function yl(n){switch(n){case F.INTEGER_CNT:return Qi.IntegerCnt;case F.LONG_CNT:return Qi.LongCnt}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function Qh(n){switch(n.type){case F.JSON_OBJECT:return n.value?mO(n.value):nt.create(V(n.createdAt));case F.JSON_ARRAY:return n.value?Dw(n.value):pt.create(V(n.createdAt));case F.TEXT:return Bt.create(fs.create(),V(n.createdAt));case F.TREE:return Bw(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 pe.of(pe.valueFromBytes(hO(n.type),n.value),V(n.createdAt));case F.INTEGER_CNT:case F.LONG_CNT:return gt.create(yl(n.type),gt.valueFromBytes(yl(n.type),n.value),V(n.createdAt))}}function ea(n){return Gt.of(xi.of(V(n.createdAt),n.offset),n.relativeOffset)}function cO(n){return xi.of(V(n.createdAt),n.offset)}function kw(n){const e=fo.create(n.value);Object.entries(n.attributes).forEach(([i,r])=>{e.setAttr(i,r.value,V(r.updatedAt))});const t=rr.create(cO(n.id),e);return t.remove(V(n.removedAt)),t}function Zr(n){return zt.of(Ys(n.parentId),Ys(n.leftSiblingId))}function Ys(n){return Me.of(V(n.createdAt),n.offset)}function xw(n){if(!n.length)return;const e=[];return n.forEach(t=>{const i=Yu(t.content);e.push(i)}),e}function Yu(n){if(n.length===0)return;const e=[];for(const r of n)e.push(Qw(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(),qt.create(t,_t).getRoot()}function Tw(n){const e=qn.create();for(const[t,i]of Object.entries(n))e.setInternal(t,i.value,V(i.updatedAt),i.isRemoved);return e}function Qw(n){const e=Ys(n.id),t=ut.create(e,n.type),i=Object.entries(n.attributes);return t.isText?t.value=n.value:i.length&&(t.attrs=Tw(n.attributes)),n.insPrevId&&(t.insPrevID=Ys(n.insPrevId)),n.insNextId&&(t.insNextID=Ys(n.insNextId)),t.removedAt=V(n.removedAt),t}function uO(n){if(n.body.case==="set"){const e=n.body.value;return Dr.create(e.key,Qh(e.value),V(e.parentCreatedAt),V(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Bo.create(V(e.parentCreatedAt),V(e.prevCreatedAt),Qh(e.value),V(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Hn.create(V(e.parentCreatedAt),V(e.prevCreatedAt),V(e.createdAt),V(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return cr.create(V(e.parentCreatedAt),V(e.createdAt),V(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,V(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),qo.create(V(e.parentCreatedAt),ea(e.from),ea(e.to),t,e.content,i,V(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,V(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Mo.create(V(e.parentCreatedAt),ea(e.from),ea(e.to),t,i,V(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ds.create(V(e.parentCreatedAt),Qh(e.value),V(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,V(r))}),Xo.create(V(e.parentCreatedAt),Zr(e.from),Zr(e.to),xw(e.contents),e.splitLevel,t,V(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,V(o))}),(i==null?void 0:i.length)>0?En.createTreeRemoveStyleOperation(V(e.parentCreatedAt),Zr(e.from),Zr(e.to),r,i,V(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),En.create(V(e.parentCreatedAt),Zr(e.from),Zr(e.to),r,t,V(e.executedAt)))}else throw new v(w.ErrUnimplemented,"unimplemented operation")}}function Pw(n){const e=[];for(const t of n){const i=uO(t);i&&e.push(i)}return e}function fO(n){const e=[];for(const t of n)e.push(us.create({id:lO(t.id),operations:Pw(t.operations),presenceChange:t.presenceChange?ww(t.presenceChange):void 0,message:t.message}));return e}function Aw(n){return es.of(BigInt(n.serverSeq),n.clientSeq)}function $w(n){return Kl.create(n.documentKey,Aw(n.checkpoint),n.isRemoved,fO(n.changes),n.snapshot,V(n.minSyncedTicket))}function dO(n){const e=new ho;for(const i of n.nodes){const r=Hu(i.element);e.set(i.key,r,r.getPositionedAt())}const t=new nt(V(n.createdAt),e);return t.setMovedAt(V(n.movedAt)),t.setRemovedAt(V(n.removedAt)),t}function pO(n){const e=new uo;for(const i of n.nodes)e.insert(Hu(i.element));const t=new pt(V(n.createdAt),e);return t.setMovedAt(V(n.movedAt)),t.setRemovedAt(V(n.removedAt)),t}function Cw(n){const e=pe.of(pe.valueFromBytes(hO(n.type),n.value),V(n.createdAt));return e.setMovedAt(V(n.movedAt)),e.setRemovedAt(V(n.removedAt)),e}function Iw(n){const e=new fs;let t=e.getHead();for(const r of n.nodes){const s=e.insertAfter(t,kw(r));r.insPrevId&&s.setInsPrev(e.findNode(cO(r.insPrevId))),t=s}const i=new Bt(e,V(n.createdAt));return i.setMovedAt(V(n.movedAt)),i.setRemovedAt(V(n.removedAt)),i}function Rw(n){const e=gt.create(yl(n.type),gt.valueFromBytes(yl(n.type),n.value),V(n.createdAt));return e.setMovedAt(V(n.movedAt)),e.setRemovedAt(V(n.removedAt)),e}function gO(n){const e=Yu(n.nodes);return qt.create(e,V(n.createdAt))}function Hu(n){if(n.body.case==="jsonObject")return dO(n.body.value);if(n.body.case==="jsonArray")return pO(n.body.value);if(n.body.case==="primitive")return Cw(n.body.value);if(n.body.case==="text")return Iw(n.body.value);if(n.body.case==="counter")return Rw(n.body.value);if(n.body.case==="tree")return gO(n.body.value);throw new v(w.ErrUnimplemented,"unimplemented element")}function Ew(n){if(!n)return{root:nt.create(_t),presences:new Map};const e=fc.fromBinary(n);return{root:Hu(e.root),presences:vw(e.presences)}}function mO(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return dO(e.body.value)}function OO(n){return Gu(n).toBinary()}function Dw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return pO(e.body.value)}function Nw(n){return oO(n).toBinary()}function Bw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return gO(e.body.value)}function qw(n){return aO(n).toBinary()}function yO(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function Ku(n){return yO(n)}function bO(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ef(n){return bO(n)}function Mw(n){const e=Yl.fromBinary(n);return lO(e)}function Xw(n){const e=Vu.fromBinary(n);return uO(e)}const $e={fromPresence:Ju,toChangePack:Sw,fromChangePack:$w,fromChanges:fO,toTreeNodes:_u,fromTreeNodes:Yu,objectToBytes:OO,bytesToObject:mO,bytesToSnapshot:Ew,bytesToHex:yO,hexToBytes:bO,toHexString:Ku,toUint8Array:ef,toOperation:sO,toChangeID:iO,PbChangeID:Yl,bytesToChangeID:Mw,bytesToOperation:Xw};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 wr=3;function SO(n){wr=n}const U={trivial:(...n)=>{wr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{wr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{wr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{wr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{wr>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=>wr<=n};function wO(){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 Lw{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===Ba.RealtimeSyncOff?!1:this.syncMode===Ba.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ba.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 Ph=()=>{};class Vw{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=Ph),r.error===void 0&&(r.error=Ph),r.complete===void 0&&(r.complete=Ph);const s=wO(),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){U.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 Gr{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=jm,this.root=t,this.operations=[],this.previousPresence=Zt(i),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,i,r){return new Gr(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 us.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 po{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 Bt||t instanceof qt)for(const i of t.getGCPairs())this.registerGCPair(i);return!1})}static create(){return new po(nt.create(_t))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const 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 nr&&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 nr&&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 nr&&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 po(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const i of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(i);r.element.getRemovedAt()&&e.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,i]of this.gcPairMap){const r=i.child.getRemovedAt();r!==void 0&&e.compare(r)>=0&&(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()}}function vO(n,e){const t=new go(n);return new Proxy(e,t.getHandlers())}class go{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]=${JSON.stringify(r)}`),go.setInternal(e,t,i,r),!0),get:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),i==="getID"?()=>t.getCreatedAt():i==="toJSON"||i==="toString"?()=>t.toJSON():i==="toJS"?()=>t.toJS():i==="toJSForTest"?()=>t.toJSForTest():vr(e,t.get(i))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),go.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=bl(e,r,s),a=t.set(i,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Dr.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=bl(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(cr.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function Zw(n,e){const t=new me(n,e);return new Proxy(e,t.getHandlers())}function Ww(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function jw(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){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 Fn(e,a)}:r==="getElementByIndex"?o=>{const a=i.get(o);return Fn(e,a)}:r==="getLast"?()=>Fn(e,i.getLast()):r==="deleteByID"?o=>{const a=me.deleteInternalByID(e,i,o);return Fn(e,a)}:r==="insertAfter"?(o,a)=>{const l=me.insertAfterInternal(e,i,o,a);return Fn(e,l)}:r==="insertBefore"?(o,a)=>{const l=me.insertBeforeInternal(e,i,o,a);return Fn(e,l)}:r==="moveBefore"?(o,a)=>{me.moveBeforeInternal(e,i,o,a)}:r==="moveAfter"?(o,a)=>{me.moveAfterInternal(e,i,o,a)}:r==="moveFront"?o=>{me.moveFrontInternal(e,i,o)}:r==="moveLast"?o=>{me.moveLastInternal(e,i,o)}:Ww(r)?vr(e,i.get(Number(r))):r==="push"?o=>me.pushInternal(e,i,o):r==="splice"?(o,a,...l)=>me.splice(e,i,o,a,...l):r==="length"?i.length:typeof r=="symbol"&&r===Symbol.iterator?me.iteratorInternal.bind(this,e,i):r==="includes"?(o,a)=>me.includes(e,i,o,a):r==="indexOf"?(o,a)=>me.indexOf(e,i,o,a):r==="lastIndexOf"?(o,a)=>me.lastIndexOf(e,i,o,a):r==="toJSForTest"?()=>i.toJSForTest():r==="toTestString"?()=>me.toTestString(i):typeof r=="string"&&jw(r)?(...o)=>{const a=Array.from(i).map(l=>vr(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(i,r,s),deleteProperty:(i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`array[${r}]`),me.deleteInternalByIndex(e,i,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const i of t)yield Fn(e,i)}static buildArrayElements(e,t){const i=[];for(const r of t){const s=e.issueTimeTicket(),o=bl(e,r,s);i.push(o)}return i}static pushInternal(e,t,i){return me.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(Hn.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,i,r){const s=e.issueTimeTicket();t.moveAfter(i,r,s),e.push(Hn.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(Hn.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(Hn.create(t.getCreatedAt(),s,i,r))}static insertAfterInternal(e,t,i,r){const s=e.issueTimeTicket(),o=bl(e,r,s);return t.insertAfter(i,o),e.registerElement(o,t),e.push(Bo.create(t.getCreatedAt(),i,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,i,r){return me.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(cr.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(cr.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(pe.isSupport(i))return Array.from(t).map(h=>vr(e,h)).includes(i,o);for(let l=o;l=s)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>vr(e,h)).indexOf(i,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>vr(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 eh=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);U.isEnabled(Ge.Debug)&&U.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${i}`);const o=r?hs(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 qo(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);U.isEnabled(Ge.Debug)&&U.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(i)}`);const s=hs(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 Mo(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([Gt.fromStruct(e[0]),Gt.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 th{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=pe.of(e,t);if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`);return this.counter.increase(i),this.context.push(ds.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 tf(n,e,t){const{type:i}=n,r=t.issueTimeTicket();if(i===Rn){kO(n);const{value:s}=n,o=ut.create(Me.of(r,0),i,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Wm(o)){const h=hs(o);a=new qn;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(Me.of(r,0),i,void 0,a);e.append(l);for(const h of s)tf(h,l,t)}}function Fw(n,e){const{type:t}=e,i=n.issueTimeTicket();let r;if(e.type===Rn){const{value:s}=e;r=ut.create(Me.of(i,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Wm(o)){const l=hs(o);a=new qn;for(const[h,c]of Object.entries(l))a.set(h,c,i)}r=ut.create(Me.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)tf(l,r,n)}return r}function kO(n){if(!n.value.length)throw new v(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function Id(n){if(!n.length)return!0;if(n[0].type===Rn)for(const t of n){const{type:i}=t;if(i!==Rn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together");kO(t)}else for(const t of n){const{type:i}=t;if(i===Rn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let ih=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(Me.of(e.issueTimeTicket(),0),z1);const t=ut.create(Me.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const i of this.initialRoot.children)tf(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?hs(t):void 0,[a]=this.tree.style([i,r],o,s);this.context.push(En.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?hs(i):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(En.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(En.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,i,o))}editInternal(e,t,i,r=0){var h;if(i.length!==0&&i[0]&&(Id(i),i[0].type!==Rn))for(const c of i){const{children:u=[]}=c;Id(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=i[0])==null?void 0:h.type)===Rn){let c="";for(const u of i){const{value:f}=u;c+=f}o.push(ut.create(Me.of(this.context.issueTimeTicket(),0),Rn,c))}else o=i.map(c=>c&&Fw(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(Xo.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=[zt.fromStruct(e[0]),zt.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=[zt.fromStruct(e[0]),zt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Rd(n,e){return vO(n,e)}function Fn(n,e){if(e){if(e instanceof pe)return e;if(e instanceof nt)return vO(n,e);if(e instanceof pt)return Zw(n,e);if(e instanceof Bt)return new eh(n,e);if(e instanceof gt){const t=new th(Qi.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof qt){const t=new ih;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function vr(n,e){const t=Fn(n,e);return t instanceof pe?t.getValue():t}function bl(n,e,t){let i;if(pe.isSupport(e))i=pe.of(e,t);else if(Array.isArray(e))i=pt.create(t,me.buildArrayElements(n,e));else if(typeof e=="object")e instanceof eh?(i=Bt.create(fs.create(),t),e.initialize(n,i)):e instanceof th?(i=gt.create(e.getValueType(),e.getValue(),t),e.initialize(n,i)):e instanceof ih?(i=qt.create(e.buildRoot(n),t),e.initialize(n,i)):i=nt.create(t,go.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return i}const Ed=50;class zw{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Ed&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Ed&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const _w="yorkie-devtools-panel",Gw="yorkie-devtools-sdk";let jr="disconnected";const Dd=new Map,Na=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Na);function ta(n,e){(e!=null&&e.force||jr!=="disconnected")&&window.postMessage({source:Gw,...n},"*")}function Jw(n){if(!n.isEnableDevtools()||typeof window>"u"||Dd.has(n.getKey()))return;Na.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(i=>i.type!==_e.StatusChanged&&i.type!==_e.Snapshot&&i.type!==_e.LocalChange&&i.type!==_e.RemoteChange&&i.type!==_e.Initialized&&i.type!==_e.Watched&&i.type!==_e.Unwatched&&i.type!==_e.PresenceChanged)||(Na.get(n.getKey()).push(t),jr==="synced"&&ta({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Dd.set(n.getKey(),[e]),ta({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==_w)return;switch(t.data.msg){case"devtools::connect":if(jr!=="disconnected")break;jr="connected",ta({msg:"doc::available",docKey:n.getKey()}),U.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":jr="disconnected",U.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":jr="synced",ta({msg:"doc::sync::full",docKey:n.getKey(),events:Na.get(n.getKey())}),U.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var zn=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(zn||{}),_e=(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))(_e||{}),mo=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(mo||{}),Mc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Mc||{});class xO{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=po.create(),this.changeID=tw,this.checkpoint=iw,this.localChanges=[],this.eventStream=Uw(i=>{this.eventStreamObserver=i}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new zw,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Jw(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=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(i)||{},t);try{const s=Rd(r,this.clone.root.getObject());this.presences.has(i)||this.clone.presences.set(i,{}),this.isUpdating=!0,e(s,new xh(r,this.clone.presences.get(i)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){U.isEnabled(Ge.Trivial)&&U.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),U.isEnabled(Ge.Trivial)&&U.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==="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])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),U.isEnabled(Ge.Trivial)&&U.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:Zt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Kl.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Rd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:i,presences:r}=$e.bytesToSnapshot(t);this.root=new po(i),this.presences=r,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{snapshot:this.isEnableDevtools()?$e.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){U.isEnabled(Ge.Debug)&&U.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),U.isEnabled(Ge.Trivial)&&U.trivial(e.map(i=>`${i.getID().toTestString()} ${i.toTestString()}`).join(` -`));for(const i of e)this.applyChange(i,t);U.isEnabled(Ge.Debug)&&U.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 hr.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 hr.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.syncLamport(e.getID().getLamport()),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===Ir.DOCUMENT_WATCHED)this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}});else if(t===Ir.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===Ir.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(Wu),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}=e.value;if(!t)return;this.applySnapshot(BigInt(i),$e.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=us.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?Zt(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?Zt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Zt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Zt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Zt(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}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=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Jt)){new xh(t,Zt(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=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Jt)){new xh(t,Zt(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])}}function Yw(n,e){return t=>async i=>(n&&i.header.set("x-api-key",n),e&&i.header.set("authorization",e),await t(i))}const Hw="yorkie-js-sdk",Kw="0.5.1",ev="Yorkie JS SDK",tv="./src/yorkie.ts",iv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},nv=["dist"],rv={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"},sv={node:">=18.0.0",npm:">=7.1.0"},ov={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},av={name:"hackerwins",email:"susukang98@gmail.com"},lv="Apache-2.0",hv={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},cv="https://github.com/yorkie-team/yorkie-js-sdk#readme",uv={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},fv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Nd={name:Hw,version:Kw,description:ev,main:tv,publishConfig:iv,files:nv,scripts:rv,engines:sv,repository:ov,author:av,license:lv,bugs:hv,homepage:cv,devDependencies:uv,dependencies:fv};function dv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Nd.name+"/"+Nd.version),await n(e))}const pv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ba=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ba||{});const ia={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ah={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class TO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ia,this.key=t.key?t.key:wO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ia.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ia.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ia.retrySyncLoopDelay,this.rpcClient=d1(B1,N1({baseUrl:e,interceptors:[Yw(t.apiKey,t.token),dv()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),U.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw U.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),U.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw U.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==zn.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:$e.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=$e.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===zn.Removed||(e.applyStatus(zn.Attached),this.attachmentMap.set(e.getKey(),new Lw(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),U.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw U.error(`[AD] c:"${this.getKey()}" err :`,s),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:$e.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=$e.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==zn.Removed&&e.applyStatus(zn.Detached),this.detachInternal(e.getKey()),U.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw U.error(`[DD] c:"${this.getKey()}" err :`,r),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(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),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(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),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=$e.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=$e.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),U.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw U.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,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(!pv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Ah.maxRetries,a=Ah.maxBackoff;let l=0;const h=u=>Math.min(Ah.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(()=>{U.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(U.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),U.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw U.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){U.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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(i=>{U.error(`[SL] c:"${this.getKey()}" sync failed:`,i),this.handleConnectError(i)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};U.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:_e.ConnectionChanged,value:mo.Connected}]),U.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:_e.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:_e.ConnectionChanged,value:mo.Disconnected}]),U.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?i():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Ir.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(zn.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:$e.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=$e.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:_e.SyncStatusChanged,value:Mc.Synced}]),i.getStatus()===zn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return U.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(o=>{throw i.publish([{type:_e.SyncStatusChanged,value:Mc.SyncFailed}]),U.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof xe?e.code===ie.Canceled||e.code===ie.Unknown||e.code===ie.ResourceExhausted||e.code===ie.Unavailable?!0:((Cd(e)===w.ErrClientNotActivated||Cd(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{U.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const $h={Client:TO,Document:xO,Primitive:pe,Text:eh,Counter:th,Tree:ih,LogLevel:Ge,setLogLevel:SO,IntType:Qi.IntegerCnt,LongType:Qi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:TO,Document:xO,Primitive:pe,Text:eh,Counter:th,Tree:ih,LogLevel:Ge,setLogLevel:SO,IntType:Qi.IntegerCnt,LongType:Qi.LongCnt});class K{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]=ps(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),ci.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]=ps(this,e,t);let i=[];return this.decompose(e,t,i,0),ci.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 Hs(this),s=new Hs(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 Hs(this,e)}iterRange(e,t=this.length){return new QO(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 PO(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]?K.empty:e.length<=32?new Se(e):ci.from(Se.split(e,[]))}}class Se extends K{constructor(e,t=gv(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 mv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new Se(Bd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=qa(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new Se(a,o.length+s.length));else{let l=a.length>>1;i.push(new Se(a.slice(0,l)),new Se(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof Se))return super.replace(e,t,i);[e,t]=ps(this,e,t);let r=qa(this.text,qa(i.text,Bd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new Se(r,s):ci.from(Se.split(r,[]),s)}sliceString(e,t=this.length,i=` +`));for(const i of e)this.applyChange(i,t);U.isEnabled(Ge.Debug)&&U.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 hr.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 hr.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.syncLamport(e.getID().getLamport()),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===Ir.DOCUMENT_WATCHED)this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}});else if(t===Ir.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===Ir.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(Wu),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}=e.value;if(!t)return;this.applySnapshot(BigInt(i),$e.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=us.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?Zt(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?Zt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Zt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Zt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Zt(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}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=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Jt)){new xh(t,Zt(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=Gr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Jt)){new xh(t,Zt(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])}}function Yw(n,e){return t=>async i=>(n&&i.header.set("x-api-key",n),e&&i.header.set("authorization",e),await t(i))}const Hw="yorkie-js-sdk",Kw="0.5.2",ev="Yorkie JS SDK",tv="./src/yorkie.ts",iv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},nv=["dist"],rv={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"},sv={node:">=18.0.0",npm:">=7.1.0"},ov={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},av={name:"hackerwins",email:"susukang98@gmail.com"},lv="Apache-2.0",hv={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},cv="https://github.com/yorkie-team/yorkie-js-sdk#readme",uv={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},fv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Nd={name:Hw,version:Kw,description:ev,main:tv,publishConfig:iv,files:nv,scripts:rv,engines:sv,repository:ov,author:av,license:lv,bugs:hv,homepage:cv,devDependencies:uv,dependencies:fv};function dv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Nd.name+"/"+Nd.version),await n(e))}const pv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ba=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ba||{});const ia={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ah={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class TO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ia,this.key=t.key?t.key:wO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ia.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ia.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ia.retrySyncLoopDelay,this.rpcClient=d1(B1,N1({baseUrl:e,interceptors:[Yw(t.apiKey,t.token),dv()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),U.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw U.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),U.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw U.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==zn.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:$e.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=$e.fromChangePack(s.changePack);return e.applyChangePack(o),e.getStatus()===zn.Removed||(e.applyStatus(zn.Attached),this.attachmentMap.set(e.getKey(),new Lw(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),U.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(s=>{throw U.error(`[AD] c:"${this.getKey()}" err :`,s),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:$e.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=$e.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==zn.Removed&&e.applyStatus(zn.Detached),this.detachInternal(e.getKey()),U.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw U.error(`[DD] c:"${this.getKey()}" err :`,r),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(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),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(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),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=$e.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=$e.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),U.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw U.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,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(!pv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Ah.maxRetries,a=Ah.maxBackoff;let l=0;const h=u=>Math.min(Ah.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(()=>{U.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(U.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),U.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw U.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){U.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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(i=>{U.error(`[SL] c:"${this.getKey()}" sync failed:`,i),this.handleConnectError(i)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};U.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:_e.ConnectionChanged,value:mo.Connected}]),U.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:_e.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:_e.ConnectionChanged,value:mo.Disconnected}]),U.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?i():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Ir.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(zn.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:$e.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=$e.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:_e.SyncStatusChanged,value:Mc.Synced}]),i.getStatus()===zn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return U.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(o=>{throw i.publish([{type:_e.SyncStatusChanged,value:Mc.SyncFailed}]),U.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof xe?e.code===ie.Canceled||e.code===ie.Unknown||e.code===ie.ResourceExhausted||e.code===ie.Unavailable?!0:((Cd(e)===w.ErrClientNotActivated||Cd(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{U.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const $h={Client:TO,Document:xO,Primitive:pe,Text:eh,Counter:th,Tree:ih,LogLevel:Ge,setLogLevel:SO,IntType:Qi.IntegerCnt,LongType:Qi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:TO,Document:xO,Primitive:pe,Text:eh,Counter:th,Tree:ih,LogLevel:Ge,setLogLevel:SO,IntType:Qi.IntegerCnt,LongType:Qi.LongCnt});class K{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]=ps(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),ci.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]=ps(this,e,t);let i=[];return this.decompose(e,t,i,0),ci.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 Hs(this),s=new Hs(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 Hs(this,e)}iterRange(e,t=this.length){return new QO(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 PO(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]?K.empty:e.length<=32?new Se(e):ci.from(Se.split(e,[]))}}class Se extends K{constructor(e,t=gv(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 mv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new Se(Bd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=qa(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new Se(a,o.length+s.length));else{let l=a.length>>1;i.push(new Se(a.slice(0,l)),new Se(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof Se))return super.replace(e,t,i);[e,t]=ps(this,e,t);let r=qa(this.text,qa(i.text,Bd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new Se(r,s):ci.from(Se.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ps(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 Se(i,r)),i=[],r=-1);return r>-1&&t.push(new Se(i,r)),t}}class ci extends K{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]=ps(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 ci(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]=ps(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 ci))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 Se(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 ci)for(let y of p.children)u(y);else p.lines>o&&(l>o||!l)?(f(),a.push(p)):p instanceof Se&&l&&(g=c[c.length-1])instanceof Se&&p.lines+g.lines<=32?(l+=p.lines,h+=p.length+1,c[c.length-1]=new Se(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]:ci.from(c,h)),h=-1,l=c.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new ci(a,t)}}K.empty=new Se([""],0);function gv(n){let e=-1;for(let t of n)e+=t.length+1;return e}function qa(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 Se?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 Se?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 Se){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 Se?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 QO{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Hs(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 PO{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"&&(K.prototype[Symbol.iterator]=function(){return this.iter()},Hs.prototype[Symbol.iterator]=QO.prototype[Symbol.iterator]=PO.prototype[Symbol.iterator]=function(){return this});let mv=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 ps(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}let ts="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 ts[e-1]<=n;return!1}function qd(n){return n>=127462&&n<=127487}const Md=8205;function We(n,e,t=!0,i=!0){return(t?AO:yv)(n,e,i)}function AO(n,e,t){if(e==n.length)return e;e&&$O(n.charCodeAt(e))&&CO(n.charCodeAt(e-1))&&e--;let i=Ne(n,e);for(e+=lt(i);e=0&&qd(Ne(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function yv(n,e,t){for(;e>0;){let i=AO(n,e-2,t);if(i=56320&&n<57344}function CO(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!CO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return $O(i)?(t-55296<<10)+(i-56320)+65536:t}function nf(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 Xc=/\r\n?|\n/;var qe=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(qe||(qe={}));class Ti{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(i!=qe.Simple&&h>=e&&(i==qe.TrackDel&&re||i==qe.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 Ti(e)}static create(e){return new Ti(e)}}class Ce extends Ti{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 Lc(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Vc(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&&Kn(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"?K.of(p.split(i||Xc)):p:K.empty,y=g.length;if(u==f&&y==0)return;uo&&Ve(r,u-o,-1),Ve(r,f-u,y),Kn(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 Kn(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 Vc(n,e,t,i=!1){let r=[],s=i?[]:null,o=new Oo(n),a=new Oo(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Ve(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 Oo{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?K.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?K.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 Ar{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 Ar(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.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 P.range(e.anchor,e.head)}static create(e,t,i){return new Ar(e,t,i)}}class P{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:P.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 P(e.ranges.map(t=>Ar.fromJSON(t)),e.main)}static single(e,t=e){return new P([P.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?P.range(l,a):P.range(a,l))}}return new P(e,t)}}function RO(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let rf=0;class B{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=rf++,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:sf),!!e.static,e.enables)}of(e){return new Ma([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ma(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Ma(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function sf(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Ma{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=rf++}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)||Uc(u,c)){let p=i(u);if(a?!Xd(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 y=wl(f,g);if(this.dependencies.every(O=>O instanceof B?f.facet(O)===u.facet(O):O instanceof Re?f.field(O,!1)==u.field(O,!1):!0)||(a?Xd(p=i(u),y,r):r(p=i(u),y)))return u.values[o]=y,0}else p=i(u);return u.values[o]=p,1}}}}function Xd(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(Ld).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,Ld.of({field:this,create:e})]}get extension(){return this}}const xr={lowest:4,low:3,default:2,high:1,highest:0};function Rs(n){return e=>new EO(e,n)}const gr={highest:Rs(xr.highest),high:Rs(xr.high),default:Rs(xr.default),low:Rs(xr.low),lowest:Rs(xr.lowest)};class EO{constructor(e,t){this.inner=e,this.prec=t}}class nh{of(e){return new Zc(this,e)}reconfigure(e){return nh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Zc{constructor(e,t){this.compartment=e,this.inner=t}}class Sl{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 Sv(e,t,o))f instanceof Re?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,y=c&&c[f]||[];if(p.every(O=>O.type==0))if(a[g.id]=l.length<<1|1,sf(y,p))l.push(i.facet(g));else{let O=g.combine(p.map(S=>S.value));l.push(i&&g.compare(O,i.facet(g))?i.facet(g):O)}else{for(let O of p)O.type==0?(a[O.id]=l.length<<1|1,l.push(O.value)):(a[O.id]=h.length<<1,h.push(S=>O.dynamicSlot(S)));a[g.id]=h.length<<1,h.push(O=>bv(O,g,p))}}let u=h.map(f=>f(a));return new Sl(e,o,u,a,l,s)}}function Sv(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 Zc&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof Zc){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 EO)s(o.inner,o.prec);else if(o instanceof Re)i[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Ma)i[a].push(o),o.facet.extensions&&s(o.facet.extensions,xr.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,xr.default),i.reduce((o,a)=>o.concat(a))}function Ks(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 wl(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const DO=B.define(),Wc=B.define({combine:n=>n.some(e=>e),static:!0}),NO=B.define({combine:n=>n.length?n[0]:void 0,static:!0}),BO=B.define(),qO=B.define(),MO=B.define(),XO=B.define({combine:n=>n.length?n[0]:!1});class Zn{constructor(e,t){this.type=e,this.value=t}static define(){return new wv}}class wv{of(e){return new Zn(this,e)}}class vv{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{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 z(this.type,t)}is(e){return this.type==e}static define(e={}){return new vv(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}}z.reconfigure=z.define();z.appendConfig=z.define();class ye{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&&RO(i,t.newLength),s.some(a=>a.type==ye.time)||(this.annotations=s.concat(ye.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ye(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(ye.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ye.time=Zn.define();ye.userEvent=Zn.define();ye.addToHistory=Zn.define();ye.remote=Zn.define();function kv(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 ye?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ye?n=s[0]:n=VO(e,is(s),!1)}return n}function Tv(n){let e=n.startState,t=e.facet(MO),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=LO(i,jc(e,s,n.changes.newLength),!0))}return i==n?n:ye.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const Qv=[];function is(n){return n==null?Qv:Array.isArray(n)?n:[n]}var fe=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(fe||(fe={}));const Pv=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Fc;try{Fc=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Av(n){if(Fc)return Fc.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||Pv.test(t)))return!0}return!1}function $v(n){return e=>{if(!/\S/.test(e))return fe.Space;if(Av(e))return fe.Word;for(let t=0;t-1)return fe.Word;return fe.Other}}class H{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(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=is(i).concat(a.value));let s;t?s=e.startState.values.slice():(t=Sl.resolve(i,r,this),s=new H(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(Wc)?e.newSelection:e.newSelection.asSingle();new H(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:P.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=is(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return H.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=Sl.resolve(e.extensions||[],new Map),i=e.doc instanceof K?e.doc:K.of((e.doc||"").split(t.staticFacet(H.lineSeparator)||Xc)),r=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return RO(r,i.length),t.staticFacet(Wc)||(r=r.asSingle()),new H(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(H.tabSize)}get lineBreak(){return this.facet(H.lineSeparator)||` diff --git a/examples/vanilla-codemirror6/index.html b/examples/vanilla-codemirror6/index.html index ac6451497..41f8dcfe1 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-CKJvWhky.js b/examples/vanilla-quill/assets/index-DYVWARJt.js similarity index 99% rename from examples/vanilla-quill/assets/index-CKJvWhky.js rename to examples/vanilla-quill/assets/index-DYVWARJt.js index 7c8676f71..ea7b3cb0b 100644 --- a/examples/vanilla-quill/assets/index-CKJvWhky.js +++ b/examples/vanilla-quill/assets/index-DYVWARJt.js @@ -20,7 +20,7 @@ var ju=Object.defineProperty;var Uu=(i,t,e)=>t in i?ju(i,t,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var Ht=null;try{Ht=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 Ke(i,t,e){this.low=i|0,this.high=t|0,this.unsigned=!!e}Ke.prototype.__isLong__;Object.defineProperty(Ke.prototype,"__isLong__",{value:!0});function yt(i){return(i&&i.__isLong__)===!0}function ul(i){var t=Math.clz32(i&-i);return i?31-t:t}Ke.isLong=yt;var cl={},fl={};function _i(i,t){var e,n,r;return t?(i>>>=0,(r=0<=i&&i<256)&&(n=fl[i],n)?n:(e=He(i,0,!0),r&&(fl[i]=e),e)):(i|=0,(r=-128<=i&&i<128)&&(n=cl[i],n)?n:(e=He(i,i<0?-1:0,!1),r&&(cl[i]=e),e))}Ke.fromInt=_i;function Vt(i,t){if(isNaN(i))return t?Hr:sn;if(t){if(i<0)return Hr;if(i>=iu)return au}else{if(i<=-dl)return Et;if(i+1>=dl)return su}return i<0?Vt(-i,t).neg():He(i%Wi|0,i/Wi|0,t)}Ke.fromNumber=Vt;function He(i,t,e){return new Ke(i,t,e)}Ke.fromBits=He;var ys=Math.pow;function wa(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?Hr:sn;if(e=e||10,e<2||360)throw Error("interior hyphen");if(n===0)return wa(i.substring(1),t,e).neg();for(var r=Vt(ys(e,8)),o=sn,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Wi+(this.low>>>0):this.high*Wi+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,v=m.toString(t);if(s=c,s.isZero())return v+u;for(;v.length<6;)v="0"+v;u=""+v+u}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Et)?64:this.neg().getNumBitsAbs();for(var 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=fn(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=fn(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=fn(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,v=0,d=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,d+=l>>>16,l&=65535,d+=n+u,v+=d>>>16,d&=65535,v+=e+s,v&=65535,He(l<<16|a,v<<16|d,this.unsigned)};he.subtract=function(t){return yt(t)||(t=fn(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(yt(t)||(t=fn(t)),Ht){var e=Ht.mul(this.low,this.high,t.low,t.high);return He(e,Ht.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Hr:sn;if(this.eq(Et))return t.isOdd()?Et:sn;if(t.eq(Et))return this.isOdd()?Et:sn;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(gl)&&t.lt(gl))return Vt(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,v=t.low&65535,d=0,l=0,a=0,p=0;return p+=s*v,a+=p>>>16,p&=65535,a+=o*v,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*v,d+=l>>>16,l&=65535,l+=o*m,d+=l>>>16,l&=65535,l+=s*c,d+=l>>>16,l&=65535,d+=n*v+r*m+o*c+s*u,d&=65535,He(a<<16|p,d<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(yt(t)||(t=fn(t)),t.isZero())throw Error("division by zero");if(Ht){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Ht.div_u:Ht.div_s)(this.low,this.high,t.low,t.high);return He(e,Ht.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Hr:sn;var n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Hr;if(t.gt(this.shru(1)))return ou;o=Hr}else{if(this.eq(Et)){if(t.eq(ji)||t.eq(ca))return Et;if(t.eq(Et))return ji;var s=this.shr(1);return n=s.div(t).shl(1),n.eq(sn)?t.isNegative()?ji:ca:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o)}else if(t.eq(Et))return this.unsigned?Hr:sn;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=sn}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:ys(2,u-48),m=Vt(n),v=m.mul(t);v.isNegative()||v.gt(r);)n-=c,m=Vt(n,this.unsigned),v=m.mul(t);m.isZero()&&(m=ji),o=o.add(m),r=r.sub(v)}return o};he.div=he.divide;he.modulo=function(t){if(yt(t)||(t=fn(t)),Ht){var e=(this.unsigned?Ht.rem_u:Ht.rem_s)(this.low,this.high,t.low,t.high);return He(e,Ht.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return He(~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?ul(this.low):ul(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return yt(t)||(t=fn(t)),He(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return yt(t)||(t=fn(t)),He(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return yt(t)||(t=fn(t)),He(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?He(this.low<>>32-t,this.unsigned):He(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):He(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?He(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?He(this.high,0,this.unsigned):He(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?He(this.high,this.low,this.unsigned):t<32?(e=32-t,He(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,He(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?He(this.high,this.low,this.unsigned):t<32?(e=32-t,He(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,He(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?He(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:He(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]};Ke.fromBytes=function(t,e,n){return n?Ke.fromBytesLE(t,e):Ke.fromBytesBE(t,e)};Ke.fromBytesLE=function(t,e){return new Ke(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ke.fromBytesBE=function(t,e){return new Ke(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var ct=(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))(ct||{});class et extends To{constructor(e,n){super(n);T(this,"valueType");T(this,"value");this.valueType=et.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,n){return new et(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 Ke.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Ke.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${qn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=et.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 Ke)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return et.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=Ke.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class vs extends ru{constructor(e){super(e);T(this,"prev");T(this,"next");this.value=e}static createAfter(e,n){const r=new vs(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 yo{constructor(){T(this,"dummyHead");T(this,"last");T(this,"nodeMapByIndex");T(this,"nodeMapByCreatedAt");const t=et.of(0,ln);t.setRemovedAt(ln),this.dummyHead=new vs(t),this.last=this.dummyHead,this.nodeMapByIndex=new mo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new yo}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=vs.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 Rt extends fi{constructor(e,n){super(e);T(this,"elements");this.elements=n}static create(e,n){if(!n)return new Rt(e,yo.create());const r=yo.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(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 fi&&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({...a,value:a.value?{attributes:Ji(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,v,[c,c]]}setStyle(e,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),v=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):ln:ao;if(a.canStyle(r,b)){const w=v.get(p),y=a.getCreatedAt();(!w||y.after(w))&&v.set(p,y),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:Ji(n)}});for(const[w,y]of Object.entries(n)){const[h]=a.getValue().setAttr(w,y,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[v,l,c]}indexRangeToPosRange(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:Ji(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Wt(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 Eo extends cn{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 Eo(e,n,r,o,s,u,c)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Wt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,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 xo extends cn{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 xo(e,n,r,o,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Wt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)e.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,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 wf=2,Af="root",Vr="text";function ro(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===Vr}get paddedSize(){return this.size+(this.isText?0:wf)}isAncestorOf(t){return Sf(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 Sf(i,t){if(i===t)return!1;for(;t.parent;){if(t.parent===i)return!0;t=t.parent}return!1}var lt=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(lt||{});function lu(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),lu(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function uu(i,t,e=0){for(const n of i.children)uu(n,t,e+1);t(i,e)}function Ss(i,t,e=0){for(const n of i._children)Ss(n,t,e+1);t(i,e)}function fa(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 fa(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 fa(o,t-r-1,e);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function cu(i){return i.isText||i.children.length===0?i:cu(i.children[0])}function Ef(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 Of(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 an{constructor(t,e){T(this,"parentID");T(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new an(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],an.of(n.id,pt.of(r.getCreatedAt(),r.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return an.of(pt.of(Lt.fromStruct(t.parentID.createdAt),t.parentID.offset),pt.of(Lt.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(Lt.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){return!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,n){this.attrs||(this.attrs=new Yr);const r=new Array;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 ha(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(ha)};return i.attrs&&(t.attributes=Ji((e=i.attrs)==null?void 0:e.toObject())),t}function Aa(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()}="${qn(e.getValue())}"`}).join(" ")),`<${i.type}${t}>${i.children.map(e=>Aa(e)).join("")}`}function hu(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(hu),size:i.size,isRemoved:i.isRemoved}}class Gt extends To{constructor(e,n){super(n);T(this,"indexTree");T(this,"nodeMapByID");this.indexTree=new xf(e),this.nodeMapByID=new fu(pt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(e,n){return new Gt(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,v=u?0:m.indexOf(s)+1;for(let d=v;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):ln:ao;if(p.canStyle(r,w)&&n){const y=l.get(b),h=p.getCreatedAt();(!y||h.after(y))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((E,[,O])=>(O&&(E[O.getKey()]=d[O.getKey()]),E),{}),A=p.parent,S=p.prevSibling||p.parent;Object.keys(f).length>0&&v.push({type:"style",from:this.toIndex(A,S),to:this.toIndex(p,p),fromPath:this.toPath(A,S),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[E]of g)E&&a.push({parent:p,child:E})}}),[l,a,v]}removeStyle(e,n,r,o){const[s,u]=this.findNodesAndSplitText(e[0],r),[c,m]=this.findNodesAndSplitText(e[1],r),v=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):ln:ao;if(a.canStyle(r,b)&&n){const w=d.get(p),y=a.getCreatedAt();(!w||y.after(w))&&d.set(p,y),a.attrs||(a.attrs=new Yr);for(const f of n){const A=a.attrs.remove(f,r);for(const S of A)l.push({parent:a,child:S})}const h=a.parent,g=a.prevSibling||a.parent;v.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,v]}edit(e,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(e[0],o),[v,d]=this.findNodesAndSplitText(e[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],y=new Map;this.traverseInPosRange(c,m,v,d,([f,A],S)=>{if(A===lt.Start&&!S)for(const P of f.children)w.push(P);const E=f.getCreatedAt().getActorID(),O=u?u.has(E)?u.get(E):ln:ao;if(f.canDelete(o,O)||p.includes(f.parent)){const P=y.get(E),k=f.getCreatedAt();(!P||k.after(P))&&y.set(E,k),(A===lt.Text||A===lt.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,S=m;for(;f{c.isRemoved&&(E.remove(o),g.push({parent:this,child:E})),this.nodeMapByID.put(E.id,E)}),S.isRemoved||f.push(S);if(f.length){const S=f.map(E=>ha(E));h.length&&h[h.length-1].from===l?h[h.length-1].value=S:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:S})}}return[h,g,y]}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 an.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 Aa(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,v;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),v=an.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?Ji((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:v};for(let y=0;y0&&y===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:y,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([e,n]){if(n===lt.Start){const c=e.allChildren;return c.length>0?[c[0],c[0].isText?lt.Text:lt.Start]:[e,lt.End]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===o.length-1)return[r,lt.End];const u=o[s+1];return[u,u.isText?lt.Text:lt.Start]}findLeftToken([e,n]){if(n===lt.End){const c=e.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?lt.Text:lt.End]}return[e,lt.Start]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===0)return[r,lt.Start];const u=o[s-1];return[u,u.isText?lt.Text:lt.End]}}class ko extends cn{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 ko(e,n,r,o,s,u,c)}execute(e){var c;const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Lt.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)e.registerGCPair(m);return{opInfos:s.map(({from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:m,to:v,value:d,splitLevel:l,fromPath:a,toPath:p}))}}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=>Aa(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class li{constructor(t,e,n,r){T(this,"clientSeq");T(this,"serverSeq");T(this,"lamport");T(this,"actor");this.clientSeq=t,this.serverSeq=r,this.lamport=e,this.actor=n}static of(t,e,n,r){return new li(t,e,n,r)}next(){return new li(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(t){return t>this.lamport?new li(this.clientSeq,t,this.actor):new li(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(t){return Lt.of(this.lamport,t,this.actor)}setActor(t){return new li(this.clientSeq,this.lamport,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const If=new li(0,0n,va);class Gi{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 Gi({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);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===gi.Put?e.set(this.id.getActorID(),on(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:ft.bytesToHex(ft.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>ft.bytesToHex(ft.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:n,presenceChange:r,message:o}=t;return Gi.create({id:ft.bytesToChangeID(ft.hexToBytes(e)),operations:n==null?void 0:n.map(s=>ft.bytesToOperation(ft.hexToBytes(s))),presenceChange:r,message:o})}}class Es{constructor(t,e,n,r,o,s){T(this,"documentKey");T(this,"checkpoint");T(this,"isRemoved");T(this,"changes");T(this,"snapshot");T(this,"minSyncedTicket");this.documentKey=t,this.checkpoint=e,this.isRemoved=n,this.changes=r,this.snapshot=o,this.minSyncedTicket=s}static create(t,e,n,r,o,s){return new Es(t,e,n,r,o,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class $i{constructor(t,e){T(this,"serverSeq");T(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new $i(t,e)}increaseClientSeq(t){return t===0?this:new $i(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 $i.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 _f=new $i(0n,0);class Fn{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Fn(t,e)}static fromStruct(t){return Fn.of(Lt.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 Fn(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 Pf=Fn.of(ln,0);class un{constructor(t,e){T(this,"id");T(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new un(t,e)}static fromStruct(t){const e=Fn.fromStruct(t.id);return un.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Fn.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 hi extends ru{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 hi(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){if(!t.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(t,e,n),s=new Map,u=new Map,c=this.makeChanges(o,e);for(const m of r){const v=m.getCreatedAt().getActorID();(!s.has(v)||m.getID().getCreatedAt().after(s.get(v)))&&s.set(v,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(e)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(t,e,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(t);s.push(u);for(const m of t){const v=m.getCreatedAt().getActorID(),d=r?n.has(v)?n.get(v):ln:ao;m.canDelete(e,d)?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 jn=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(jn||{});class Dt extends To{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=Ke.fromNumber(n).toInt():this.value=pl(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Ke.fromNumber(n):this.value=n;break;default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,n,r){return new Dt(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 Ke.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=Dt.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 Ke?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!!Dt.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()===ct.Long?this.value=this.value+e.getValue().toInt():this.value=Ke.fromNumber(this.value+pl(e.getValue())).toInt(),this}}class Zi extends cn{constructor(e,n,r){super(e,r);T(this,"value");this.value=n}static create(e,n,r){return new Zi(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 Dt))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()===ct.Long?e.getValue().multiply(-1):e.getValue()*-1;return Zi.create(this.getParentCreatedAt(),et.of(r,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Wr extends cn{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 Wr(e,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(e,n,r,o,s,u){return new Wr(e,n,r,o,new Map,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:v,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:v,toPath:d,path: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 Cf(i){const t=new ya,e=t.data;for(const[n,r]of Object.entries(i))e[n]=JSON.stringify(r);return t}function Lf(i){if(i.type===gi.Put)return new go({type:Ni.PUT,presence:Cf(i.presence)});if(i.type===gi.Clear)return new go({type:Ni.CLEAR});throw new ne(te.ErrUnimplemented,"unimplemented type")}function Rf(i){return new eu({serverSeq:i.getServerSeq(),clientSeq:i.getClientSeq()})}function du(i){return new Ts({clientSeq:i.getClientSeq(),lamport:i.getLamport(),actorId:Na(i.getActorID())})}function ke(i){if(i)return new xe({lamport:i.getLamport(),delimiter:i.getDelimiter(),actorId:Na(i.getActorID())})}function gu(i){switch(i){case ct.Null:return Re.NULL;case ct.Boolean:return Re.BOOLEAN;case ct.Integer:return Re.INTEGER;case ct.Long:return Re.LONG;case ct.Double:return Re.DOUBLE;case ct.String:return Re.STRING;case ct.Bytes:return Re.BYTES;case ct.Date:return Re.DATE;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function pu(i){switch(i){case jn.IntegerCnt:return Re.INTEGER_CNT;case jn.LongCnt:return Re.LONG_CNT;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Rs(i){if(i instanceof xt)return new Mt({type:Re.JSON_OBJECT,createdAt:ke(i.getCreatedAt()),value:Nu(i)});if(i instanceof Rt)return new Mt({type:Re.JSON_ARRAY,createdAt:ke(i.getCreatedAt()),value:uh(i)});if(i instanceof Wt)return new Mt({type:Re.TEXT,createdAt:ke(i.getCreatedAt())});if(i instanceof et)return new Mt({type:gu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Mt({type:pu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Gt)return new Mt({type:Re.TREE,createdAt:ke(i.getCreatedAt()),value:fh(i)});throw new ne(te.ErrUnimplemented,"unimplemented element")}function Df(i){return new fo({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Mo(i){return new Gr({createdAt:ke(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function qo(i){return new Oi({parentId:lo(i.getParentID()),leftSiblingId:lo(i.getLeftSiblingID())})}function lo(i){return new ci({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function mu(i){const t=new ma;if(i instanceof Ii){const e=i,n=new Qo;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.key=e.getKey(),n.value=Rs(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="set",t.body.value=n}else if(i instanceof So){const e=i,n=new es;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.value=Rs(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="add",t.body.value=n}else if(i instanceof ui){const e=i,n=new ts;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 pi){const e=i,n=new ns;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 Eo){const e=i,n=new rs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Mo(e.getFromPos()),n.to=Mo(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 xo){const e=i,n=new is;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Mo(e.getFromPos()),n.to=Mo(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 Zi){const e=i,n=new os;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.value=Rs(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="increase",t.body.value=n}else if(i instanceof ko){const e=i,n=new ss,r=n.createdAtMapByActor;for(const[o,s]of e.getMaxCreatedAtMapByActor())r[o]=ke(s);n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=qo(e.getFromPos()),n.to=qo(e.getToPos()),n.contents=Jf(e.getContents()),n.splitLevel=e.getSplitLevel(),n.executedAt=ke(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=n}else if(i instanceof Wr){const e=i,n=new as;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=qo(e.getFromPos()),n.to=qo(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 Bf(i){const t=[];for(const e of i)t.push(mu(e));return t}function Mf(i){const t=new Xl({id:du(i.getID()),message:i.getMessage()});return i.hasOperations()&&(t.operations=Bf(i.getOperations())),i.hasPresenceChange()&&(t.presenceChange=Lf(i.getPresenceChange())),t}function qf(i){const t=[];for(const e of i)t.push(Mf(e));return t}function Ff(i){const t=[];for(const e of i)t.push(new Ql({key:e.getStrKey(),element:Sa(e.getValue())}));return t}function jf(i){const t=[];for(const e of i)t.push(new gs({element:Sa(e.getValue())}));return t}function Uf(i){const t=[];for(const e of i){const n=new ps;n.id=Df(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 Hi;u.value=s.getValue(),u.updatedAt=ke(s.getUpdatedAt()),r[s.getKey()]=u}t.push(n)}return t}function Jf(i){const t=[];if(!i||!i.length)return t;for(const e of i)t.push(new ms({content:Ta(e)}));return t}function $f(i){const t={};for(const e of i)t[e.getKey()]=new Hi({value:e.getValue(),updatedAt:ke(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ta(i){if(!i)return[];const t=[];return Ss(i,(e,n)=>{const r=new ho({id:lo(e.id),type:e.type,removedAt:ke(e.removedAt),depth:n});e.isText&&(r.value=e.value),e.insPrevID&&(r.insPrevId=lo(e.insPrevID)),e.insNextID&&(r.insNextId=lo(e.insNextID)),e.attrs&&(r.attributes=$f(e.attrs)),t.push(r)}),t}function zf(i){const t=new kt;return t.body.case="jsonObject",t.body.value=new ls({nodes:Ff(i.getRHT()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function yu(i){const t=new kt;return t.body.case="jsonArray",t.body.value=new us({nodes:jf(i.getElements()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Kf(i){const t=new kt;return t.body.case="primitive",t.body.value=new cs({type:gu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Hf(i){const t=new kt;return t.body.case="text",t.body.value=new fs({nodes:Uf(i.getRGATreeSplit()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Vf(i){const t=new kt;return t.body.case="counter",t.body.value=new hs({type:pu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function vu(i){const t=new kt;return t.body.case="tree",t.body.value=new ds({nodes:Ta(i.getRoot()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Sa(i){if(i instanceof xt)return zf(i);if(i instanceof Rt)return yu(i);if(i instanceof et)return Kf(i);if(i instanceof Wt)return Hf(i);if(i instanceof Dt)return Vf(i);if(i instanceof Gt)return vu(i);throw new ne(te.ErrUnimplemented,"unimplemented element")}function Wf(i){return new Zr({documentKey:i.getDocumentKey(),checkpoint:Rf(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:qf(i.getChanges()),snapshot:i.getSnapshot(),minSyncedTicket:ke(i.getMinSyncedTicket())})}function ml(i){const t=i.findDetails(ff);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function bu(i){return li.of(i.clientSeq,BigInt(i.lamport),Oa(i.actorId),BigInt(i.serverSeq))}function Ne(i){if(i)return Lt.of(BigInt(i.lamport),i.delimiter,Oa(i.actorId))}function Ea(i){const t={};return Object.entries(i.data).forEach(([e,n])=>{t[e]=JSON.parse(n)}),t}function Gf(i){const t=i.type;if(t===Ni.PUT){const e=Ea(i.presence);return{type:gi.Put,presence:e}}if(t===Ni.CLEAR)return{type:gi.Clear};throw new ne(te.ErrInvalidType,`unsupported type: ${t}`)}function Yf(i){const t=new Map;return Object.entries(i).forEach(([e,n])=>{t.set(e,Ea(n))}),t}function wu(i){switch(i){case Re.NULL:return ct.Null;case Re.BOOLEAN:return ct.Boolean;case Re.INTEGER:return ct.Integer;case Re.LONG:return ct.Long;case Re.DOUBLE:return ct.Double;case Re.STRING:return ct.String;case Re.BYTES:return ct.Bytes;case Re.DATE:return ct.Date}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function bs(i){switch(i){case Re.INTEGER_CNT:return jn.IntegerCnt;case Re.LONG_CNT:return jn.LongCnt}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function Ds(i){switch(i.type){case Re.JSON_OBJECT:return i.value?Ou(i.value):xt.create(Ne(i.createdAt));case Re.JSON_ARRAY:return i.value?lh(i.value):Rt.create(Ne(i.createdAt));case Re.TEXT:return Wt.create(Yi.create(),Ne(i.createdAt));case Re.TREE:return ch(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 et.of(et.valueFromBytes(wu(i.type),i.value),Ne(i.createdAt));case Re.INTEGER_CNT:case Re.LONG_CNT:return Dt.create(bs(i.type),Dt.valueFromBytes(bs(i.type),i.value),Ne(i.createdAt))}}function Fo(i){return un.of(Fn.of(Ne(i.createdAt),i.offset),i.relativeOffset)}function Au(i){return Fn.of(Ne(i.createdAt),i.offset)}function Zf(i){const t=vo.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{t.setAttr(n,r.value,Ne(r.updatedAt))});const e=hi.create(Au(i.id),t);return e.remove(Ne(i.removedAt)),e}function Bi(i){return an.of(uo(i.parentId),uo(i.leftSiblingId))}function uo(i){return pt.of(Ne(i.createdAt),i.offset)}function Xf(i){if(!i.length)return;const t=[];return i.forEach(e=>{const n=xa(e.content);t.push(n)}),t}function xa(i){if(i.length===0)return;const t=[];for(const r of i)t.push(eh(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(),Gt.create(e,ln).getRoot()}function Qf(i){const t=Yr.create();for(const[e,n]of Object.entries(i))t.setInternal(e,n.value,Ne(n.updatedAt),n.isRemoved);return t}function eh(i){const t=uo(i.id),e=Ct.create(t,i.type),n=Object.entries(i.attributes);return e.isText?e.value=i.value:n.length&&(e.attrs=Qf(i.attributes)),i.insPrevId&&(e.insPrevID=uo(i.insPrevId)),i.insNextId&&(e.insNextID=uo(i.insNextId)),e.removedAt=Ne(i.removedAt),e}function Tu(i){if(i.body.case==="set"){const t=i.body.value;return Ii.create(t.key,Ds(t.value),Ne(t.parentCreatedAt),Ne(t.executedAt))}else if(i.body.case==="add"){const t=i.body.value;return So.create(Ne(t.parentCreatedAt),Ne(t.prevCreatedAt),Ds(t.value),Ne(t.executedAt))}else if(i.body.case==="move"){const t=i.body.value;return ui.create(Ne(t.parentCreatedAt),Ne(t.prevCreatedAt),Ne(t.createdAt),Ne(t.executedAt))}else if(i.body.case==="remove"){const t=i.body.value;return pi.create(Ne(t.parentCreatedAt),Ne(t.createdAt),Ne(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,Ne(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),Eo.create(Ne(t.parentCreatedAt),Fo(t.from),Fo(t.to),e,t.content,n,Ne(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,Ne(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),xo.create(Ne(t.parentCreatedAt),Fo(t.from),Fo(t.to),e,n,Ne(t.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const t=i.body.value;return Zi.create(Ne(t.parentCreatedAt),Ds(t.value),Ne(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,Ne(r))}),ko.create(Ne(t.parentCreatedAt),Bi(t.from),Bi(t.to),Xf(t.contents),t.splitLevel,e,Ne(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,Ne(s))}),(n==null?void 0:n.length)>0?Wr.createTreeRemoveStyleOperation(Ne(t.parentCreatedAt),Bi(t.from),Bi(t.to),r,n,Ne(t.executedAt)):(Object.entries(t.attributes).forEach(([o,s])=>{e.set(o,s)}),Wr.create(Ne(t.parentCreatedAt),Bi(t.from),Bi(t.to),r,e,Ne(t.executedAt)))}else throw new ne(te.ErrUnimplemented,"unimplemented operation")}}function th(i){const t=[];for(const e of i){const n=Tu(e);n&&t.push(n)}return t}function Su(i){const t=[];for(const e of i)t.push(Gi.create({id:bu(e.id),operations:th(e.operations),presenceChange:e.presenceChange?Gf(e.presenceChange):void 0,message:e.message}));return t}function nh(i){return $i.of(BigInt(i.serverSeq),i.clientSeq)}function rh(i){return Es.create(i.documentKey,nh(i.checkpoint),i.isRemoved,Su(i.changes),i.snapshot,Ne(i.minSyncedTicket))}function Eu(i){const t=new po;for(const n of i.nodes){const r=ka(n.element);t.set(n.key,r,r.getPositionedAt())}const e=new xt(Ne(i.createdAt),t);return e.setMovedAt(Ne(i.movedAt)),e.setRemovedAt(Ne(i.removedAt)),e}function xu(i){const t=new yo;for(const n of i.nodes)t.insert(ka(n.element));const e=new Rt(Ne(i.createdAt),t);return e.setMovedAt(Ne(i.movedAt)),e.setRemovedAt(Ne(i.removedAt)),e}function ih(i){const t=et.of(et.valueFromBytes(wu(i.type),i.value),Ne(i.createdAt));return t.setMovedAt(Ne(i.movedAt)),t.setRemovedAt(Ne(i.removedAt)),t}function oh(i){const t=new Yi;let e=t.getHead();for(const r of i.nodes){const o=t.insertAfter(e,Zf(r));r.insPrevId&&o.setInsPrev(t.findNode(Au(r.insPrevId))),e=o}const n=new Wt(t,Ne(i.createdAt));return n.setMovedAt(Ne(i.movedAt)),n.setRemovedAt(Ne(i.removedAt)),n}function sh(i){const t=Dt.create(bs(i.type),Dt.valueFromBytes(bs(i.type),i.value),Ne(i.createdAt));return t.setMovedAt(Ne(i.movedAt)),t.setRemovedAt(Ne(i.removedAt)),t}function ku(i){const t=xa(i.nodes);return Gt.create(t,Ne(i.createdAt))}function ka(i){if(i.body.case==="jsonObject")return Eu(i.body.value);if(i.body.case==="jsonArray")return xu(i.body.value);if(i.body.case==="primitive")return ih(i.body.value);if(i.body.case==="text")return oh(i.body.value);if(i.body.case==="counter")return sh(i.body.value);if(i.body.case==="tree")return ku(i.body.value);throw new ne(te.ErrUnimplemented,"unimplemented element")}function ah(i){if(!i)return{root:xt.create(ln),presences:new Map};const t=Us.fromBinary(i);return{root:ka(t.root),presences:Yf(t.presences)}}function Ou(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Eu(t.body.value)}function Nu(i){return Sa(i).toBinary()}function lh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return xu(t.body.value)}function uh(i){return yu(i).toBinary()}function ch(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return ku(t.body.value)}function fh(i){return vu(i).toBinary()}function Iu(i){return i?Array.from(i).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function Oa(i){return Iu(i)}function _u(i){return new Uint8Array(i.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Na(i){return _u(i)}function hh(i){const t=Ts.fromBinary(i);return bu(t)}function dh(i){const t=ma.fromBinary(i);return Tu(t)}const ft={fromPresence:Ea,toChangePack:Wf,fromChangePack:rh,fromChanges:Su,toTreeNodes:Ta,fromTreeNodes:xa,objectToBytes:Nu,bytesToObject:Ou,bytesToSnapshot:ah,bytesToHex:Iu,hexToBytes:_u,toHexString:Oa,toUint8Array:Na,toOperation:mu,toChangeID:du,PbChangeID:Ts,bytesToChangeID:hh,bytesToOperation: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 vi=3;function Pu(i){vi=i}const Ie={trivial:(...i)=>{vi>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{vi>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{vi>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{vi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{vi>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=>vi<=i};function Cu(){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 gh{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===Go.RealtimeSyncOff?!1:this.syncMode===Go.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Go.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 Bs=()=>{};class ph{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=Bs),r.error===void 0&&(r.error=Bs),r.complete===void 0&&(r.complete=Bs);const o=Cu(),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){Ie.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 Ui{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=nu,this.root=e,this.operations=[],this.previousPresence=on(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(t,e,n,r){return new Ui(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 Gi.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 bo{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 Wt||e instanceof Gt)for(const n of e.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new bo(xt.create(ln))}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 fi&&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 fi&&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 fi&&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 bo(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n);r.element.getRemovedAt()&&t.compare(r.element.getRemovedAt())>=0&&(r.parent.purge(r.element),e+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r!==void 0&&t.compare(r)>=0&&(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()}}function Lu(i,t){const e=new wo(i);return new Proxy(t,e.getHandlers())}class wo{constructor(t){T(this,"context");T(this,"handlers");this.context=t,this.handlers={set:(e,n,r)=>(Ie.isEnabled(wt.Trivial)&&Ie.trivial(`obj[${n}]=${JSON.stringify(r)}`),wo.setInternal(t,e,n,r),!0),get:(e,n)=>(Ie.isEnabled(wt.Trivial)&&Ie.trivial(`obj[${n}]`),n==="getID"?()=>e.getCreatedAt():n==="toJSON"||n==="toString"?()=>e.toJSON():n==="toJS"?()=>e.toJS():n==="toJSForTest"?()=>e.toJSForTest():bi(t,e.get(n))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,n)=>(Ie.isEnabled(wt.Trivial)&&Ie.trivial(`obj[${n}]`),wo.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=ws(t,r,o),u=e.set(n,s,o);t.registerElement(s,e),u&&t.registerRemovedElement(u),t.push(Ii.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=ws(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(pi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function yh(i,t){const e=new nt(i,t);return new Proxy(t,e.getHandlers())}function vh(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function bh(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class nt{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 ri(t,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return ri(t,u)}:r==="getLast"?()=>ri(t,n.getLast()):r==="deleteByID"?s=>{const u=nt.deleteInternalByID(t,n,s);return ri(t,u)}:r==="insertAfter"?(s,u)=>{const c=nt.insertAfterInternal(t,n,s,u);return ri(t,c)}:r==="insertBefore"?(s,u)=>{const c=nt.insertBeforeInternal(t,n,s,u);return ri(t,c)}:r==="moveBefore"?(s,u)=>{nt.moveBeforeInternal(t,n,s,u)}:r==="moveAfter"?(s,u)=>{nt.moveAfterInternal(t,n,s,u)}:r==="moveFront"?s=>{nt.moveFrontInternal(t,n,s)}:r==="moveLast"?s=>{nt.moveLastInternal(t,n,s)}:vh(r)?bi(t,n.get(Number(r))):r==="push"?s=>nt.pushInternal(t,n,s):r==="splice"?(s,u,...c)=>nt.splice(t,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?nt.iteratorInternal.bind(this,t,n):r==="includes"?(s,u)=>nt.includes(t,n,s,u):r==="indexOf"?(s,u)=>nt.indexOf(t,n,s,u):r==="lastIndexOf"?(s,u)=>nt.lastIndexOf(t,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>nt.toTestString(n):typeof r=="string"&&bh(r)?(...s)=>{const u=Array.from(n).map(c=>bi(t,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(Ie.isEnabled(wt.Trivial)&&Ie.trivial(`array[${r}]`),nt.deleteInternalByIndex(t,n,Number.parseInt(r)),!0)}}static*iteratorInternal(t,e){for(const n of e)yield ri(t,n)}static buildArrayElements(t,e){const n=[];for(const r of e){const o=t.issueTimeTicket(),s=ws(t,r,o);n.push(s)}return n}static pushInternal(t,e,n){return nt.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(ui.create(e.getCreatedAt(),s,r,o))}static moveAfterInternal(t,e,n,r){const o=t.issueTimeTicket();e.moveAfter(n,r,o),t.push(ui.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(ui.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(ui.create(e.getCreatedAt(),o,n,r))}static insertAfterInternal(t,e,n,r){const o=t.issueTimeTicket(),s=ws(t,r,o);return e.insertAfter(n,s),t.registerElement(s,e),t.push(So.create(e.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(t,e,n,r){return nt.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(pi.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(pi.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 v=u;v=o)return!1;if(et.isSupport(n))return Array.from(e).map(m=>bi(t,m)).includes(n,s);for(let c=s;c=o)return-1;if(et.isSupport(n))return Array.from(e).map(m=>bi(t,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(et.isSupport(n))return Array.from(e).map(m=>bi(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 xs=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);Ie.isEnabled(wt.Debug)&&Ie.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${e}->${o[1].toTestString()} c:${n}`);const s=r?Vi(r):void 0,u=this.context.issueTimeTicket(),[c,,m,v]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new Eo(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(v)}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);Ie.isEnabled(wt.Debug)&&Ie.debug(`STYL: f:${t}->${r[0].toTestString()}, t:${e}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Vi(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 xo(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([un.fromStruct(t[0]),un.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 ks{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=et.of(t,e);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Zi.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 Ia(i,t,e){const{type:n}=i,r=e.issueTimeTicket();if(n===Vr){Ru(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"&&!tu(s)){const m=Vi(s);u=new Yr;for(const[v,d]of Object.entries(m))u.set(v,d,r)}const c=Ct.create(pt.of(r,0),n,void 0,u);t.append(c);for(const m of o)Ia(m,c,e)}}function wh(i,t){const{type:e}=t,n=i.issueTimeTicket();let r;if(t.type===Vr){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"&&!tu(s)){const c=Vi(s);u=new Yr;for(const[m,v]of Object.entries(c))u.set(m,v,n)}r=Ct.create(pt.of(i.issueTimeTicket(),0),e,void 0,u);for(const c of o)Ia(c,r,i)}return r}function Ru(i){if(!i.value.length)throw new ne(te.ErrInvalidArgument,"text node cannot have empty value");return!0}function yl(i){if(!i.length)return!0;if(i[0].type===Vr)for(const e of i){const{type:n}=e;if(n!==Vr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together");Ru(e)}else for(const e of i){const{type:n}=e;if(n===Vr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Os{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),Af);const e=Ct.create(pt.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Ia(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?Vi(e):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(Wr.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?Vi(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const v of m)this.context.registerGCPair(v);this.context.push(Wr.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(Wr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(t,e,n,r=0){var m;if(n.length!==0&&n[0]&&(yl(n),n[0].type!==Vr))for(const v of n){const{children:d=[]}=v;yl(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Vr){let v="";for(const d of n){const{value:l}=d;v+=l}s.push(Ct.create(pt.of(this.context.issueTimeTicket(),0),Vr,v))}else s=n.map(v=>v&&wh(this.context,v)).filter(v=>v);const[,u,c]=this.tree.edit([t,e],s.length?s.map(v=>v==null?void 0:v.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const v of u)this.context.registerGCPair(v);return this.context.push(ko.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=[an.fromStruct(t[0]),an.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=[an.fromStruct(t[0]),an.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function vl(i,t){return Lu(i,t)}function ri(i,t){if(t){if(t instanceof et)return t;if(t instanceof xt)return Lu(i,t);if(t instanceof Rt)return yh(i,t);if(t instanceof Wt)return new xs(i,t);if(t instanceof Dt){const e=new ks(jn.IntegerCnt,0);return e.initialize(i,t),e}else if(t instanceof Gt){const e=new Os;return e.initialize(i,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function bi(i,t){const e=ri(i,t);return e instanceof et?e.getValue():e}function ws(i,t,e){let n;if(et.isSupport(t))n=et.of(t,e);else if(Array.isArray(t))n=Rt.create(e,nt.buildArrayElements(i,t));else if(typeof t=="object")t instanceof xs?(n=Wt.create(Yi.create(),e),t.initialize(i,n)):t instanceof ks?(n=Dt.create(t.getValueType(),t.getValue(),e),t.initialize(i,n)):t instanceof Os?(n=Gt.create(t.buildRoot(i),e),t.initialize(i,n)):n=xt.create(e,wo.buildObjectMembers(i,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return n}const bl=50;class Ah{constructor(){T(this,"undoStack",[]);T(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=bl&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=bl&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Th="yorkie-devtools-panel",Sh="yorkie-devtools-sdk";let Mi="disconnected";const wl=new Map,Wo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Wo);function jo(i,t){(t!=null&&t.force||Mi!=="disconnected")&&window.postMessage({source:Sh,...i},"*")}function Eh(i){if(!i.isEnableDevtools()||typeof window>"u"||wl.has(i.getKey()))return;Wo.set(i.getKey(),[]);const t=i.subscribe("all",e=>{e.some(n=>n.type!==gt.StatusChanged&&n.type!==gt.Snapshot&&n.type!==gt.LocalChange&&n.type!==gt.RemoteChange&&n.type!==gt.Initialized&&n.type!==gt.Watched&&n.type!==gt.Unwatched&&n.type!==gt.PresenceChanged)||(Wo.get(i.getKey()).push(e),Mi==="synced"&&jo({msg:"doc::sync::partial",docKey:i.getKey(),event:e}))});wl.set(i.getKey(),[t]),jo({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.source)!==Th)return;switch(e.data.msg){case"devtools::connect":if(Mi!=="disconnected")break;Mi="connected",jo({msg:"doc::available",docKey:i.getKey()}),Ie.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":Mi="disconnected",Ie.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":Mi="synced",jo({msg:"doc::sync::full",docKey:i.getKey(),events:Wo.get(i.getKey())}),Ie.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var ii=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(ii||{}),gt=(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))(gt||{}),Ao=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(Ao||{}),da=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(da||{});class Du{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=bo.create(),this.changeID=If,this.checkpoint=_f,this.localChanges=[],this.eventStream=mh(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Ah,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Eh(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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},e);try{const o=vl(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,t(o,new Ls(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){Ie.isEnabled(wt.Trivial)&&Ie.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),Ie.isEnabled(wt.Trivial)&&Ie.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==="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 v of c.value.operations)this.isSameElementOrChildOf(v.path,o)&&m.push(v);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof 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])}applyChangePack(t){for(t.hasSnapshot()?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),Ye.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();t.hasSnapshot()&&this.applyChanges(this.localChanges,Ye.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),this.garbageCollect(t.getMinSyncedTicket()),t.getIsRemoved()&&this.applyStatus("removed"),Ie.isEnabled(wt.Trivial)&&Ie.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:on(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Es.create(this.key,e,!1,t)}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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return vl(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e){const{root:n,presences:r}=ft.bytesToSnapshot(e);this.root=new bo(n),this.presences=r,this.changeID=this.changeID.syncLamport(t),this.clone=void 0,this.publish([{type:"snapshot",source:Ye.Remote,value:{snapshot:this.isEnableDevtools()?ft.bytesToHex(e):void 0,serverSeq:t.toString()}}])}applyChanges(t,e){Ie.isEnabled(wt.Debug)&&Ie.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Ie.isEnabled(wt.Trivial)&&Ie.trivial(t.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` -`));for(const n of t)this.applyChange(n,e);Ie.isEnabled(wt.Debug)&&Ie.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 gi.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 gi.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.syncLamport(t.getID().getLamport()),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===ki.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(e===ki.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===ki.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(va),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}=t.value;if(!e)return;this.applySnapshot(BigInt(n),ft.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Gi.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?on(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?on(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?on(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:on(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:on(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}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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof cn)){new Ls(e,on(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=e.issueTimeTicket();m.setExecutedAt(v),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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof cn)){new Ls(e,on(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=e.issueTimeTicket();m.setExecutedAt(v),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])}}function xh(i,t){return e=>async n=>(i&&n.header.set("x-api-key",i),t&&n.header.set("authorization",t),await e(n))}const kh="yorkie-js-sdk",Oh="0.5.1",Nh="Yorkie JS SDK",Ih="./src/yorkie.ts",_h={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Ph=["dist"],Ch={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"},Lh={node:">=18.0.0",npm:">=7.1.0"},Rh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Dh={name:"hackerwins",email:"susukang98@gmail.com"},Bh="Apache-2.0",Mh={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},qh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Fh={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},jh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Al={name:kh,version:Oh,description:Nh,main:Ih,publishConfig:_h,files:Ph,scripts:Ch,engines:Lh,repository:Rh,author:Dh,license:Bh,bugs:Mh,homepage:qh,devDependencies:Fh,dependencies:jh};function Uh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Al.name+"/"+Al.version),await i(t))}const Jh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Go=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Go||{});const Uo={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ms={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Bu{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"taskQueue");T(this,"processing",!1);e=e||Uo,this.key=e.key?e.key:Cu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||Uo.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||Uo.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||Uo.retrySyncLoopDelay,this.rpcClient=jc(cf,uf({baseUrl:t,interceptors:[xh(e.apiKey,e.token),Uh()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Ie.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Ie.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Ie.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Ie.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==ii.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 v;const{topic:s,payload:u}=o.value,c=(v=o.options)==null?void 0:v.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ft.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=ft.fromChangePack(o.changePack);return t.applyChangePack(s),t.getStatus()===ii.Removed||(t.applyStatus(ii.Attached),this.attachmentMap.set(t.getKey(),new gh(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ie.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(o=>{throw Ie.error(`[AD] c:"${this.getKey()}" err :`,o),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:ft.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=ft.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==ii.Removed&&t.applyStatus(ii.Detached),this.detachInternal(t.getKey()),Ie.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(r=>{throw Ie.error(`[DD] c:"${this.getKey()}" err :`,r),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(n=>{throw Ie.error(`[SY] c:"${this.getKey()}" err :`,n),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(n=>{throw Ie.error(`[SY] c:"${this.getKey()}" err :`,n),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=ft.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=ft.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ie.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(r=>{throw Ie.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(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(!Jh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??Ms.maxRetries,u=Ms.maxBackoff;let c=0;const m=d=>Math.min(Ms.initialRetryInterval*2**d,u),v=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(()=>{Ie.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(d=>{if(Ie.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cv(),m(c-1)),Ie.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ie.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return v()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ie.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)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(n=>{Ie.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ie.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:gt.ConnectionChanged,value:Ao.Connected}]),Ie.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:gt.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:gt.ConnectionChanged,value:Ao.Disconnected}]),Ie.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===ki.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(ii.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:ft.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=ft.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:gt.SyncStatusChanged,value:da.Synced}]),n.getStatus()===ii.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ie.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:gt.SyncStatusChanged,value:da.SyncFailed}]),Ie.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(t){return t instanceof ut?t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable?!0:((ml(t)===te.ErrClientNotActivated||ml(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{Ie.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const qs={Client:Bu,Document:Du,Primitive:et,Text:xs,Counter:ks,Tree:Os,LogLevel:wt,setLogLevel:Pu,IntType:jn.IntegerCnt,LongType:jn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Bu,Document:Du,Primitive:et,Text:xs,Counter:ks,Tree:Os,LogLevel:wt,setLogLevel:Pu,IntType:jn.IntegerCnt,LongType:jn.LongCnt});var $h=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var qu={exports:{}};/*! +`));for(const n of t)this.applyChange(n,e);Ie.isEnabled(wt.Debug)&&Ie.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 gi.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 gi.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.syncLamport(t.getID().getLamport()),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===ki.DOCUMENT_WATCHED)this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}});else if(e===ki.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===ki.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(va),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}=t.value;if(!e)return;this.applySnapshot(BigInt(n),ft.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Gi.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?on(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?on(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?on(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:on(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:on(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}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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof cn)){new Ls(e,on(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=e.issueTimeTicket();m.setExecutedAt(v),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=Ui.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof cn)){new Ls(e,on(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const v=e.issueTimeTicket();m.setExecutedAt(v),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])}}function xh(i,t){return e=>async n=>(i&&n.header.set("x-api-key",i),t&&n.header.set("authorization",t),await e(n))}const kh="yorkie-js-sdk",Oh="0.5.2",Nh="Yorkie JS SDK",Ih="./src/yorkie.ts",_h={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Ph=["dist"],Ch={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"},Lh={node:">=18.0.0",npm:">=7.1.0"},Rh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Dh={name:"hackerwins",email:"susukang98@gmail.com"},Bh="Apache-2.0",Mh={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},qh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Fh={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},jh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Al={name:kh,version:Oh,description:Nh,main:Ih,publishConfig:_h,files:Ph,scripts:Ch,engines:Lh,repository:Rh,author:Dh,license:Bh,bugs:Mh,homepage:qh,devDependencies:Fh,dependencies:jh};function Uh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Al.name+"/"+Al.version),await i(t))}const Jh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Go=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Go||{});const Uo={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ms={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Bu{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"taskQueue");T(this,"processing",!1);e=e||Uo,this.key=e.key?e.key:Cu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||Uo.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||Uo.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||Uo.retrySyncLoopDelay,this.rpcClient=jc(cf,uf({baseUrl:t,interceptors:[xh(e.apiKey,e.token),Uh()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Ie.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Ie.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Ie.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Ie.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==ii.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 v;const{topic:s,payload:u}=o.value,c=(v=o.options)==null?void 0:v.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:ft.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=ft.fromChangePack(o.changePack);return t.applyChangePack(s),t.getStatus()===ii.Removed||(t.applyStatus(ii.Attached),this.attachmentMap.set(t.getKey(),new gh(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ie.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`)),t}).catch(o=>{throw Ie.error(`[AD] c:"${this.getKey()}" err :`,o),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:ft.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=ft.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==ii.Removed&&t.applyStatus(ii.Detached),this.detachInternal(t.getKey()),Ie.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(r=>{throw Ie.error(`[DD] c:"${this.getKey()}" err :`,r),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(n=>{throw Ie.error(`[SY] c:"${this.getKey()}" err :`,n),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(n=>{throw Ie.error(`[SY] c:"${this.getKey()}" err :`,n),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=ft.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=ft.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ie.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(r=>{throw Ie.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(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(!Jh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??Ms.maxRetries,u=Ms.maxBackoff;let c=0;const m=d=>Math.min(Ms.initialRetryInterval*2**d,u),v=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(()=>{Ie.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(d=>{if(Ie.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cv(),m(c-1)),Ie.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ie.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return v()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ie.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)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(n=>{Ie.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ie.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:gt.ConnectionChanged,value:Ao.Connected}]),Ie.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:gt.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:gt.ConnectionChanged,value:Ao.Disconnected}]),Ie.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===ki.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(ii.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:ft.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=ft.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:gt.SyncStatusChanged,value:da.Synced}]),n.getStatus()===ii.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ie.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:gt.SyncStatusChanged,value:da.SyncFailed}]),Ie.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(t){return t instanceof ut?t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable?!0:((ml(t)===te.ErrClientNotActivated||ml(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1):!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{Ie.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const qs={Client:Bu,Document:Du,Primitive:et,Text:xs,Counter:ks,Tree:Os,LogLevel:wt,setLogLevel:Pu,IntType:jn.IntegerCnt,LongType:jn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Bu,Document:Du,Primitive:et,Text:xs,Counter:ks,Tree:Os,LogLevel:wt,setLogLevel:Pu,IntType:jn.IntegerCnt,LongType:jn.LongCnt});var $h=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var qu={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 ba4023d6e..cf4bfc3de 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-BqVvB3pR.js b/examples/vuejs-kanban/assets/index-ClPsSZVC.js similarity index 99% rename from examples/vuejs-kanban/assets/index-BqVvB3pR.js rename to examples/vuejs-kanban/assets/index-ClPsSZVC.js index 1d0ca5efd..8eb39c054 100644 --- a/examples/vuejs-kanban/assets/index-BqVvB3pR.js +++ b/examples/vuejs-kanban/assets/index-ClPsSZVC.js @@ -20,4 +20,4 @@ var Hf=Object.defineProperty;var Gf=(n,e,t)=>e in n?Hf(n,e,{enumerable:!0,config * * SPDX-License-Identifier: Apache-2.0 */var st=null;try{st=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 Ce(n){return(n&&n.__isLong__)===!0}function Nu(n){var e=Math.clz32(n&-n);return n?31-e:e}X.isLong=Ce;var Pu={},Ou={};function zr(n,e){var t,r,s;return e?(n>>>=0,(s=0<=n&&n<256)&&(r=Ou[n],r)?r:(t=Q(n,0,!0),s&&(Ou[n]=t),t)):(n|=0,(s=-128<=n&&n<128)&&(r=Pu[n],r)?r:(t=Q(n,n<0?-1:0,!1),s&&(Pu[n]=t),t))}X.fromInt=zr;function it(n,e){if(isNaN(n))return e?Yn:mt;if(e){if(n<0)return Yn;if(n>=ff)return gf}else{if(n<=-Bu)return Je;if(n+1>=Bu)return df}return n<0?it(-n,e).neg():Q(n%ls|0,n/ls|0,e)}X.fromNumber=it;function Q(n,e,t){return new X(n,e,t)}X.fromBits=Q;var Xi=Math.pow;function Qa(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?Yn:mt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Qa(n.substring(1),e,t).neg();for(var s=it(Xi(t,8)),i=mt,o=0;o>>0:this.low};k.toNumber=function(){return this.unsigned?(this.high>>>0)*ls+(this.low>>>0):this.high*ls+(this.low>>>0)};k.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}};k.getHighBits=function(){return this.high};k.getHighBitsUnsigned=function(){return this.high>>>0};k.getLowBits=function(){return this.low};k.getLowBitsUnsigned=function(){return this.low>>>0};k.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};k.isOdd=function(){return(this.low&1)===1};k.isEven=function(){return(this.low&1)===0};k.equals=function(e){return Ce(e)||(e=Tt(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};k.eq=k.equals;k.notEquals=function(e){return!this.eq(e)};k.neq=k.notEquals;k.ne=k.notEquals;k.lessThan=function(e){return this.comp(e)<0};k.lt=k.lessThan;k.lessThanOrEqual=function(e){return this.comp(e)<=0};k.lte=k.lessThanOrEqual;k.le=k.lessThanOrEqual;k.greaterThan=function(e){return this.comp(e)>0};k.gt=k.greaterThan;k.greaterThanOrEqual=function(e){return this.comp(e)>=0};k.gte=k.greaterThanOrEqual;k.ge=k.greaterThanOrEqual;k.compare=function(e){if(Ce(e)||(e=Tt(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};k.comp=k.compare;k.negate=function(){return!this.unsigned&&this.eq(Je)?Je:this.not().add(_r)};k.neg=k.negate;k.add=function(e){Ce(e)||(e=Tt(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,g=0,v=0,m=0;return m+=i+l,v+=m>>>16,m&=65535,v+=s+u,g+=v>>>16,v&=65535,g+=r+a,h+=g>>>16,g&=65535,h+=t+o,h&=65535,Q(v<<16|m,h<<16|g,this.unsigned)};k.subtract=function(e){return Ce(e)||(e=Tt(e)),this.add(e.neg())};k.sub=k.subtract;k.multiply=function(e){if(this.isZero())return this;if(Ce(e)||(e=Tt(e)),st){var t=st.mul(this.low,this.high,e.low,e.high);return Q(t,st.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Yn:mt;if(this.eq(Je))return e.isOdd()?Je:mt;if(e.eq(Je))return this.isOdd()?Je:mt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Ru)&&e.lt(Ru))return it(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,g=0,v=0,m=0,A=0;return A+=o*h,m+=A>>>16,A&=65535,m+=i*h,v+=m>>>16,m&=65535,m+=o*l,v+=m>>>16,m&=65535,v+=s*h,g+=v>>>16,v&=65535,v+=i*l,g+=v>>>16,v&=65535,v+=o*u,g+=v>>>16,v&=65535,g+=r*h+s*l+i*u+o*a,g&=65535,Q(m<<16|A,g<<16|v,this.unsigned)};k.mul=k.multiply;k.divide=function(e){if(Ce(e)||(e=Tt(e)),e.isZero())throw Error("division by zero");if(st){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?st.div_u:st.div_s)(this.low,this.high,e.low,e.high);return Q(t,st.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Yn:mt;var r,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Yn;if(e.gt(this.shru(1)))return hf;i=Yn}else{if(this.eq(Je)){if(e.eq(_r)||e.eq(ba))return Je;if(e.eq(Je))return _r;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(mt)?e.isNegative()?_r:ba:(s=this.sub(e.mul(r)),i=r.add(s.div(e)),i)}else if(e.eq(Je))return this.unsigned?Yn:mt;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=mt}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:Xi(2,a-48),l=it(r),h=l.mul(e);h.isNegative()||h.gt(s);)r-=u,l=it(r,this.unsigned),h=l.mul(e);l.isZero()&&(l=_r),i=i.add(l),s=s.sub(h)}return i};k.div=k.divide;k.modulo=function(e){if(Ce(e)||(e=Tt(e)),st){var t=(this.unsigned?st.rem_u:st.rem_s)(this.low,this.high,e.low,e.high);return Q(t,st.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};k.mod=k.modulo;k.rem=k.modulo;k.not=function(){return Q(~this.low,~this.high,this.unsigned)};k.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};k.clz=k.countLeadingZeros;k.countTrailingZeros=function(){return this.low?Nu(this.low):Nu(this.high)+32};k.ctz=k.countTrailingZeros;k.and=function(e){return Ce(e)||(e=Tt(e)),Q(this.low&e.low,this.high&e.high,this.unsigned)};k.or=function(e){return Ce(e)||(e=Tt(e)),Q(this.low|e.low,this.high|e.high,this.unsigned)};k.xor=function(e){return Ce(e)||(e=Tt(e)),Q(this.low^e.low,this.high^e.high,this.unsigned)};k.shiftLeft=function(e){return Ce(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)};k.shr=k.shiftRight;k.shiftRightUnsigned=function(e){return Ce(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)};k.shru=k.shiftRightUnsigned;k.shr_u=k.shiftRightUnsigned;k.rotateLeft=function(e){var t;return Ce(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))};k.rotl=k.rotateLeft;k.rotateRight=function(e){var t;return Ce(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))};k.rotr=k.rotateRight;k.toSigned=function(){return this.unsigned?Q(this.low,this.high,!1):this};k.toUnsigned=function(){return this.unsigned?this:Q(this.low,this.high,!0)};k.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};k.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]};k.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 we=(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))(we||{});class le extends Ws{constructor(t,r){super(r);c(this,"valueType");c(this,"value");this.valueType=le.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new le(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?`"${Mt(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=le.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 le.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 Zi extends lf{constructor(t){super(t);c(this,"prev");c(this,"next");this.value=t}static createAfter(t,r){const s=new Zi(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 zs{constructor(){c(this,"dummyHead");c(this,"last");c(this,"nodeMapByIndex");c(this,"nodeMapByCreatedAt");const e=le.of(0,vt);e.setRemovedAt(vt),this.dummyHead=new Zi(e),this.last=this.dummyHead,this.nodeMapByIndex=new qs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new zs}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=Zi.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 Ve extends mr{constructor(t,r){super(t);c(this,"elements");this.elements=r}static create(t,r){if(!r)return new Ve(t,zs.create());const s=zs.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new Ve(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 mr&&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({...m,value:m.value?{attributes:ts(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,h,[u,u]]}setStyle(t,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),u=[],l=this.rgaTreeSplit.findBetween(a,o),h=new Map,g=[];for(const m of l){const A=m.getCreatedAt().getActorID(),E=i!=null&&i.size?i.has(A)?i.get(A):vt:Es;if(m.canStyle(s,E)){const R=h.get(A),$=m.getCreatedAt();(!R||$.after(R))&&h.set(A,$),g.push(m)}}const v=[];for(const m of g){if(m.isRemoved())continue;const[A,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:s.getActorID(),from:A,to:E,value:{attributes:ts(r)}});for(const[R,$]of Object.entries(r)){const[U]=m.getValue().setAttr(R,$,s);U!==void 0&&v.push({parent:m.getValue(),child:U})}}return[h,v,u]}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:ts(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new ot(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 Gs extends bt{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 Gs(t,r,s,i,o,a,u)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ot))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l})=>({type:"edit",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class _s extends bt{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 _s(t,r,s,i,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ot))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:u,value:l})=>({type:"style",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Zm=2,Qm="root",Xn="text";function bs(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===Xn}get paddedSize(){return this.size+(this.isText?0:Zm)}isAncestorOf(e){return tp(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 tp(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ye=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ye||{});function mf(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),mf(i,Math.max(0,o),Math.min(a,i.size),r),l&&r([i,"End"],l)}s+=i.paddedSize}}function pf(n,e,t=0){for(const r of n.children)pf(r,e,t+1);e(n,t)}function go(n,e,t=0){for(const r of n._children)go(r,e,t+1);e(n,t)}function Ta(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 Ta(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 Ta(i,e-s-1,t);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function yf(n){return n.isText||n.children.length===0?n:yf(n.children[0])}function np(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 ip(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 pt{constructor(e,t){c(this,"parentID");c(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new pt(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],pt.of(r.id,Ae.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return pt.of(Ae.of(je.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(je.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 Ae{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ae(e,t)}static fromStruct(e){return Ae.of(je.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 Ke(Ae.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ke(Ae.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new tr);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,r));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Aa(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(Aa)};return n.attrs&&(e.attributes=ts((t=n.attrs)==null?void 0:t.toObject())),e}function ec(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()}="${Mt(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>ec(t)).join("")}`}function wf(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(wf),size:n.size,isRemoved:n.isRemoved}}class at extends Ws{constructor(t,r){super(r);c(this,"indexTree");c(this,"nodeMapByID");this.indexTree=new rp(t),this.nodeMapByID=new vf(Ae.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,r){return new at(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 g=h;g{const E=A.getCreatedAt().getActorID(),R=i?i.has(E)?i.get(E):vt:Es;if(A.canStyle(s,R)&&r){const $=v.get(E),U=A.getCreatedAt();(!$||U.after($))&&v.set(E,U);const Y=A.setAttrs(r,s),D=Y.reduce((ae,[,Se])=>(Se&&(ae[Se.getKey()]=g[Se.getKey()]),ae),{}),G=A.parent,ee=A.prevSibling||A.parent;Object.keys(D).length>0&&h.push({type:"style",from:this.toIndex(G,ee),to:this.toIndex(A,A),fromPath:this.toPath(G,ee),toPath:this.toPath(A,A),actor:s.getActorID(),value:D});for(const[ae]of Y)ae&&m.push({parent:A,child:ae})}}),[v,m,h]}removeStyle(t,r,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[u,l]=this.findNodesAndSplitText(t[1],s),h=[],g=new Map,v=[];return this.traverseInPosRange(o,a,u,l,([m])=>{const A=m.getCreatedAt().getActorID(),E=i?i.has(A)?i.get(A):vt:Es;if(m.canStyle(s,E)&&r){const R=g.get(A),$=m.getCreatedAt();(!R||$.after(R))&&g.set(A,$),m.attrs||(m.attrs=new tr);for(const D of r){const G=m.attrs.remove(D,s);for(const ee of G)v.push({parent:m,child:ee})}const U=m.parent,Y=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(U,Y),to:this.toIndex(m,m),fromPath:this.toPath(U,Y),toPath:this.toPath(m,m),value:r})}}),[g,v,h]}edit(t,r,s,i,o,a){const[u,l]=this.findNodesAndSplitText(t[0],i),[h,g]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(u,l),m=this.toPath(u,l),A=[],E=[],R=[],$=new Map;this.traverseInPosRange(u,l,h,g,([D,G],ee)=>{if(G===ye.Start&&!ee)for(const ct of D.children)R.push(ct);const ae=D.getCreatedAt().getActorID(),Se=a?a.has(ae)?a.get(ae):vt:Es;if(D.canDelete(i,Se)||A.includes(D.parent)){const ct=$.get(ae),He=D.getCreatedAt();(!ct||He.after(ct))&&$.set(ae,He),(G===ye.Text||G===ye.Start)&&A.push(D),E.push([D,G])}});const U=this.makeDeletionChanges(E,i),Y=[];for(const D of A)D.remove(i),D.isRemoved&&Y.push({parent:this,child:D});for(const D of R)D.removedAt||u.append(D);if(s>0){let D=0,G=u,ee=l;for(;D{u.isRemoved&&(ae.remove(i),Y.push({parent:this,child:ae})),this.nodeMapByID.put(ae.id,ae)}),ee.isRemoved||D.push(ee);if(D.length){const ee=D.map(ae=>Aa(ae));U.length&&U[U.length-1].from===v?U[U.length-1].value=ee:U.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:ee})}}return[U,Y,$]}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 pt.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 ec(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 m,A,E,R;let u,l,h;const g=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;g&&(u=this.indexTree.indexOf(g),l=this.indexTree.treePosToPath(g),h=pt.fromTreePos(g).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(E=s.insNextID)==null?void 0:E.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?ts((R=s.attrs)==null?void 0:R.toObject()):void 0,index:u,path:l,pos:h};for(let $=0;$0&&$===s[s.length-1].to?(s[s.length-1].to=U,s[s.length-1].toPath=this.toPath(R,m)):s.push({type:"content",from:$,to:U,fromPath:this.toPath(E,g),toPath:this.toPath(R,m),actor:r.getActorID()}))}return s.reverse()}findRightToken([t,r]){if(r===ye.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?ye.Text:ye.Start]:[t,ye.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,ye.End];const a=i[o+1];return[a,a.isText?ye.Text:ye.Start]}findLeftToken([t,r]){if(r===ye.End){const u=t.allChildren;if(u.length>0){const l=u[u.length-1];return[l,l.isText?ye.Text:ye.End]}return[t,ye.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,ye.Start];const a=i[o-1];return[a,a.isText?ye.Text:ye.End]}}class Ys extends bt{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 Ys(t,r,s,i,o,a,u)}execute(t){var u;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,a]=i.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>je.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${r},${s},${i.map(o=>ec(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class lr{constructor(e,t,r,s){c(this,"clientSeq");c(this,"serverSeq");c(this,"lamport");c(this,"actor");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.actor=r}static of(e,t,r,s){return new lr(e,t,r,s)}next(){return new lr(this.clientSeq+1,this.lamport+1n,this.actor)}syncLamport(e){return e>this.lamport?new lr(this.clientSeq,e,this.actor):new lr(this.clientSeq,this.lamport+1n,this.actor)}createTimeTicket(e){return je.of(this.lamport,e,this.actor)}setActor(e){return new lr(this.clientSeq,this.lamport,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const ap=new lr(0,0n,Xa);class fs{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 fs({id:e,operations:t,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:u,reverseOp:l}=a;s.push(...u),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===wr.Put?t.set(this.id.getActorID(),ft(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:be.bytesToHex(be.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>be.bytesToHex(be.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:s,message:i}=e;return fs.create({id:be.bytesToChangeID(be.hexToBytes(t)),operations:r==null?void 0:r.map(o=>be.bytesToOperation(be.hexToBytes(o))),presenceChange:s,message:i})}}class mo{constructor(e,t,r,s,i,o){c(this,"documentKey");c(this,"checkpoint");c(this,"isRemoved");c(this,"changes");c(this,"snapshot");c(this,"minSyncedTicket");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=s,this.snapshot=i,this.minSyncedTicket=o}static create(e,t,r,s,i,o){return new mo(e,t,r,s,i,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}}class ns{constructor(e,t){c(this,"serverSeq");c(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 cp=new ns(0n,0);class Ut{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ut(e,t)}static fromStruct(e){return Ut.of(je.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 Ut(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 up=Ut.of(vt,0);class wt{constructor(e,t){c(this,"id");c(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new wt(e,t)}static fromStruct(e){const t=Ut.fromStruct(e.id);return wt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ut.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 pr extends lf{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 pr(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){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,r),o=new Map,a=new Map,u=this.makeChanges(i,t);for(const l of s){const h=l.getCreatedAt().getActorID();(!o.has(h)||l.getID().getCreatedAt().after(o.get(h)))&&o.set(h,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[u,o,a]}filterNodes(e,t,r){const s=!!r,i=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const h=l.getCreatedAt().getActorID(),g=s?r.has(h)?r.get(h):vt:Es;l.canDelete(t,g)?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 qt=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(qt||{});class We extends Ws{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=Fu(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 We(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=We.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!!We.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()===we.Long?this.value=this.value+t.getValue().toInt():this.value=X.fromNumber(this.value+Fu(t.getValue())).toInt(),this}}class ds extends bt{constructor(t,r,s){super(t,s);c(this,"value");this.value=r}static create(t,r,s){return new ds(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 We))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()===we.Long?t.getValue().multiply(-1):t.getValue()*-1;return ds.create(this.getParentCreatedAt(),le.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Zn extends bt{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 Zn(t,r,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,s,i,o,a){return new Zn(t,r,s,i,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([u,l])=>a[u]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l,fromPath:h,toPath:g})=>({type:"tree-style",from:a,to:u,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:h,toPath:g,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 lp(n){const e=new Ya,t=e.data;for(const[r,s]of Object.entries(n))t[r]=JSON.stringify(s);return e}function fp(n){if(n.type===wr.Put)return new $s({type:$r.PUT,presence:lp(n.presence)});if(n.type===wr.Clear)return new $s({type:$r.CLEAR});throw new w(y.ErrUnimplemented,"unimplemented type")}function hp(n){return new af({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function bf(n){return new ho({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ac(n.getActorID())})}function J(n){if(n)return new L({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ac(n.getActorID())})}function Tf(n){switch(n){case we.Null:return W.NULL;case we.Boolean:return W.BOOLEAN;case we.Integer:return W.INTEGER;case we.Long:return W.LONG;case we.Double:return W.DOUBLE;case we.String:return W.STRING;case we.Bytes:return W.BYTES;case we.Date:return W.DATE;default:throw new w(y.ErrInvalidType,`unsupported type: ${n}`)}}function Af(n){switch(n){case qt.IntegerCnt:return W.INTEGER_CNT;case qt.LongCnt:return W.LONG_CNT;default:throw new w(y.ErrInvalidType,`unsupported type: ${n}`)}}function Do(n){if(n instanceof Me)return new _e({type:W.JSON_OBJECT,createdAt:J(n.getCreatedAt()),value:Ff(n)});if(n instanceof Ve)return new _e({type:W.JSON_ARRAY,createdAt:J(n.getCreatedAt()),value:qp(n)});if(n instanceof ot)return new _e({type:W.TEXT,createdAt:J(n.getCreatedAt())});if(n instanceof le)return new _e({type:Tf(n.getType()),createdAt:J(n.getCreatedAt()),value:n.toBytes()});if(n instanceof We)return new _e({type:Af(n.getType()),createdAt:J(n.getCreatedAt()),value:n.toBytes()});if(n instanceof at)return new _e({type:W.TREE,createdAt:J(n.getCreatedAt()),value:Kp(n)});throw new w(y.ErrUnimplemented,"unimplemented element")}function dp(n){return new Js({createdAt:J(n.getCreatedAt()),offset:n.getOffset()})}function ui(n){return new er({createdAt:J(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function li(n){return new Mr({parentId:Cs(n.getParentID()),leftSiblingId:Cs(n.getLeftSiblingID())})}function Cs(n){return new gr({createdAt:J(n.getCreatedAt()),offset:n.getOffset()})}function If(n){const e=new _a;if(n instanceof Ur){const t=n,r=new Bi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Do(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Hs){const t=n,r=new Ri;r.parentCreatedAt=J(t.getParentCreatedAt()),r.prevCreatedAt=J(t.getPrevCreatedAt()),r.value=Do(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof fr){const t=n,r=new Fi;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 br){const t=n,r=new Li;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 Gs){const t=n,r=new Ji;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=ui(t.getFromPos()),r.to=ui(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 _s){const t=n,r=new Mi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=ui(t.getFromPos()),r.to=ui(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 ds){const t=n,r=new $i;r.parentCreatedAt=J(t.getParentCreatedAt()),r.value=Do(t.getValue()),r.executedAt=J(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Ys){const t=n,r=new Ui,s=r.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=J(o);r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=li(t.getFromPos()),r.to=li(t.getToPos()),r.contents=bp(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=J(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof Zn){const t=n,r=new qi;r.parentCreatedAt=J(t.getParentCreatedAt()),r.from=li(t.getFromPos()),r.to=li(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 gp(n){const e=[];for(const t of n)e.push(If(t));return e}function mp(n){const e=new sf({id:bf(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=gp(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=fp(n.getPresenceChange())),e}function pp(n){const e=[];for(const t of n)e.push(mp(t));return e}function yp(n){const e=[];for(const t of n)e.push(new of({key:t.getStrKey(),element:nc(t.getValue())}));return e}function vp(n){const e=[];for(const t of n)e.push(new Gi({element:nc(t.getValue())}));return e}function wp(n){const e=[];for(const t of n){const r=new _i;r.id=dp(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 cs;a.value=o.getValue(),a.updatedAt=J(o.getUpdatedAt()),s[o.getKey()]=a}e.push(r)}return e}function bp(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new Yi({content:tc(t)}));return e}function Tp(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:J(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function tc(n){if(!n)return[];const e=[];return go(n,(t,r)=>{const s=new Ms({id:Cs(t.id),type:t.type,removedAt:J(t.removedAt),depth:r});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=Cs(t.insPrevID)),t.insNextID&&(s.insNextId=Cs(t.insNextID)),t.attrs&&(s.attributes=Tp(t.attrs)),e.push(s)}),e}function Ap(n){const e=new Ue;return e.body.case="jsonObject",e.body.value=new zi({nodes:yp(n.getRHT()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Sf(n){const e=new Ue;return e.body.case="jsonArray",e.body.value=new Ki({nodes:vp(n.getElements()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Ip(n){const e=new Ue;return e.body.case="primitive",e.body.value=new ji({type:Tf(n.getType()),value:n.toBytes(),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function Sp(n){const e=new Ue;return e.body.case="text",e.body.value=new Vi({nodes:wp(n.getRGATreeSplit()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function xp(n){const e=new Ue;return e.body.case="counter",e.body.value=new Wi({type:Af(n.getType()),value:n.toBytes(),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function xf(n){const e=new Ue;return e.body.case="tree",e.body.value=new Hi({nodes:tc(n.getRoot()),createdAt:J(n.getCreatedAt()),movedAt:J(n.getMovedAt()),removedAt:J(n.getRemovedAt())}),e}function nc(n){if(n instanceof Me)return Ap(n);if(n instanceof Ve)return Sf(n);if(n instanceof le)return Ip(n);if(n instanceof ot)return Sp(n);if(n instanceof We)return xp(n);if(n instanceof at)return xf(n);throw new w(y.ErrUnimplemented,"unimplemented element")}function kp(n){return new rr({documentKey:n.getDocumentKey(),checkpoint:hp(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:pp(n.getChanges()),snapshot:n.getSnapshot(),minSyncedTicket:J(n.getMinSyncedTicket())})}function Lu(n){const e=n.findDetails(Km);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function kf(n){return lr.of(n.clientSeq,BigInt(n.lamport),oc(n.actorId),BigInt(n.serverSeq))}function M(n){if(n)return je.of(BigInt(n.lamport),n.delimiter,oc(n.actorId))}function rc(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function Ep(n){const e=n.type;if(e===$r.PUT){const t=rc(n.presence);return{type:wr.Put,presence:t}}if(e===$r.CLEAR)return{type:wr.Clear};throw new w(y.ErrInvalidType,`unsupported type: ${e}`)}function Cp(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,rc(r))}),e}function Ef(n){switch(n){case W.NULL:return we.Null;case W.BOOLEAN:return we.Boolean;case W.INTEGER:return we.Integer;case W.LONG:return we.Long;case W.DOUBLE:return we.Double;case W.STRING:return we.String;case W.BYTES:return we.Bytes;case W.DATE:return we.Date}throw new w(y.ErrUnimplemented,`unimplemented value type: ${n}`)}function Qi(n){switch(n){case W.INTEGER_CNT:return qt.IntegerCnt;case W.LONG_CNT:return qt.LongCnt}throw new w(y.ErrUnimplemented,`unimplemented value type: ${n}`)}function Bo(n){switch(n.type){case W.JSON_OBJECT:return n.value?Rf(n.value):Me.create(M(n.createdAt));case W.JSON_ARRAY:return n.value?Up(n.value):Ve.create(M(n.createdAt));case W.TEXT:return ot.create(hs.create(),M(n.createdAt));case W.TREE:return zp(n.value);case W.NULL:case W.BOOLEAN:case W.INTEGER:case W.LONG:case W.DOUBLE:case W.STRING:case W.BYTES:case W.DATE:return le.of(le.valueFromBytes(Ef(n.type),n.value),M(n.createdAt));case W.INTEGER_CNT:case W.LONG_CNT:return We.create(Qi(n.type),We.valueFromBytes(Qi(n.type),n.value),M(n.createdAt))}}function fi(n){return wt.of(Ut.of(M(n.createdAt),n.offset),n.relativeOffset)}function Cf(n){return Ut.of(M(n.createdAt),n.offset)}function Np(n){const e=Ks.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{e.setAttr(r,s.value,M(s.updatedAt))});const t=pr.create(Cf(n.id),e);return t.remove(M(n.removedAt)),t}function Wr(n){return pt.of(Ns(n.parentId),Ns(n.leftSiblingId))}function Ns(n){return Ae.of(M(n.createdAt),n.offset)}function Pp(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=sc(t.content);e.push(r)}),e}function sc(n){if(n.length===0)return;const e=[];for(const s of n)e.push(Dp(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(),at.create(t,vt).getRoot()}function Op(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 Dp(n){const e=Ns(n.id),t=Ke.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=Op(n.attributes)),n.insPrevId&&(t.insPrevID=Ns(n.insPrevId)),n.insNextId&&(t.insNextID=Ns(n.insNextId)),t.removedAt=M(n.removedAt),t}function Nf(n){if(n.body.case==="set"){const e=n.body.value;return Ur.create(e.key,Bo(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Hs.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Bo(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 br.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)}),Gs.create(M(e.parentCreatedAt),fi(e.from),fi(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)}),_s.create(M(e.parentCreatedAt),fi(e.from),fi(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 ds.create(M(e.parentCreatedAt),Bo(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))}),Ys.create(M(e.parentCreatedAt),Wr(e.from),Wr(e.to),Pp(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?Zn.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Wr(e.from),Wr(e.to),s,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),Zn.create(M(e.parentCreatedAt),Wr(e.from),Wr(e.to),s,t,M(e.executedAt)))}else throw new w(y.ErrUnimplemented,"unimplemented operation")}}function Bp(n){const e=[];for(const t of n){const r=Nf(t);r&&e.push(r)}return e}function Pf(n){const e=[];for(const t of n)e.push(fs.create({id:kf(t.id),operations:Bp(t.operations),presenceChange:t.presenceChange?Ep(t.presenceChange):void 0,message:t.message}));return e}function Rp(n){return ns.of(BigInt(n.serverSeq),n.clientSeq)}function Fp(n){return mo.create(n.documentKey,Rp(n.checkpoint),n.isRemoved,Pf(n.changes),n.snapshot,M(n.minSyncedTicket))}function Of(n){const e=new Us;for(const r of n.nodes){const s=ic(r.element);e.set(r.key,s,s.getPositionedAt())}const t=new Me(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Df(n){const e=new zs;for(const r of n.nodes)e.insert(ic(r.element));const t=new Ve(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Lp(n){const e=le.of(le.valueFromBytes(Ef(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Jp(n){const e=new hs;let t=e.getHead();for(const s of n.nodes){const i=e.insertAfter(t,Np(s));s.insPrevId&&i.setInsPrev(e.findNode(Cf(s.insPrevId))),t=i}const r=new ot(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function Mp(n){const e=We.create(Qi(n.type),We.valueFromBytes(Qi(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Bf(n){const e=sc(n.nodes);return at.create(e,M(n.createdAt))}function ic(n){if(n.body.case==="jsonObject")return Of(n.body.value);if(n.body.case==="jsonArray")return Df(n.body.value);if(n.body.case==="primitive")return Lp(n.body.value);if(n.body.case==="text")return Jp(n.body.value);if(n.body.case==="counter")return Mp(n.body.value);if(n.body.case==="tree")return Bf(n.body.value);throw new w(y.ErrUnimplemented,"unimplemented element")}function $p(n){if(!n)return{root:Me.create(vt),presences:new Map};const e=Xo.fromBinary(n);return{root:ic(e.root),presences:Cp(e.presences)}}function Rf(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(n);return Of(e.body.value)}function Ff(n){return nc(n).toBinary()}function Up(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(n);return Df(e.body.value)}function qp(n){return Sf(n).toBinary()}function zp(n){if(!n)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(n);return Bf(e.body.value)}function Kp(n){return xf(n).toBinary()}function Lf(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function oc(n){return Lf(n)}function Jf(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ac(n){return Jf(n)}function jp(n){const e=ho.fromBinary(n);return kf(e)}function Vp(n){const e=_a.fromBinary(n);return Nf(e)}const be={fromPresence:rc,toChangePack:kp,fromChangePack:Fp,fromChanges:Pf,toTreeNodes:tc,fromTreeNodes:sc,objectToBytes:Ff,bytesToObject:Rf,bytesToSnapshot:$p,bytesToHex:Lf,hexToBytes:Jf,toHexString:oc,toUint8Array:ac,toOperation:If,toChangeID:bf,PbChangeID:ho,bytesToChangeID:jp,bytesToOperation:Vp};var Be=(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))(Be||{});let kr=3;function Mf(n){kr=n}const K={trivial:(...n)=>{kr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{kr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{kr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{kr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{kr>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=>kr<=n};function $f(){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 Wp{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===xi.RealtimeSyncOff?!1:this.syncMode===xi.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==xi.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 Ro=()=>{};class Hp{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=Ro),s.error===void 0&&(s.error=Ro),s.complete===void 0&&(s.complete=Ro);const i=$f(),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 Yr{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=uf,this.root=t,this.operations=[],this.previousPresence=ft(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,r,s){return new Yr(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 fs.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 js{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 ot||t instanceof at)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new js(Me.create(vt))}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 mr&&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 mr&&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 mr&&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 js(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r);s.element.getRemovedAt()&&e.compare(s.element.getRemovedAt())>=0&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s!==void 0&&e.compare(s)>=0&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}}function Uf(n,e){const t=new Vs(n);return new Proxy(e,t.getHandlers())}class Vs{constructor(e){c(this,"context");c(this,"handlers");this.context=e,this.handlers={set:(t,r,s)=>(K.isEnabled(Be.Trivial)&&K.trivial(`obj[${r}]=${JSON.stringify(s)}`),Vs.setInternal(e,t,r,s),!0),get:(t,r)=>(K.isEnabled(Be.Trivial)&&K.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():Er(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(K.isEnabled(Be.Trivial)&&K.trivial(`obj[${r}]`),Vs.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=eo(e,s,i),a=t.set(r,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ur.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=eo(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(br.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function _p(n,e){const t=new de(n,e);return new Proxy(e,t.getHandlers())}function Yp(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Xp(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class de{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 ar(e,a)}:s==="getElementByIndex"?o=>{const a=r.get(o);return ar(e,a)}:s==="getLast"?()=>ar(e,r.getLast()):s==="deleteByID"?o=>{const a=de.deleteInternalByID(e,r,o);return ar(e,a)}:s==="insertAfter"?(o,a)=>{const u=de.insertAfterInternal(e,r,o,a);return ar(e,u)}:s==="insertBefore"?(o,a)=>{const u=de.insertBeforeInternal(e,r,o,a);return ar(e,u)}:s==="moveBefore"?(o,a)=>{de.moveBeforeInternal(e,r,o,a)}:s==="moveAfter"?(o,a)=>{de.moveAfterInternal(e,r,o,a)}:s==="moveFront"?o=>{de.moveFrontInternal(e,r,o)}:s==="moveLast"?o=>{de.moveLastInternal(e,r,o)}:Yp(s)?Er(e,r.get(Number(s))):s==="push"?o=>de.pushInternal(e,r,o):s==="splice"?(o,a,...u)=>de.splice(e,r,o,a,...u):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?de.iteratorInternal.bind(this,e,r):s==="includes"?(o,a)=>de.includes(e,r,o,a):s==="indexOf"?(o,a)=>de.indexOf(e,r,o,a):s==="lastIndexOf"?(o,a)=>de.lastIndexOf(e,r,o,a):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>de.toTestString(r):typeof s=="string"&&Xp(s)?(...o)=>{const a=Array.from(r).map(u=>Er(e,u));return Array.prototype[s].apply(a,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(K.isEnabled(Be.Trivial)&&K.trivial(`array[${s}]`),de.deleteInternalByIndex(e,r,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield ar(e,r)}static buildArrayElements(e,t){const r=[];for(const s of t){const i=e.issueTimeTicket(),o=eo(e,s,i);r.push(o)}return r}static pushInternal(e,t,r){return de.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(fr.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,r,s){const i=e.issueTimeTicket();t.moveAfter(r,s,i),e.push(fr.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(fr.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(fr.create(t.getCreatedAt(),i,r,s))}static insertAfterInternal(e,t,r,s){const i=e.issueTimeTicket(),o=eo(e,s,i);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Hs.create(t.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,r,s){return de.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(br.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(br.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(le.isSupport(r))return Array.from(t).map(l=>Er(e,l)).includes(r,o);for(let u=o;u=i)return-1;if(le.isSupport(r))return Array.from(t).map(l=>Er(e,l)).indexOf(r,o);for(let u=o;u=i?i-1:s<0?s+i:s;if(o<0)return-1;if(le.isSupport(r))return Array.from(t).map(l=>Er(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 po{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(Be.Debug)&&K.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${r}`);const o=s?us(s):void 0,a=this.context.issueTimeTicket(),[u,,l,h]=this.text.edit(i,r,a,o);for(const g of l)this.context.registerGCPair(g);return this.context.push(new Gs(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(Be.Debug)&&K.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=us(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 _s(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([wt.fromStruct(e[0]),wt.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 yo{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=le.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ds.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 cc(n,e,t){const{type:r}=n,s=t.issueTimeTicket();if(r===Xn){qf(n);const{value:i}=n,o=Ke.create(Ae.of(s,0),r,i);e.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!cf(o)){const l=us(o);a=new tr;for(const[h,g]of Object.entries(l))a.set(h,g,s)}const u=Ke.create(Ae.of(s,0),r,void 0,a);e.append(u);for(const l of i)cc(l,u,t)}}function Zp(n,e){const{type:t}=e,r=n.issueTimeTicket();let s;if(e.type===Xn){const{value:i}=e;s=Ke.create(Ae.of(r,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!cf(o)){const u=us(o);a=new tr;for(const[l,h]of Object.entries(u))a.set(l,h,r)}s=Ke.create(Ae.of(n.issueTimeTicket(),0),t,void 0,a);for(const u of i)cc(u,s,n)}return s}function qf(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===Xn)for(const t of n){const{type:r}=t;if(r!==Xn)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together");qf(t)}else for(const t of n){const{type:r}=t;if(r===Xn)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class vo{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 Ke.create(Ae.of(e.issueTimeTicket(),0),Qm);const t=Ke.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)cc(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?us(t):void 0,[a]=this.tree.style([r,s],o,i);this.context.push(Zn.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?us(r):void 0,[u,l]=this.tree.style([s,i],a,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Zn.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(Zn.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!==Xn))for(const h of r){const{children:g=[]}=h;Ju(g)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=r[0])==null?void 0:l.type)===Xn){let h="";for(const g of r){const{value:v}=g;h+=v}o.push(Ke.create(Ae.of(this.context.issueTimeTicket(),0),Xn,h))}else o=r.map(h=>h&&Zp(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(Ys.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=[pt.fromStruct(e[0]),pt.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=[pt.fromStruct(e[0]),pt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function Mu(n,e){return Uf(n,e)}function ar(n,e){if(e){if(e instanceof le)return e;if(e instanceof Me)return Uf(n,e);if(e instanceof Ve)return _p(n,e);if(e instanceof ot)return new po(n,e);if(e instanceof We){const t=new yo(qt.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof at){const t=new vo;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Er(n,e){const t=ar(n,e);return t instanceof le?t.getValue():t}function eo(n,e,t){let r;if(le.isSupport(e))r=le.of(e,t);else if(Array.isArray(e))r=Ve.create(t,de.buildArrayElements(n,e));else if(typeof e=="object")e instanceof po?(r=ot.create(hs.create(),t),e.initialize(n,r)):e instanceof yo?(r=We.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof vo?(r=at.create(e.buildRoot(n),t),e.initialize(n,r)):r=Me.create(t,Vs.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const $u=50;class Qp{constructor(){c(this,"undoStack",[]);c(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=$u&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=$u&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const ey="yorkie-devtools-panel",ty="yorkie-devtools-sdk";let Gr="disconnected";const Uu=new Map,Si=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Si);function hi(n,e){(e!=null&&e.force||Gr!=="disconnected")&&window.postMessage({source:ty,...n},"*")}function ny(n){if(!n.isEnableDevtools()||typeof window>"u"||Uu.has(n.getKey()))return;Si.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==Le.StatusChanged&&r.type!==Le.Snapshot&&r.type!==Le.LocalChange&&r.type!==Le.RemoteChange&&r.type!==Le.Initialized&&r.type!==Le.Watched&&r.type!==Le.Unwatched&&r.type!==Le.PresenceChanged)||(Si.get(n.getKey()).push(t),Gr==="synced"&&hi({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Uu.set(n.getKey(),[e]),hi({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==ey)return;switch(t.data.msg){case"devtools::connect":if(Gr!=="disconnected")break;Gr="connected",hi({msg:"doc::available",docKey:n.getKey()}),K.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Gr="disconnected",K.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Gr="synced",hi({msg:"doc::sync::full",docKey:n.getKey(),events:Si.get(n.getKey())}),K.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var cr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(cr||{}),Le=(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))(Le||{}),Ia=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Ia||{}),Sa=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Sa||{});class zf{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=js.create(),this.changeID=ap,this.checkpoint=cp,this.localChanges=[],this.eventStream=Gp(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Qp,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ny(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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const i=Mu(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(i,new Oo(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){K.isEnabled(Be.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,se.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:se.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:se.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(l),K.isEnabled(Be.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==="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])}applyChangePack(e){for(e.hasSnapshot()?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();e.hasSnapshot()&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),this.garbageCollect(e.getMinSyncedTicket()),e.getIsRemoved()&&this.applyStatus("removed"),K.isEnabled(Be.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:ft(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return mo.create(this.key,t,!1,e)}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Mu(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t){const{root:r,presences:s}=be.bytesToSnapshot(t);this.root=new js(r),this.presences=s,this.changeID=this.changeID.syncLamport(e),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{snapshot:this.isEnableDevtools()?be.bytesToHex(t):void 0,serverSeq:e.toString()}}])}applyChanges(e,t){K.isEnabled(Be.Debug)&&K.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),K.isEnabled(Be.Trivial)&&K.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` -`));for(const r of e)this.applyChange(r,t);K.isEnabled(Be.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 wr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:s,presence:o.presence}});break;case wr.Clear:r.push({type:"unwatched",source:se.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===se.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:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,s=[];if(t===Jr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:se.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===Jr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:se.Remote,value:{clientID:r,presence:i}})}else if(t===Jr.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(Xa),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:r}=e.value;if(!t)return;this.applySnapshot(BigInt(r),be.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=fs.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?ft(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?ft(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?ft(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:ft(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:ft(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new 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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof bt)){new Oo(t,ft(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,se.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,se.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:se.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:se.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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof bt)){new Oo(t,ft(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,se.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,se.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:se.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:se.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])}}function ry(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const sy="yorkie-js-sdk",iy="0.5.1",oy="Yorkie JS SDK",ay="./src/yorkie.ts",cy={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},uy=["dist"],ly={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"},fy={node:">=18.0.0",npm:">=7.1.0"},hy={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},dy={name:"hackerwins",email:"susukang98@gmail.com"},gy="Apache-2.0",my={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},py="https://github.com/yorkie-team/yorkie-js-sdk#readme",yy={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},vy={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},qu={name:sy,version:iy,description:oy,main:ay,publishConfig:cy,files:uy,scripts:ly,engines:fy,repository:hy,author:dy,license:gy,bugs:my,homepage:py,devDependencies:yy,dependencies:vy};function wy(){return n=>async e=>(e.header.set("x-yorkie-user-agent",qu.name+"/"+qu.version),await n(e))}const by=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var xi=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(xi||{});const di={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Fo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Kf{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"taskQueue");c(this,"processing",!1);t=t||di,this.key=t.key?t.key:$f(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||di.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||di.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||di.retrySyncLoopDelay,this.rpcClient=wm(zm,qm({baseUrl:e,interceptors:[ry(t.apiKey,t.token),wy()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),K.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw K.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),K.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw K.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==cr.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(g){g instanceof Error&&(u==null||u(g))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:be.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=be.fromChangePack(i.changePack);return e.applyChangePack(o),e.getStatus()===cr.Removed||(e.applyStatus(cr.Attached),this.attachmentMap.set(e.getKey(),new Wp(this.reconnectStreamDelay,e,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(e.getKey()),K.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(i=>{throw K.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new 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:be.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=be.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==cr.Removed&&e.applyStatus(cr.Detached),this.detachInternal(e.getKey()),K.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw K.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new 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(r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),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=be.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=be.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),K.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw K.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,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(!by(r))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??Fo.maxRetries,a=Fo.maxBackoff;let u=0;const l=g=>Math.min(Fo.initialRetryInterval*2**g,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(g=>{if(K.error(`[BC] c:"${this.getKey()}" err:`,g),this.handleConnectError(g))if(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`),g;else throw g}));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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{K.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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:Le.ConnectionChanged,value:Ia.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:Le.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Le.ConnectionChanged,value:Ia.Disconnected}]),K.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?r():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Jr.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(cr.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:be.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=be.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Le.SyncStatusChanged,value:Sa.Synced}]),r.getStatus()===cr.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(o=>{throw r.publish([{type:Le.SyncStatusChanged,value:Sa.SyncFailed}]),K.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof ve?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((Lu(e)===y.ErrClientNotActivated||Lu(e)===y.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{K.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const jf={Client:Kf,Document:zf,Primitive:le,Text:po,Counter:yo,Tree:vo,LogLevel:Be,setLogLevel:Mf,IntType:qt.IntegerCnt,LongType:qt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Kf,Document:zf,Primitive:le,Text:po,Counter:yo,Tree:vo,LogLevel:Be,setLogLevel:Mf,IntType:qt.IntegerCnt,LongType:qt.LongCnt});const Ty=(n,e)=>{const t=n.__vccOpts||n;for(const[r,s]of e)t[r]=s;return t},Ay=[{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"}]}],or=new jf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Vt=new jf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Iy={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 or.activate(),await or.attach(Vt),Vt.update(n=>{n.lists||(n.lists=Ay)},"create default list if not exists"),Vt.subscribe(n=>{this.lists=Vt.getRoot().lists}),await or.sync(),this.lists=Vt.getRoot().lists},async disconnect(){await or.deactivate()},isOpened(n){return this.opened===n},openForm(n){this.opened=n},closeForm(){this.opened=null},addCard(n){this.title!==""&&Vt.update(e=>{e.lists.getElementByID(n.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${or.getID()}`)},deleteCard(n,e){Vt.update(t=>{t.lists.getElementByID(n.getID()).cards.deleteByID(e.getID())},`delete a card by ${or.getID()}`)},addList(){this.title!==""&&Vt.update(n=>{n.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${or.getID()}`)},deleteList(n){Vt.update(e=>{e.lists.deleteByID(n.getID())},`delete a list by ${or.getID()}`)}}},Sy={class:"list"},xy=["onClick"],ky={class:"title"},Ey={class:"card"},Cy=["onClick"],Ny={key:0,class:"add-form"},Py=["onKeyup"],Oy={class:"buttons"},Dy=["onClick"],By=["onClick"],Ry={class:"add-list",ref:"addListForm"},Fy={key:0,class:"add-form"},Ly={class:"buttons"};function Jy(n,e,t,r,s,i){return Kt(),jt(Ge,null,[(Kt(!0),jt(Ge,null,Nc(s.lists,(o,a)=>(Kt(),jt("div",Sy,[Oe("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,xy),Oe("div",ky,vc(o.title),1),(Kt(!0),jt(Ge,null,Nc(o.cards,u=>(Kt(),jt("div",Ey,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Cy),Nl(" "+vc(u.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Kt(),jt("div",Ny,[Cc(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[ai(u=>i.addCard(o),["enter"]),e[1]||(e[1]=ai(u=>i.closeForm(),["esc"]))]},null,40,Py),[[Yc,s.title]]),Oe("div",Oy,[Oe("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,Dy),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,By))],512)]))),256)),Oe("div",Ry,[i.isOpened(0)?(Kt(),jt("div",Fy,[Cc(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=ai(o=>i.addList(),["enter"])),e[5]||(e[5]=ai(o=>i.closeForm(),["esc"]))]},null,544),[[Yc,s.title]]),Oe("div",Ly,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const My=Ty(Iy,[["render",Jy]]);wg(My).mount("#app"); +`));for(const r of e)this.applyChange(r,t);K.isEnabled(Be.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 wr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:s,presence:o.presence}});break;case wr.Clear:r.push({type:"unwatched",source:se.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncLamport(e.getID().getLamport()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===se.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:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,s=[];if(t===Jr.DOCUMENT_WATCHED)this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:se.Remote,value:{clientID:r,presence:this.getPresence(r)}});else if(t===Jr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:se.Remote,value:{clientID:r,presence:i}})}else if(t===Jr.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(Xa),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:r}=e.value;if(!t)return;this.applySnapshot(BigInt(r),be.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=fs.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?ft(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?ft(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?ft(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:ft(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:ft(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new 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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof bt)){new Oo(t,ft(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,se.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,se.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:se.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:se.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=Yr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof bt)){new Oo(t,ft(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,se.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,se.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:se.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:se.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])}}function ry(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const sy="yorkie-js-sdk",iy="0.5.2",oy="Yorkie JS SDK",ay="./src/yorkie.ts",cy={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},uy=["dist"],ly={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"},fy={node:">=18.0.0",npm:">=7.1.0"},hy={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},dy={name:"hackerwins",email:"susukang98@gmail.com"},gy="Apache-2.0",my={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},py="https://github.com/yorkie-team/yorkie-js-sdk#readme",yy={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},vy={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},qu={name:sy,version:iy,description:oy,main:ay,publishConfig:cy,files:uy,scripts:ly,engines:fy,repository:hy,author:dy,license:gy,bugs:my,homepage:py,devDependencies:yy,dependencies:vy};function wy(){return n=>async e=>(e.header.set("x-yorkie-user-agent",qu.name+"/"+qu.version),await n(e))}const by=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var xi=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(xi||{});const di={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Fo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Kf{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"taskQueue");c(this,"processing",!1);t=t||di,this.key=t.key?t.key:$f(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||di.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||di.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||di.retrySyncLoopDelay,this.rpcClient=wm(zm,qm({baseUrl:e,interceptors:[ry(t.apiKey,t.token),wy()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),K.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw K.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),K.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw K.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==cr.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(g){g instanceof Error&&(u==null||u(g))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:be.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=be.fromChangePack(i.changePack);return e.applyChangePack(o),e.getStatus()===cr.Removed||(e.applyStatus(cr.Attached),this.attachmentMap.set(e.getKey(),new Wp(this.reconnectStreamDelay,e,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(e.getKey()),K.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`)),e}).catch(i=>{throw K.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new 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:be.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=be.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==cr.Removed&&e.applyStatus(cr.Detached),this.detachInternal(e.getKey()),K.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw K.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new 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(r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw K.error(`[SY] c:"${this.getKey()}" err :`,r),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=be.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=be.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),K.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw K.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,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(!by(r))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??Fo.maxRetries,a=Fo.maxBackoff;let u=0;const l=g=>Math.min(Fo.initialRetryInterval*2**g,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(g=>{if(K.error(`[BC] c:"${this.getKey()}" err:`,g),this.handleConnectError(g))if(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`),g;else throw g}));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)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{K.error(`[SL] c:"${this.getKey()}" sync failed:`,r),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:Le.ConnectionChanged,value:Ia.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:Le.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Le.ConnectionChanged,value:Ia.Disconnected}]),K.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?r():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Jr.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(cr.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:be.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=be.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:Le.SyncStatusChanged,value:Sa.Synced}]),r.getStatus()===cr.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(o=>{throw r.publish([{type:Le.SyncStatusChanged,value:Sa.SyncFailed}]),K.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof ve?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((Lu(e)===y.ErrClientNotActivated||Lu(e)===y.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{K.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const jf={Client:Kf,Document:zf,Primitive:le,Text:po,Counter:yo,Tree:vo,LogLevel:Be,setLogLevel:Mf,IntType:qt.IntegerCnt,LongType:qt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Kf,Document:zf,Primitive:le,Text:po,Counter:yo,Tree:vo,LogLevel:Be,setLogLevel:Mf,IntType:qt.IntegerCnt,LongType:qt.LongCnt});const Ty=(n,e)=>{const t=n.__vccOpts||n;for(const[r,s]of e)t[r]=s;return t},Ay=[{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"}]}],or=new jf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Vt=new jf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Iy={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 or.activate(),await or.attach(Vt),Vt.update(n=>{n.lists||(n.lists=Ay)},"create default list if not exists"),Vt.subscribe(n=>{this.lists=Vt.getRoot().lists}),await or.sync(),this.lists=Vt.getRoot().lists},async disconnect(){await or.deactivate()},isOpened(n){return this.opened===n},openForm(n){this.opened=n},closeForm(){this.opened=null},addCard(n){this.title!==""&&Vt.update(e=>{e.lists.getElementByID(n.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${or.getID()}`)},deleteCard(n,e){Vt.update(t=>{t.lists.getElementByID(n.getID()).cards.deleteByID(e.getID())},`delete a card by ${or.getID()}`)},addList(){this.title!==""&&Vt.update(n=>{n.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${or.getID()}`)},deleteList(n){Vt.update(e=>{e.lists.deleteByID(n.getID())},`delete a list by ${or.getID()}`)}}},Sy={class:"list"},xy=["onClick"],ky={class:"title"},Ey={class:"card"},Cy=["onClick"],Ny={key:0,class:"add-form"},Py=["onKeyup"],Oy={class:"buttons"},Dy=["onClick"],By=["onClick"],Ry={class:"add-list",ref:"addListForm"},Fy={key:0,class:"add-form"},Ly={class:"buttons"};function Jy(n,e,t,r,s,i){return Kt(),jt(Ge,null,[(Kt(!0),jt(Ge,null,Nc(s.lists,(o,a)=>(Kt(),jt("div",Sy,[Oe("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,xy),Oe("div",ky,vc(o.title),1),(Kt(!0),jt(Ge,null,Nc(o.cards,u=>(Kt(),jt("div",Ey,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Cy),Nl(" "+vc(u.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Kt(),jt("div",Ny,[Cc(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[ai(u=>i.addCard(o),["enter"]),e[1]||(e[1]=ai(u=>i.closeForm(),["esc"]))]},null,40,Py),[[Yc,s.title]]),Oe("div",Oy,[Oe("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,Dy),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,By))],512)]))),256)),Oe("div",Ry,[i.isOpened(0)?(Kt(),jt("div",Fy,[Cc(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=ai(o=>i.addList(),["enter"])),e[5]||(e[5]=ai(o=>i.closeForm(),["esc"]))]},null,544),[[Yc,s.title]]),Oe("div",Ly,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const My=Ty(Iy,[["render",Jy]]);wg(My).mount("#app"); diff --git a/examples/vuejs-kanban/index.html b/examples/vuejs-kanban/index.html index 53239ab95..7b644c76b 100644 --- a/examples/vuejs-kanban/index.html +++ b/examples/vuejs-kanban/index.html @@ -6,7 +6,7 @@ Vite App - +