All files / json-crdt/model/api nodes.ts

85.35% Statements 402/471
74.71% Branches 130/174
89.13% Functions 82/92
91.51% Lines 345/377

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x 173x                 173x         173x 135x 135x 135x 135x       84x   51x 51x 51x                   173x   29398x 29398x       29398x                         728x 728x                   7839x       7839x 286x 286x 286x       286x       7553x 7553x 7553x 7553x                     7518x 7518x       29x 1x       5352x         14x         1527x         26x         84x         10x                                       4221x 4221x 4221x 4221x 4221x 4221x 4221x 288x         25x       5347x       14x       1523x       23x       84x       10x       4779x       248x 248x 224x 224x   24x         210x 210x 123x 118x 118x 118x       76x 76x 76x 76x 36x 40x 34x 34x 34x 34x   25x 25x   31x 31x 31x 31x 11x 5x 5x 5x   6x 4x 2x 71x   5x       28x 28x 28x 28x 14x 14x 10x 14x 2x 2x 2x   2x 2x   2x 2x 2x 12x   24x   4x       31x 31x 31x 31x 2x 2x 1x 29x 27x 27x 27x 19x   19x 19x   27x 26x 2x 2x   28x   3x       1x       11x       84x 84x 84x   33x   22x   9x   20x                 34x 34x 34x   9x                               173x         10x                 173x           9x                   14286x 14286x 14286x 14286x 14286x               3991x 3991x     3988x 3988x     3991x                     173x               12x                   10866x 10866x 10866x   42816x   10866x       3x 6x                 4x               3941x       3941x 3927x                 3941x                     173x               6x                   124x 124x 124x   132x   124x                   13x 13x 13x   15x   13x                   16x               4026x       4030x 4017x 4017x 4017x 4017x       4026x                     173x                 430409x 430409x 430409x 430409x 430409x 430409x 430409x 430409x 430409x 430409x                     110396x 110396x 110396x 110396x 110396x 110396x 110396x 110396x 110396x                     19x 19x 19x 19x 19x 17x 17x                       19x 19x 19x 17x 17x 17x 17x                 61x             17x                     173x                 15x 15x 15x 15x 15x                     8x 8x 8x 8x 8x                 8x             3x                         173x               151x                   64x 64x 64x 64x 64x 89x 64x 64x                 4x 4x                   29x 29x 29x 29x 29x 29x                     44x 44x 44x 44x 44x                 224x                 11x       11x 8x 8x 8x 8x 8x       11x                   173x                     14937x     14937x   14937x   14937x   14937x   14937x   14937x         14937x   14937x   14937x   14937x           14937x   14937x         14937x 14937x 14937x 14937x 14937x 14937x 14937x 14937x                                 49371x 49309x 27314x 27275x 23979x 19594x 19447x 4222x 4221x 2197x 2197x 1x                               14274x 14274x               52134x 52134x 52134x 52134x 52134x 497549x 52133x 52133x 52133x                         540805x 540805x 540805x 540805x     14937x   98x   97x 97x 97x 97x 85x   97x                       13884x 13884x 13884x 13884x     14937x                                                 14937x 14937x    
import {printTree} from 'tree-dump/lib/printTree';
import {get} from '@jsonjoy.com/json-pointer/lib/get';
import {toPath} from '@jsonjoy.com/json-pointer/lib/util';
import {find} from './find';
import {type ITimestampStruct, Timestamp} from '../../../json-crdt-patch/clock';
import {ObjNode, ArrNode, BinNode, ConNode, VecNode, ValNode, StrNode, RootNode} from '../../nodes';
import {NodeEvents} from './NodeEvents';
import {FanOut} from 'thingies/lib/fanout';
import {PatchBuilder} from '../../../json-crdt-patch/PatchBuilder';
import {MergeFanOut, MicrotaskBufferFanOut} from './fanout';
import {ExtNode} from '../../extensions/ExtNode';
import * as diff from '../../../json-crdt-diff';
import type {Path} from '@jsonjoy.com/json-pointer';
import type {Extension} from '../../extensions/Extension';
import type {ExtApi} from '../../extensions/types';
import type * as types from './proxy';
import type {Printable} from 'tree-dump/lib/types';
import type {ApiOperation, ApiPath, JsonNodeApi} from './types';
import type {VecNodeExtensionData} from '../../schema/types';
import type {Patch} from '../../../json-crdt-patch';
import {type JsonNodeToProxyPathNode, proxy$} from './proxy';
import type {SyncStore} from '../../../util/events/sync-store';
import type {Model} from '../Model';
import type {JsonNode, JsonNodeView} from '../../nodes';
 
