all files / model/data/ ObjectOperation.js

56% Statements 154/275
41.91% Branches 57/136
38.24% Functions 13/34
57.46% Lines 154/268
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                            7274×     7274×     7274× 7274×     7274× 7274×     7274× 5501×     5501×   1773× 1730× 1730× 1730× 383× 1347× 1333× 14× 14×               43× 43× 43×             46× 46× 46×     46×   46× 28× 28×   18×     18× 18× 18×   14× 14× 14×                                         18×                                                                                     1301×     1301× 1301× 854×   447× 52×   395× 383× 383× 163× 220× 213×       383×     12× 12×   1301×               1349×     1349×       1349× 934×   415× 403× 169× 234× 227×       403×     12× 12×   1349×                                                                                                                                                                                                                                                                                                                                         4442× 4442×     4442×   4442×     125× 125×     125×   125×     1329×             31×               46× 46× 18×     14× 14×               46× 46×          
import isEqual from '../../util/isEqual'
import isNil from '../../util/isNil'
import isString from '../../util/isString'
import cloneDeep from '../../util/cloneDeep'
import PathObject from '../../util/PathObject'
import TextOperation from './TextOperation'
import ArrayOperation from './ArrayOperation'
import CoordinateOperation from './CoordinateOperation'
import Conflict from './Conflict'
 
const NOP = "NOP"
const CREATE = "create"
const DELETE = 'delete'
const UPDATE = 'update'
const SET = 'set'
 
class ObjectOperation {
 
  constructor(data) {
    Iif (!data) {
      throw new Error('Data of ObjectOperation is missing.')
    }
    Iif (!data.type) {
      throw new Error('Invalid data: type is mandatory.')
    }
    this.type = data.type
    Iif (data.type === NOP) {
      return
    }
    this.path = data.path
    Iif (!data.path) {
      throw new Error('Invalid data: path is mandatory.')
    }
    if (this.type === CREATE || this.type === DELETE) {
      Iif (!data.val) {
        throw new Error('Invalid data: value is missing.')
      }
      this.val = data.val
    }
    else if (this.type === UPDATE) {
      Eif (data.diff) {
        this.diff = data.diff
        if (data.diff._isTextOperation) {
          this.propertyType = 'string'
        } else if (data.diff._isArrayOperation) {
          this.propertyType = 'array'
        } else Eif (data.diff._isCoordinateOperation) {
          this.propertyType = 'coordinate'
        } else {
          throw new Error('Invalid data: diff must be a TextOperation or an ArrayOperation.')
        }
      } else {
        throw new Error("Invalid data: diff is mandatory for update operation.")
      }
    }
    else Eif (this.type === SET) {
      this.val = data.val
      this.original = data.original
    } else {
      throw new Error('Invalid type: '+ data.type)
    }
  }
 
  apply(obj) {
    Iif (this.type === NOP) return obj
    var adapter
    Iif (obj._isPathObject) {
      adapter = obj
    } else {
      adapter = new PathObject(obj)
    }
    if (this.type === CREATE) {
      adapter.set(this.path, cloneDeep(this.val))
      return obj
    }
    Iif (this.type === DELETE) {
      adapter.delete(this.path, "strict")
    }
    else Eif (this.type === UPDATE) {
      var diff = this.diff
      switch (this.propertyType) {
        case 'array': {
          let arr = adapter.get(this.path)
          diff.apply(arr)
          break
        }
        case 'string': {
          let str = adapter.get(this.path)
          Iif (isNil(str)) str = ''
          str = diff.apply(str)
          adapter.set(this.path, str)
          break
        }
        case 'coordinate': {
          let coor = adapter.get(this.path)
          if (!coor) throw new Error('No coordinate with path '+this.path)
          diff.apply(coor)
          break
        }
        default:
          throw new Error('Invalid state.')
      }
    }
    else if (this.type === SET) {
      // clone here as the operations value must not be changed
      adapter.set(this.path, cloneDeep(this.val))
    }
    else {
      throw new Error('Invalid type.')
    }
    return obj
  }
 
  clone() {
    var data = {
      type: this.type,
      path: this.path,
    }
    if (this.val) {
      data.val = cloneDeep(this.val)
    }
    if (this.diff) {
      data.diff = this.diff.clone()
    }
    return new ObjectOperation(data)
  }
 
  isNOP() {
    if (this.type === NOP) return true
    else if (this.type === UPDATE) return this.diff.isNOP()
  }
 
  isCreate() {
    return this.type === CREATE
  }
 
  isDelete() {
    return this.type === DELETE
  }
 
  isUpdate(propertyType) {
    if (propertyType) {
      return (this.type === UPDATE && this.propertyType === propertyType)
    } else {
      return this.type === UPDATE
    }
  }
 
