All files / json-crdt/json-patch JsonPatch.ts

91.66% Statements 132/144
76.66% Branches 46/60
100% Functions 18/18
97.58% Lines 121/124

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 2055x 5x 5x 5x           5x   87x 87x       97x 97x 109x   85x       109x   29x 29x   20x 15x   9x 7x   5x 4x   4x 4x   14x 10x   19x 19x   9x 9x       97x 97x       114x       175x       44x 44x 44x   35x 35x 35x 35x 16x 19x 19x 19x 3x 3x 3x   16x 16x 16x   7x 7x 7x               33x 33x 33x   31x 31x 29x 29x 19x 19x 19x 15x 14x 10x 10x 10x 10x 10x 10x 10x           9x 7x       5x 5x 5x 4x 4x 4x       4x 4x 4x       14x 14x 14x       19x 19x 19x 19x 19x 19x       9x 9x 9x 9x 7x 7x 7x 7x       48x       70x 70x   63x 63x 63x 60x 60x 56x 4x 3x 3x 3x 3x 3x     3x     1x       22x 22x 22x       11x 11x      
import {deepEqual} from '@jsonjoy.com/util/lib/json-equal/deepEqual';
import {ObjNode, ArrNode, type JsonNode, ConNode} from '../nodes';
import {toPath, isChild} from '@jsonjoy.com/json-pointer/lib/util';
import {interval} from '../../json-crdt-patch/clock';
import type {PatchBuilder} from '../../json-crdt-patch/PatchBuilder';
import type {Path} from '@jsonjoy.com/json-pointer/lib/types';
import type {Model} from '../model';
import type {Operation} from '../../json-patch';
 
export class JsonPatch<N extends JsonNode = JsonNode<any>> {
  constructor(
    protected readonly model: Model<N>,
    protected readonly pfx: Path = [],
  ) {}
 
  public apply(ops: Operation[]): this {
    const length = ops.length;
    this.model.api.transaction(() => {
      for (let i = 0; i < length; i++) this.applyOp(ops[i]);
    });
    return this;
  }
 
  public applyOp(op: Operation): this {
    switch (op.op) {
      case 'add':
        this.add(op.path, op.value);
        break;
      case 'remove':
        this.remove(op.path);
        break;
      case 'replace':
        this.replace(op.path, op.value);
        break;
      case 'move':
        this.move(op.path, op.from);
        break;
      case 'copy':
        this.copy(op.path, op.from);
        break;
      case 'test':
        this.test(op.path, op.value);
        break;
      case 'str_ins':
        this.strIns(op.path, op.pos, op.str);
        break;
      case 'str_del':
        this.strDel(op.path, op.pos, op.len ?? 0, op.str);
        break;
      default:
        throw new Error('UNKNOWN_OP');
    }
    this.model.api.apply();
    return this;
  }
 
  protected builder(): PatchBuilder {
    return this.model.api.builder;
  }
 
  public toPath(path: string | Path): Path {
    return this.pfx.concat(toPath(path));
  }
 
  public add(path: string | Path, value: unknown): void {
    const builder = this.builder();
    const steps = this.toPath(path);
    if (!steps.length) this.setRoot(value);
    else {
      const objSteps = steps.slice(0, steps.length - 1);
      const node = this.model.api.find(objSteps);
      const key = steps[steps.length - 1];
      if (node instanceof ObjNode) {
        builder.insObj(node.id, [[String(key), builder.json(value)]]); // TODO: see if "con" nodes can be used here in some cases.
      } else if (node instanceof ArrNode) {
        const builderValue = builder.json(value);
        if (key === '-') {
          const length = node.length();
          const after = node.find(length - 1) || node.id;
          builder.insArr(node.id, after, [builderValue]);
        } else {
          const index = ~~key;
          Iif ('' + index !== key) throw new Error('INVALID_INDEX');
          if (!index) builder.insArr(node.id, node.id, [builderValue]);
          else {
            const after = node.find(index - 1);
            Iif (!after) throw new Error('NOT_FOUND');
            builder.insArr(node.id, after, [builderValue]);
          }
        }
      } else Ethrow new Error('NOT_FOUND');
    }
  }
 