const breakPath = (path: ApiPath): [parent: Path | undefined, key: string | number] => {
  Iif (!path) return [void 0, ''];
  Iif (typeof path === 'number') return [void 0, path];
  if (typeof path === 'string') path = toPath(path);
  switch (path.length) {
    case 0:
      return [void 0, ''];
    case 1:
      return [void 0, path[0]];
    default: {
      const key = path[path.length - 1];
      const parent = path.slice(0, -1);
      return [parent, key];
    }
  }
};
 
/**
 * A generic local changes API for a JSON CRDT node.
 *
 * @category Local API
 */
export class NodeApi<N extends JsonNode = JsonNode> implements Printable {
  constructor(
    public node: N,
    public readonly api: ModelApi<any>,
  ) {}
 
  /** @ignore */
  private ev: undefined | NodeEvents<N> = undefined;
 
  /**
   * Event target for listening to node changes. You can subscribe to `"view"`
   * events, which are triggered every time the node's view changes.
   *
   * ```ts
   * node.events.on('view', () => {
   *   // do something...
   * });
   * ```
   */
  public get events(): NodeEvents<N> {
    const et = this.ev;
    return et || (this.ev = new NodeEvents<N>(this));
  }
 
  /**
   * Find a child node at the given path starting from this node.
   *
   * @param path Path to the child node to find.
   * @returns JSON CRDT node at the given path.
   */
  public find(path?: ApiPath): JsonNode {
    let node: JsonNode<any> = this.node;
    /**
     * @todo Remove this .child() loop, and remove the `.child()` method from JsonNode interface.
     */
    if (path === undefined) {
      if (typeof node.child === 'function') {
        const child = node.child();
        Iif (!child) {
          Iif (node instanceof RootNode) return node;
          throw new Error('NO_CHILD');
        }
        return child;
      }
      throw new Error('CANNOT_IN');
    }
    if (typeof path === 'string' && !!path && path[0] !== '/') path = '/' + path;
    if (typeof path === 'number') path = [path];
    while (node instanceof ValNode) node = node.child()!;
    return find(node, path);
  }
 
  /**
   * Find a child node at the given path starting from this node and wrap it in
   * a local changes API.
   *
   * @param path Path to the child node to find.
   * @returns Local changes API for the child node at the given path.
   */
  public in(path?: ApiPath) {
    const node = this.find(path);
    return this.api.wrap(node as any);
  }
 
  public asVal(): ValApi {
    if (this.node instanceof ValNode) return this.api.wrap(this.node as ValNode);
    throw new Error('NOT_VAL');
  }
 
  public asStr(): StrApi {
    if (this.node instanceof StrNode) return this.api.wrap(this.node);
    throw new Error('NOT_STR');
  }
 
  public asBin(): BinApi {
    if (this.node instanceof BinNode) return this.api.wrap(this.node);
    throw new Error('NOT_BIN');
  }
 
  public asArr(): ArrApi {
    if (this.node instanceof ArrNode) return this.api.wrap(this.node);
    throw new Error('NOT_ARR');
  }
 
  public asVec(): VecApi {
    if (this.node instanceof VecNode) return this.api.wrap(this.node as VecNode);
    throw new Error('NOT_VEC');
  }
 
  public asObj(): ObjApi {
    if (this.node instanceof ObjNode) return this.api.wrap(this.node as ObjNode);
    throw new Error('NOT_OBJ');
  }
 
  public asCon(): ConApi {
    if (this.node instanceof ConNode) return this.api.wrap(this.node);
    throw new Error('NOT_CON');
  }
 
  /**
   * Returns the API object of the extension if the node is an extension node.
   * When the `ext` parameter is provided, it checks if the node is an instance
   * of the given extension and returns the object's TypeScript type. Otherwise,
   * it returns the API object of the extension, but without any type checking.
   *
   * @param ext Extension of the node
   * @returns API of the extension
   */
  public asExt(): JsonNodeApi<VecNodeExtensionData<N>> | ExtApi<any> | undefined;
  public asExt<EN extends ExtNode<any, any>, EApi extends ExtApi<EN>>(
    ext: Extension<any, any, EN, EApi, any, any>,
  ): EApi;
  public asExt<EN extends ExtNode<any, any>, EApi extends ExtApi<EN>>(
    ext?: Extension<any, any, EN, EApi, any, any>,
  ): EApi {
    let extNode: ExtNode<any> | undefined = undefined;
    const node: JsonNode | undefined = this.node;
    Iif (node instanceof ExtNode) extNode = node;
    if (node instanceof VecNode) extNode = node.ext();
    Iif (!extNode) throw new Error('NOT_EXT');
    const api = this.api.wrap(extNode);
    if (!ext) return api as any;
    if (api instanceof ext.Api) return api;
    throw new Error('NOT_EXT');
  }
 