  isSet() {
    return this.type === SET
  }
 
  invert() {
    Iif (this.type === NOP) {
      return new ObjectOperation({ type: NOP })
    }
    var result = new ObjectOperation(this)
    if (this.type === CREATE) {
      result.type = DELETE
    }
    else if (this.type === DELETE) {
      result.type = CREATE
    }
    else if (this.type === UPDATE) {
      var invertedDiff
      if (this.diff._isTextOperation) {
        invertedDiff = TextOperation.fromJSON(this.diff.toJSON()).invert()
      } else if (this.diff._isArrayOperation) {
        invertedDiff = ArrayOperation.fromJSON(this.diff.toJSON()).invert()
      } else Eif (this.diff._isCoordinateOperation) {
        invertedDiff = CoordinateOperation.fromJSON(this.diff.toJSON()).invert()
      } else {
        throw new Error('Illegal type')
      }
      result.diff = invertedDiff
    }
    else /* if (this.type === SET) */ {
      result.val = this.original
      result.original = this.val
    }
    return result
  }
 
  hasConflict(other) {
    return ObjectOperation.hasConflict(this, other)
  }
 
  toJSON() {
    Iif (this.type === NOP) {
      return { type: NOP }
    }
    var data = {
      type: this.type,
      path: this.path,
    }
    if (this.type === CREATE || this.type === DELETE) {
      data.val = this.val
    }
    else if (this.type === UPDATE) {
      if (this.diff._isTextOperation) {
        data.propertyType = "string"
      } else if (this.diff._isArrayOperation) {
        data.propertyType = "array"
      } else Eif (this.diff._isCoordinateOperation) {
        data.propertyType = "coordinate"
      } else {
        throw new Error('Invalid property type.')
      }
      data.diff = this.diff.toJSON()
    }
    else /* if (this.type === SET) */ {
      data.val = this.val
      data.original = this.original
    }
    return data
  }
 
  getType() {
    return this.type
  }
 
  getPath() {
    return this.path
  }
 
  getValue() {
    return this.val
  }
 
  getOldValue() {
    return this.original
  }
 
  getValueOp() {
    return this.diff
  }
 
  toString() {
    switch (this.type) {
      case CREATE:
        return ["(+,", JSON.stringify(this.path), JSON.stringify(this.val), ")"].join('')
      case DELETE:
        return ["(-,", JSON.stringify(this.path), JSON.stringify(this.val), ")"].join('')
      case UPDATE:
        return ["(>>,", JSON.stringify(this.path), this.propertyType, this.diff.toString(), ")"].join('')
      case SET:
        return ["(=,", JSON.stringify(this.path), this.val, this.original, ")"].join('')
      case NOP:
        return "NOP"
      default:
        throw new Error('Invalid type')
    }
  }
}
 
ObjectOperation.prototype._isOperation = true
ObjectOperation.prototype._isObjectOperation = true
 
/* Low level implementation */
 
function hasConflict(a, b) {
  if (a.type === NOP || b.type === NOP) return false
  return isEqual(a.path, b.path)
}
 
function transform_delete_delete(a, b) {
  // both operations have the same effect.
  // the transformed operations are turned into NOPs
  a.type = NOP
  b.type = NOP
}
 
function transform_create_create() {
  throw new Error("Can not transform two concurring creates of the same property")
}
 
function transform_delete_create() {
  throw new Error('Illegal state: can not create and delete a value at the same time.')
}
 
function transform_delete_update(a, b, flipped) {
  if (a.type !== DELETE) {
    return transform_delete_update(b, a, true)
  }
  var op
  switch (b.propertyType) {
    case 'string':
      op = TextOperation.fromJSON(b.diff)
      break
    case 'array':
      op = ArrayOperation.fromJSON(b.diff)
      break
    case 'coordinate':
      op = CoordinateOperation.fromJSON(b.diff)
      break
    default:
      throw new Error('Illegal type')
  }
  // (DELETE, UPDATE) is transformed into (DELETE, CREATE)
  if (!flipped) {
    a.type = NOP
    b.type = CREATE
    b.val = op.apply(a.val)
  }
  // (UPDATE, DELETE): the delete is updated to delete the updated value
  else {
    a.val = op.apply(a.val)
    b.type = NOP
  }
}
 
function transform_create_update() {
  // it is not possible to reasonably transform this.
  throw new Error("Can not transform a concurring create and update of the same property")
}
 