  public remove(path: string | Path): void {
    const builder = this.builder();
    const steps = this.toPath(path);
    if (!steps.length) this.setRoot(null);
    else {
      const objSteps = steps.slice(0, steps.length - 1);
      const node = this.model.api.find(objSteps);
      const key = steps[steps.length - 1];
      if (node instanceof ObjNode) {
        const stringKey = String(key);
        const valueNode = node.get(stringKey);
        if (valueNode === undefined) throw new Error('NOT_FOUND');
        if (valueNode instanceof ConNode && valueNode.val === undefined) throw new Error('NOT_FOUND');
        builder.insObj(node.id, [[stringKey, builder.const(undefined)]]);
      } else if (node instanceof ArrNode) {
        const key = steps[steps.length - 1];
        const index = ~~key;
        Iif (typeof key === 'string' && '' + index !== key) throw new Error('INVALID_INDEX');
        const id = node.find(index);
        Iif (!id) throw new Error('NOT_FOUND');
        builder.del(node.id, [interval(id, 0, 1)]);
      } else Ethrow new Error('NOT_FOUND');
    }
  }
 
  public replace(path: string | Path, value: unknown): void {
    this.remove(path);
    this.add(path, value);
  }
 
  public move(path: string | Path, from: string | Path): void {
    path = toPath(path);
    from = toPath(from);
    if (isChild(from, path)) throw new Error('INVALID_CHILD');
    const json = this.json(this.toPath(from));
    this.remove(from);
    this.add(path, json);
  }
 
  public copy(path: string | Path, from: string | Path): void {
    path = toPath(path);
    const json = this.json(this.toPath(from));
    this.add(path, json);
  }
 
  public test(path: string | Path, value: unknown): void {
    path = this.toPath(path);
    const json = this.json(path);
    if (!deepEqual(json, value)) throw new Error('TEST');
  }
 
  public strIns(path: string | Path, pos: number, str: string): void {
    path = this.toPath(path);
    const {node} = this.model.api.str(path);
    const length = node.length();
    const after = pos ? node.find(length < pos ? length - 1 : pos - 1) : node.id;
    Iif (!after) throw new Error('OUT_OF_BOUNDS');
    this.builder().insStr(node.id, after, str);
  }
 
  public strDel(path: string | Path, pos: number, len: number, str: string = ''): void {
    path = this.toPath(path);
    const {node} = this.model.api.str(path);
    const length = node.length();
    if (length <= pos) return;
    const deletionLength = Math.min(len ?? str!.length, length - pos);
    const range = node.findInterval(pos, deletionLength);
    Iif (!range) throw new Error('OUT_OF_BOUNDS');
    this.builder().del(node.id, range);
  }
 
  public get(path: string | Path): unknown {
    return this._get(this.toPath(path));
  }
 
  private _get(steps: Path): unknown {
    const model = this.model;
    if (!steps.length) return model.view();
    else {
      try {
        const objSteps = steps.slice(0, steps.length - 1);
        const node = model.api.find(objSteps);
        const key = steps[steps.length - 1];
        if (node instanceof ObjNode) {
          return node.get(String(key))?.view();
        } else if (node instanceof ArrNode) {
          const index = ~~key;
          Iif ('' + index !== key) throw new Error('INVALID_INDEX');
          const arrNode = node.getNode(index);
          Iif (!arrNode) throw new Error('NOT_FOUND');
          return arrNode.view();
        }
      } catch {
        return;
      }
    }
    return undefined;
  }
 
  private json(steps: Path): unknown {
    const json = this._get(steps);
    Iif (json === undefined) throw new Error('NOT_FOUND');
    return json;
  }
 
  private setRoot(json: unknown) {
    const builder = this.builder();
    builder.root(builder.json(json));
  }
}