  public val(path?: ApiPath): ValApi {
    return this.in(path).asVal();
  }
 
  public str(path?: ApiPath): StrApi {
    return this.in(path).asStr();
  }
 
  public bin(path?: ApiPath): BinApi {
    return this.in(path).asBin();
  }
 
  public arr(path?: ApiPath): ArrApi {
    return this.in(path).asArr();
  }
 
  public vec(path?: ApiPath): VecApi {
    return this.in(path).asVec();
  }
 
  public obj(path?: ApiPath): ObjApi {
    return this.in(path).asObj();
  }
 
  public con(path?: ApiPath): ConApi {
    return this.in(path).asCon();
  }
 
  public view(): JsonNodeView<N> {
    return this.node.view() as unknown as JsonNodeView<N>;
  }
 
  public select(path?: ApiPath, leaf?: boolean) {
    try {
      let node = path !== void 0 ? this.find(path) : this.node;
      if (leaf) while (node instanceof ValNode) node = node.child();
      return this.api.wrap(node);
    } catch (e) {
      return;
    }
  }
 
  public read(path?: ApiPath): unknown {
    const view = this.view();
    if (Array.isArray(path)) return get(view, path);
    if (!path) return view;
    let path2: string = path + '';
    Iif (path && path2[0] !== '/') path2 = '/' + path2;
    return get(view, toPath(path2));
  }
 
  public add(path: ApiPath, value: unknown): boolean {
    const [parent, key] = breakPath(path);
    ADD: try {
      const node = this.select(parent, true);
      if (node instanceof ObjApi) {
        node.set({[key]: value});
      } else if (node instanceof ArrApi || node instanceof StrApi || node instanceof BinApi) {
        const length = node.length();
        let index: number = 0;
        Iif (typeof key === 'number') index = key;
        else if (key === '-') index = length;
        else {
          index = ~~key;
          if (index + '' !== key) break ADD;
        }
        Iif (index !== index) break ADD;
        Iif (index < 0) index = 0;
        if (index > length) index = length;
        if (node instanceof ArrApi) node.ins(index, Array.isArray(value) ? value : [value]);
        else if (node instanceof StrApi) node.ins(index, value + '');
        else if (node instanceof BinApi) {
          Iif (!(value instanceof Uint8Array)) break ADD;
          node.ins(index, value);
        }
      } else if (node instanceof VecApi) {
        node.set([[~~key, value]]);
      } else break ADD;
      return true;
    } catch {}
    return false;
  }
 
  public replace(path: ApiPath, value: unknown): boolean {
    const [parent, key] = breakPath(path);
    REPLACE: try {
      const node = this.select(parent, true);
      if (node instanceof ObjApi) {
        const keyStr = key + '';
        if (!node.has(keyStr)) break REPLACE;
        node.set({[key]: value});
      } else if (node instanceof ArrApi) {
        const length = node.length();
        let index: number = 0;
        Iif (typeof key === 'number') index = key;
        else {
          index = ~~key;
          Iif (index + '' !== key) break REPLACE;
        }
        Iif (index !== index || index < 0 || index > length) break REPLACE;
        Iif (index === length) node.ins(index, [value]);
        else node.upd(index, value);
      } else if (node instanceof VecApi) node.set([[~~key, value]]);
      else Ebreak REPLACE;
      return true;
    } catch {}
    return false;
  }
 
  public remove(path: ApiPath, length: number = 1): boolean {
    const [parent, key] = breakPath(path);
    REMOVE: try {
      const node = this.select(parent, true);
      if (node instanceof ObjApi) {
        const keyStr = key + '';
        if (!node.has(keyStr)) break REMOVE;
        node.del([keyStr]);
      } else if (node instanceof ArrApi || node instanceof StrApi || node instanceof BinApi) {
        const len = node.length();
        let index: number = 0;
        if (typeof key === 'number') index = key;
        else Iif (key === '-') index = length;
        else {
          index = ~~key;
          Iif (index + '' !== key) break REMOVE;
        }
        if (index !== index || index < 0 || index > len) break REMOVE;
        node.del(index, Math.min(length, len - index));
      } else if (node instanceof VecApi) {
        node.set([[~~key, void 0]]);
      } else Ebreak REMOVE;
      return true;
    } catch {}
    return false;
  }
 