function transform_update_update(a, b) {
  // Note: this is a conflict the user should know about
  var op_a, op_b, t
  switch(b.propertyType) {
    case 'string':
      op_a = TextOperation.fromJSON(a.diff)
      op_b = TextOperation.fromJSON(b.diff)
      t = TextOperation.transform(op_a, op_b, {inplace: true})
      break
    case 'array':
      op_a = ArrayOperation.fromJSON(a.diff)
      op_b = ArrayOperation.fromJSON(b.diff)
      t = ArrayOperation.transform(op_a, op_b, {inplace: true})
      break
    case 'coordinate':
      op_a = CoordinateOperation.fromJSON(a.diff)
      op_b = CoordinateOperation.fromJSON(b.diff)
      t = CoordinateOperation.transform(op_a, op_b, {inplace: true})
      break
    default:
      throw new Error('Illegal type')
  }
  a.diff = t[0]
  b.diff = t[1]
}
 
function transform_create_set() {
  throw new Error('Illegal state: can not create and set a value at the same time.')
}
 
function transform_delete_set(a, b, flipped) {
  if (a.type !== DELETE) return transform_delete_set(b, a, true)
  if (!flipped) {
    a.type = NOP
    b.type = CREATE
    b.original = undefined
  } else {
    a.val = b.val
    b.type = NOP
  }
}
 
function transform_update_set() {
  throw new Error("Unresolvable conflict: update + set.")
}
 
function transform_set_set(a, b) {
  a.type = NOP
  b.original = a.val
}
 
const _NOP = 0
const _CREATE = 1
const _DELETE = 2
const _UPDATE = 4
const _SET = 8
 
const CODE = (() => {
  const c = {}
  c[NOP] =_NOP
  c[CREATE] = _CREATE
  c[DELETE] = _DELETE
  c[UPDATE] = _UPDATE
  c[SET] = _SET
  return c
})()
 
const __transform__ = (() => {
  /* eslint-disable no-multi-spaces */
  const t = {}
  t[_DELETE | _DELETE] = transform_delete_delete
  t[_DELETE | _CREATE] = transform_delete_create
  t[_DELETE | _UPDATE] = transform_delete_update
  t[_CREATE | _CREATE] = transform_create_create
  t[_CREATE | _UPDATE] = transform_create_update
  t[_UPDATE | _UPDATE] = transform_update_update
  t[_CREATE | _SET   ] = transform_create_set
  t[_DELETE | _SET   ] = transform_delete_set
  t[_UPDATE | _SET   ] = transform_update_set
  t[_SET    | _SET   ] = transform_set_set
  /* eslint-enable no-multi-spaces */
  return t
})()
 
function transform(a, b, options) {
  options = options || {}
  if (options['no-conflict'] && hasConflict(a, b)) {
    throw new Conflict(a, b)
  }
  if (!options.inplace) {
    a = a.clone()
    b = b.clone()
  }
  if (a.isNOP() || b.isNOP()) {
    return [a, b]
  }
  var sameProp = isEqual(a.path, b.path)
  // without conflict: a' = a, b' = b
  if (sameProp) {
    __transform__[CODE[a.type] | CODE[b.type]](a,b)
  }
  return [a, b]
}
 
ObjectOperation.transform = transform
ObjectOperation.hasConflict = hasConflict
 
/* Factories */
 
ObjectOperation.Create = function(idOrPath, val) {
  var path
  Iif (isString(idOrPath)) {
    path = [idOrPath]
  } else {
    path = idOrPath
  }
  return new ObjectOperation({type: CREATE, path: path, val: val})
}
 
ObjectOperation.Delete = function(idOrPath, val) {
  var path
  Iif (isString(idOrPath)) {
    path = [idOrPath]
  } else {
    path = idOrPath
  }
  return new ObjectOperation({type: DELETE, path: path, val: val})
}
 
ObjectOperation.Update = function(path, op) {
  return new ObjectOperation({
    type: UPDATE,
    path: path,
    diff: op
  })
}
 
ObjectOperation.Set = function(path, oldVal, newVal) {
  return new ObjectOperation({
    type: SET,
    path: path,
    val: cloneDeep(newVal),
    original: cloneDeep(oldVal)
  })
}
 
ObjectOperation.fromJSON = function(data) {
  data = cloneDeep(data)
  if (data.type === "update") {
    switch (data.propertyType) {
      case "string":
        data.diff = TextOperation.fromJSON(data.diff)
        break
      case "array":
        data.diff = ArrayOperation.fromJSON(data.diff)
        break
      case "coordinate":
        data.diff = CoordinateOperation.fromJSON(data.diff)
        break
      default:
        throw new Error("Unsupported update diff:" + JSON.stringify(data.diff))
    }
  }
  var op = new ObjectOperation(data)
  return op
}
 
ObjectOperation.NOP = NOP
ObjectOperation.CREATE = CREATE
ObjectOperation.DELETE = DELETE
ObjectOperation.UPDATE = UPDATE
ObjectOperation.SET = SET
 
export default ObjectOperation