  public diff(value: unknown): Patch | undefined {
    return diff.diff(this, value);
  }
 
  public merge(value: unknown): Patch | undefined {
    return diff.merge(this, value);
  }
 
  public op(operation: ApiOperation): boolean {
    Iif (!Array.isArray(operation)) return false;
    const [type, path, value] = operation;
    switch (type) {
      case 'add':
        return this.add(path, value);
      case 'replace':
        return this.replace(path, value);
      case 'merge':
        return !!this.select(path)?.merge(value);
      case 'remove':
        return this.remove(path, value);
    }
  }
 
  public get s(): types.ProxyNode<N> {
    return {$: this} as unknown as types.ProxyNode<N>;
  }
 
  public get $(): JsonNodeToProxyPathNode<N> {
    return proxy$((path) => {
      try {
        return this.api.wrap(this.find(path));
      } catch {
        return;
      }
    }, '$') as any;
  }
 
  public toString(tab: string = ''): string {
    const name = this.constructor === NodeApi ? '*' : this.node.name();
    return 'api(' + name + ')' + printTree(tab, [(tab) => this.node.toString(tab)]);
  }
}
 
/**
 * Represents the local changes API for the `con` JSON CRDT node {@link ConNode}.
 *
 * @category Local API
 */
export class ConApi<N extends ConNode<any> = ConNode<any>> extends NodeApi<N> {
  /**
   * Returns a proxy object for this node.
   */
  public get s(): types.ProxyNodeCon<N> {
    return {$: this} as unknown as types.ProxyNodeCon<N>;
  }
}
 
/**
 * Local changes API for the `val` JSON CRDT node {@link ValNode}.
 *
 * @category Local API
 */
export class ValApi<N extends ValNode<any> = ValNode<any>> extends NodeApi<N> {
  /**
   * Get API instance of the inner node.
   * @returns Inner node API.
   */
  public get(): JsonNodeApi<N extends ValNode<infer T> ? T : JsonNode> {
    return this.in() as any;
  }
 
  /**
   * Sets the value of the node.
   *
   * @param json JSON/CBOR value or ID (logical timestamp) of the value to set.
   * @returns Reference to itself.
   */
  public set(json: JsonNodeView<N>): void {
    const {api, node} = this;
    const builder = api.builder;
    const val = builder.constOrJson(json);
    api.builder.setVal(node.id, val);
    api.apply();
  }
 
  /**
   * Returns a proxy object for this node. Allows to access the value of the
   * node by accessing the `.val` property.
   */
  public get s(): types.ProxyNodeVal<N> {
    const self = this;
    const proxy = {
      $: this,
      get _() {
        const childNode = self.node.node();
        return (<any>self).api.wrap(childNode).s;
      },
    };
    return <any>proxy;
  }
}
 
type UnVecNode<N> = N extends VecNode<infer T> ? T : never;
 
/**
 * Local changes API for the `vec` JSON CRDT node {@link VecNode}.
 *
 * @category Local API
 */
export class VecApi<N extends VecNode<any> = VecNode<any>> extends NodeApi<N> {
  /**
   * Get API instance of a child node.
   *
   * @param key Object key to get.
   * @returns A specified child node API.
   */
  public get<K extends keyof UnVecNode<N>>(key: K): JsonNodeApi<UnVecNode<N>[K]> {
    return this.in(key as string) as any;
  }
 
  /**
   * Sets a list of elements to the given values.
   *
   * @param entries List of index-value pairs to set.
   * @returns Reference to itself.
   */
  public set(entries: [index: number, value: unknown][]): void {
    const {api, node} = this;
    const {builder} = api;
    builder.insVec(
      node.id,
      entries.map(([index, json]) => [index, builder.constOrJson(json)]),
    );
    api.apply();
  }
 
  public push(...values: unknown[]): void {
    const length = this.length();
    this.set(values.map((value, index) => [length + index, value]));
  }
 
  /**
   * Get the length of the vector without materializing it to a view.
   *
   * @returns Length of the vector.
   */
  public length(): number {
    return this.node.elements.length;
  }
 
  /**
   * Returns a proxy object for this node. Allows to access vector elements by
   * index.
   */
  public get s(): types.ProxyNodeVec<N> {
    const proxy = new Proxy(
      {},
      {
        get: (target, prop, receiver) => {
          if (prop === '$') return this;
          if (prop === 'toExt') return () => this.asExt();
          const index = Number(prop);
          Iif (Number.isNaN(index)) throw new Error('INVALID_INDEX');
          const child = this.node.get(index);
          Iif (!child) throw new Error('OUT_OF_BOUNDS');
          return (<any>this).api.wrap(child).s;
        },
      },
    );
    return proxy as types.ProxyNodeVec<N>;
  }
}
 
type UnObjNode<N> = N extends ObjNode<infer T> ? T : never;
 
/**
 * Local changes API for the `obj` JSON CRDT node {@link ObjNode}.
 *
 * @category Local API
 */
export class ObjApi<N extends ObjNode<any> = ObjNode<any>> extends NodeApi<N> {
  /**
   * Get API instance of a child node.
   *
   * @param key Object key to get.
   * @returns A specified child node API.
   */
  public get<K extends keyof UnObjNode<N>>(key: K): JsonNodeApi<UnObjNode<N>[K]> {
    return this.in(key as string) as any;
  }
 
  /**
   * Sets a list of keys to the given values.
   *
   * @param entries List of key-value pairs to set.
   * @returns Reference to itself.
   */
  public set(entries: Partial<JsonNodeView<N>>): void {
    const {api, node} = this;
    const {builder} = api;
    builder.insObj(
      node.id,
      Object.entries(entries).map(([key, json]) => [key, builder.constOrJson(json)]),
    );
    api.apply();
  }
 
  /**
   * Deletes a list of keys from the object.
   *
   * @param keys List of keys to delete.
   * @returns Reference to itself.
   */
  public del(keys: string[]): void {
    const {api, node} = this;
    const {builder} = api;
    api.builder.insObj(
      node.id,
      keys.map((key) => [key, builder.con(undefined)]),
    );
    api.apply();
  }
 
  /**
   * Checks if a key exists in the object.
   *
   * @param key Key to check.
   * @returns True if the key exists, false otherwise.
   */
  public has(key: string): boolean {
    return this.node.keys.has(key);
  }
 
  /**
   * Returns a proxy object for this node. Allows to access object properties
   * by key.
   */
  public get s(): types.ProxyNodeObj<N> {
    const proxy = new Proxy(
      {},
      {
        get: (target, prop, receiver) => {
          if (prop === '$') return this;
          const key = String(prop);
          const child = this.node.get(key);
          Iif (!child) throw new Error('NO_SUCH_KEY');
          return (<any>this).api.wrap(child).s;
        },
      },
    );
    return proxy as types.ProxyNodeObj<N>;
  }
}
 
/**
 * Local changes API for the `str` JSON CRDT node {@link StrNode}. This API
 * allows to insert and delete bytes in the UTF-16 string by referencing its
 * local character positions.
 *
 * @category Local API
 */
export class StrApi extends NodeApi<StrNode> {
  /**
   * Inserts text at a given position.
   *
   * @param index Position at which to insert text.
   * @param text Text to insert.
   * @returns Reference to itself.
   */
  public ins(index: number, text: string): void {
    const {api, node} = this;
    api.onBeforeLocalChange.emit(api.next);
    const builder = api.builder;
    builder.pad();
    const nextTime = api.builder.nextTime();
    const id = new Timestamp(builder.clock.sid, nextTime);
    const after = node.insAt(index, id, text);
    Iif (!after) throw new Error('OUT_OF_BOUNDS');
    builder.insStr(node.id, after, text);
    api.advance();
  }
 
  /**
   * Deletes a range of text at a given position.
   *
   * @param index Position at which to delete text.
   * @param length Number of UTF-16 code units to delete.
   * @returns Reference to itself.
   */
  public del(index: number, length: number): void {
    const {api, node} = this;
    api.onBeforeLocalChange.emit(api.next);
    const builder = api.builder;
    builder.pad();
    const spans = node.findInterval(index, length);
    Iif (!spans) throw new Error('OUT_OF_BOUNDS');
    node.delete(spans);
    builder.del(node.id, spans);
    api.advance();
  }
 
  /**
   * Given a character index in local coordinates, find the ID of the character
   * in the global coordinates.
   *
   * @param index Index of the character or `-1` for before the first character.
   * @returns ID of the character after which the given position is located.
   */
  public findId(index: number | -1): ITimestampStruct {
    const node = this.node;
    const length = node.length();
    const max = length - 1;
    Iif (index > max) index = max;
    if (index < 0) return node.id;
    const id = node.find(index);
    return id || node.id;
  }
 
  /**
   * Given a position in global coordinates, find the position in local
   * coordinates.
   *
   * @param id ID of the character.
   * @returns Index of the character in local coordinates. Returns -1 if the
   *          the position refers to the beginning of the string.
   */
  public findPos(id: ITimestampStruct): number | -1 {
    const node = this.node;
    const nodeId = node.id;
    if (nodeId.sid === id.sid && nodeId.time === id.time) return -1;
    const chunk = node.findById(id);
    Iif (!chunk) return -1;
    const pos = node.pos(chunk);
    return pos + (chunk.del ? 0 : id.time - chunk.id.time);
  }
 
  /**
   * Get the length of the string without materializing it to a view.
   *
   * @returns Length of the string.
   */
  public length(): number {
    return this.node.length();
  }
 
  /**
   * Returns a proxy object for this node.
   */
  public get s(): types.ProxyNodeStr {
    return {$: this};
  }
}
 
/**
 * Local changes API for the `bin` JSON CRDT node {@link BinNode}. This API
 * allows to insert and delete bytes in the binary string by referencing their
 * local index.
 *
 * @category Local API
 */
export class BinApi extends NodeApi<BinNode> {
  /**
   * Inserts octets at a given position.
   *
   * @param index Position at which to insert octets.
   * @param data Octets to insert.
   * @returns Reference to itself.
   */
  public ins(index: number, data: Uint8Array): void {
    const {api, node} = this;
    const after = !index ? node.id : node.find(index - 1);
    Iif (!after) throw new Error('OUT_OF_BOUNDS');
    api.builder.insBin(node.id, after, data);
    api.apply();
  }
 
  /**
   * Deletes a range of octets at a given position.
   *
   * @param index Position at which to delete octets.
   * @param length Number of octets to delete.
   * @returns Reference to itself.
   */
  public del(index: number, length: number): void {
    const {api, node} = this;
    const spans = node.findInterval(index, length);
    Iif (!spans) throw new Error('OUT_OF_BOUNDS');
    api.builder.del(node.id, spans);
    api.apply();
  }
 
  /**
   * Get the length of the binary blob without materializing it to a view.
   *
   * @returns Length of the binary blob.
   */
  public length(): number {
    return this.node.length();
  }
 
  /**
   * Returns a proxy object for this node.
   */
  public get s(): types.ProxyNodeBin {
    return {$: this};
  }
}
 
type UnArrNode<N> = N extends ArrNode<infer T> ? T : never;
 
/**
 * Local changes API for the `arr` JSON CRDT node {@link ArrNode}. This API
 * allows to insert and delete elements in the array by referencing their local
 * index.
 *
 * @category Local API
 */
export class ArrApi<N extends ArrNode<any> = ArrNode<any>> extends NodeApi<N> {
  /**
   * Get API instance of a child node.
   *
   * @param index Index of the element to get.
   * @returns Child node API for the element at the given index.
   */
  public get(index: number): JsonNodeApi<UnArrNode<N>> {
    return this.in(index) as any;
  }
 
  /**
   * Inserts elements at a given position.
   *
   * @param index Position at which to insert elements.
   * @param values Values or schema of the elements to insert.
   */
  public ins(index: number, values: Array<JsonNodeView<N>[number]>): void {
    const {api, node} = this;
    const {builder} = api;
    const after = !index ? node.id : node.find(index - 1);
    Iif (!after) throw new Error('OUT_OF_BOUNDS');
    const valueIds: ITimestampStruct[] = [];
    for (let i = 0; i < values.length; i++) valueIds.push(builder.json(values[i]));
    builder.insArr(node.id, after, valueIds);
    api.apply();
  }
 
  /**
   * Inserts elements at the end of the array.
   *
   * @param values Values or schema of the elements to insert at the end of the array.
   */
  public push(...values: JsonNodeView<N>[number][]): void {
    const length = this.length();
    this.ins(length, values);
  }
 
  /**
   * Updates (overwrites) an element at a given position.
   *
   * @param index Position at which to update the element.
   * @param value Value or schema of the element to replace with.
   */
  public upd(index: number, value: JsonNodeView<N>[number]): void {
    const {api, node} = this;
    const ref = node.getId(index);
    Iif (!ref) throw new Error('OUT_OF_BOUNDS');
    const {builder} = api;
    builder.updArr(node.id, ref, builder.constOrJson(value));
    api.apply();
  }
 
  /**
   * Deletes a range of elements at a given position.
   *
   * @param index Position at which to delete elements.
   * @param length Number of elements to delete.
   * @returns Reference to itself.
   */
  public del(index: number, length: number): void {
    const {api, node} = this;
    const spans = node.findInterval(index, length);
    Iif (!spans) throw new Error('OUT_OF_BOUNDS');
    api.builder.del(node.id, spans);
    api.apply();
  }
 
  /**
   * Get the length of the array without materializing it to a view.
   *
   * @returns Length of the array.
   */
  public length(): number {
    return this.node.length();
  }
 
  /**
   * Returns a proxy object that allows to access array elements by index.
   *
   * @returns Proxy object that allows to access array elements by index.
   */
  public get s(): types.ProxyNodeArr<N> {
    const proxy = new Proxy(
      {},
      {
        get: (target, prop, receiver) => {
          if (prop === '$') return this;
          const index = Number(prop);
          Iif (Number.isNaN(index)) throw new Error('INVALID_INDEX');
          const child = this.node.getNode(index);
          Iif (!child) throw new Error('OUT_OF_BOUNDS');
          return (this.api.wrap(child) as any).s;
        },
      },
    );
    return proxy as types.ProxyNodeArr<N>;
  }
}
 
/**
 * Local changes API for a JSON CRDT model. This class is the main entry point
 * for executing local user actions on a JSON CRDT document.
 *
 * @category Local API
 */
export class ModelApi<N extends JsonNode = JsonNode> extends ValApi<RootNode<N>> implements SyncStore<JsonNodeView<N>> {
  /**
   * Patch builder for the local changes.
   */
  public builder: PatchBuilder;
 
  /**
   * Index of the next operation in builder's patch to be committed locally.
   *
   * @ignore
   */
  public next: number = 0;
 
  /** Emitted before the model is reset, using the `.reset()` method. */
  public readonly onBeforeReset = new FanOut<void>();
  /** Emitted after the model is reset, using the `.reset()` method. */
  public readonly onReset = new FanOut<void>();
  /** Emitted before a patch is applied using `model.applyPatch()`. */
  public readonly onBeforePatch = new FanOut<Patch>();
  /** Emitted after a patch is applied using `model.applyPatch()`. */
  public readonly onPatch = new FanOut<Patch>();
  /** Emitted before local changes through `model.api` are applied. */
  public readonly onBeforeLocalChange = new FanOut<number>();
  /** Emitted after local changes through `model.api` are applied. */
  public readonly onLocalChange = new FanOut<number>();
  /**
   * Emitted after local changes through `model.api` are applied. Same as
   * `.onLocalChange`, but this event buffered withing a microtask.
   */
  public readonly onLocalChanges = new MicrotaskBufferFanOut<number>(this.onLocalChange);
  /** Emitted before a transaction is started. */
  public readonly onBeforeTransaction = new FanOut<void>();
  /** Emitted after transaction completes. */
  public readonly onTransaction = new FanOut<void>();
  /** Emitted when the model changes. Combines `onReset`, `onPatch` and `onLocalChange`. */
  public readonly onChange = new MergeFanOut<number | Patch | undefined>([
    this.onReset,
    this.onPatch,
    this.onLocalChange,
  ]);
  /** Emitted when the model changes. Same as `.onChange`, but this event is emitted once per microtask. */
  public readonly onChanges = new MicrotaskBufferFanOut<number | Patch | undefined>(this.onChange);
  /** Emitted when the `model.api` builder change buffer is flushed. */
  public readonly onFlush = new FanOut<Patch>();
 
  /**
   * @param model Model instance on which the API operates.
   */
  constructor(public readonly model: Model<N>) {
    super(model.root, void 0 as any);
    (this as any).api = this;
    this.builder = new PatchBuilder(model.clock);
    model.onbeforereset = () => this.onBeforeReset.emit();
    model.onreset = () => this.onReset.emit();
    model.onbeforepatch = (patch) => this.onBeforePatch.emit(patch);
    model.onpatch = (patch) => this.onPatch.emit(patch);
  }
 
  /**
   * Returns a local change API for the given node. If an instance already
   * exists, returns the existing instance.
   */
  public wrap(node: ValNode): ValApi;
  public wrap(node: StrNode<any>): StrApi;
  public wrap(node: BinNode): BinApi;
  public wrap(node: ArrNode): ArrApi;
  public wrap(node: ObjNode): ObjApi;
  public wrap(node: ConNode): ConApi;
  public wrap(node: VecNode): VecApi;
  public wrap(node: JsonNode): NodeApi;
  public wrap(node: ExtNode<any, any>): NodeApi;
  public wrap(node: JsonNode) {
    if (node instanceof ValNode) return node.api || (node.api = new ValApi(node, this));
    else if (node instanceof StrNode) return node.api || (node.api = new StrApi(node, this));
    else if (node instanceof BinNode) return node.api || (node.api = new BinApi(node, this));
    else if (node instanceof ArrNode) return node.api || (node.api = new ArrApi(node, this));
    else if (node instanceof ObjNode) return node.api || (node.api = new ObjApi(node, this));
    else if (node instanceof ConNode) return node.api || (node.api = new ConApi(node, this));
    else if (node instanceof VecNode) return node.api || (node.api = new VecApi(node, this));
    else if (node instanceof ExtNode) {
      if (node.api) return node.api;
      const extension = this.model.ext.get(node.extId)!;
      return (node.api = new extension.Api(node, this));
    } else throw new Error('UNKNOWN_NODE');
  }
 
  /**
   * Given a JSON/CBOR value, constructs CRDT nodes recursively out of it and
   * sets the root node of the model to the constructed nodes.
   *
   * @param json JSON/CBOR value to set as the view of the model.
   * @returns Reference to itself.
   *
   * @deprecated Use `.set()` instead.
   */
  public root(json: unknown): this {
    return this.set(json as any);
  }
  public set(json: unknown): this {
    super.set(json as any);
    return this;
  }
 
  /**
   * Apply locally any operations from the `.builder`, which haven't been
   * applied yet.
   */
  public apply() {
    const ops = this.builder.patch.ops;
    const length = ops.length;
    const model = this.model;
    const from = this.next;
    this.onBeforeLocalChange.emit(from);
    for (let i = this.next; i < length; i++) model.applyOperation(ops[i]);
    this.next = length;
    model.tick++;
    this.onLocalChange.emit(from);
  }
 
  /**
   * Advance patch pointer to the end without applying the operations. With the
   * idea that they have already been applied locally.
   *
   * You need to manually call `this.onBeforeLocalChange.emit(this.next)` before
   * calling this method.
   *
   * @ignore
   */
  public advance() {
    const from = this.next;
    this.next = this.builder.patch.ops.length;
    this.model.tick++;
    this.onLocalChange.emit(from);
  }
 
  private inTx = false;
  public transaction(callback: () => void) {
    if (this.inTx) callback();
    else {
      this.inTx = true;
      try {
        this.onBeforeTransaction.emit();
        callback();
        this.onTransaction.emit();
      } finally {
        this.inTx = false;
      }
    }
  }
 
  /**
   * Flushes the builder and returns a patch.
   *
   * @returns A JSON CRDT patch.
   * @todo Make this return undefined if there are no operations in the builder.
   */
  public flush(): Patch {
    const patch = this.builder.flush();
    this.next = 0;
    if (patch.ops.length) this.onFlush.emit(patch);
    return patch;
  }
 
  public stopAutoFlush?: () => void = undefined;
 
  /**
   * Begins to automatically flush buffered operations into patches, grouping
   * operations by microtasks or by transactions. To capture the patch, listen
   * to the `.onFlush` event.
   *
   * @returns Callback to stop auto flushing.
   */
  public autoFlush(drainNow = false): () => void {
    const drain = () => this.builder.patch.ops.length && this.flush();
    const onLocalChangesUnsubscribe = this.onLocalChanges.listen(drain);
    const onBeforeTransactionUnsubscribe = this.onBeforeTransaction.listen(drain);
    const onTransactionUnsubscribe = this.onTransaction.listen(drain);
    Iif (drainNow) drain();
    return (this.stopAutoFlush = () => {
      this.stopAutoFlush = undefined;
      onLocalChangesUnsubscribe();
      onBeforeTransactionUnsubscribe();
      onTransactionUnsubscribe();
    });
  }
 
  // ---------------------------------------------------------------- SyncStore
 
  public readonly subscribe = (callback: () => void) => this.onChanges.listen(() => callback());
  public readonly getSnapshot = () => this.view() as JsonNodeView<N>;
}