All files / src/UUID UUID.ts

100% Statements 81/81
100% Branches 18/18
100% Functions 15/15
100% Lines 81/81
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 2791x     1x                       1x     1x     1x     1x     1x     1x     1x     1x     1x     1x                                                 1x   22x 22x   22x 22x 1x     21x 1x     20x             20x 20x 2x 18x     2x     16x       20x 20x 20x   20x 1x                       4x           7x         2x         2x         2x           6x         2x         3x                     2x           2x 2x           2x         2x 2x 1x     1x 1x 1x   1x 1x 1x 1x 1x 8x     1x   1x   1x   1x           1x   1x 1x 1x 4x     1x   1x 1x 1x 6x     1x   1x     1x         1x         1x         1x       1x       1x 6x         1x                           1x  
import {
  isNode,
} from '../isNode';
import {
  isUUIDVersion,
} from '../TypeGuards/isUUIDVersion';
import {
  IUUID,
} from './IUUID';
import {
  IUUIDComponentValues,
} from './IUUIDComponentValues';
import {
  IUUIDOptions,
} from './UUIDOptions/IUUIDOptions';
import {
  makeVersionFourOrNilUUIDValues,
} from './makeVersionFourOrNilUUIDValues';
import {
  makeVersionOneUUIDValues,
} from './makeVersionOneUUIDValues';
import {
  makeVersionThreeOrFiveUUIDValues,
} from './makeVersionThreeOrFiveUUIDValues';
import {
  mergeUUIDOptions,
} from './UUIDOptions/mergeUUIDOptions';
import {
  strings,
} from '../strings';
import {
  uintArrayAsHex,
} from '../uintArrayAsHex';
import {
  uintArrayAsBigNumber,
} from '../uintArrayAsBigNumber';
import {
  UUIDOptions,
} from './UUIDOptions/UUIDOptions';
import {
  UUIDVersions,
} from '../Enums/UUIDVersions';
import {
  writeNewResults,
} from '../writeNewResults';
 
/* The formal Augmented Backus-Naur Form grammar for UUIDs is as follows,
 * courtesy RFC-4112:
 * The formal definition of the UUID string representation is
 * provided by the following ABNF:
 *
 *    UUID                        = time-low "-" time-mid "-"
 *                                  time-high-and-version "-"
 *                                  clock-seq-high-and-reserved
 *                                  clock-seq-low "-" node
 *    time-low                    = 4hexOctet/8hexDigit
 *    time-mid                    = 2hexOctet/4hexDigit
 *    time-high-and-version       = 2hexOctet/4hexDigit
 *    clock-seq-high-and-reserved = hexOctet/2hexDigit
 *    clock-seq-low               = hexOctet/2hexDigit
 *    node                        = 6hexOctet/12hexDigit
 *    hexOctet                    = hexDigit hexDigit
 *    hexDigit =
 *          "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9" /
 *          "a" / "b" / "c" / "d" / "e" / "f" /
 *          "A" / "B" / "C" / "D" / "E" / "F"
 */
export class UUID implements IUUID {
  constructor(argOptions?: Partial<IUUIDOptions>) {
    const base = new UUIDOptions();
    const options = argOptions ? mergeUUIDOptions(base, argOptions) : base;
 
    let version = options.version.toString();
    if (!isUUIDVersion(version)) {
      throw new Error(strings.UUID_VERSION_INVALID);
    }
 
    if (!isNode() && version === UUIDVersions.One) {
      throw new Error(strings.VERSION_1_IN_BROWSER);
    }
 
    this.__version = version;
 
    const {
      clockSequence,
      nodeIdentifier,
      shouldWrite,
      timestamp,
    }: IUUIDComponentValues & { shouldWrite?: boolean, } = (() => {
      if (version === UUIDVersions.One) {
        return makeVersionOneUUIDValues(options);
      } else if (version === UUIDVersions.Three ||
                 version === UUIDVersions.Five)
      {
        return makeVersionThreeOrFiveUUIDValues(options); 
      } else {
        /* Version four or nil. */
        return makeVersionFourOrNilUUIDValues(options);
      }
    })();
 
    this.__clockSequence = clockSequence;
    this.__nodeIdentifier = nodeIdentifier;
    this.__timestamp = timestamp;
 
    if (shouldWrite) {
      writeNewResults(this);
    }
  }
 
  /* istanbul ignore next */
  get id() {
    return this.toString();
  }
 
  /* Parsed into 4 bits. */
  private __version: UUIDVersions;
  get version(): UUIDVersions {
    return this.__version;
  }
 
  /* 60 bits */
  private __timestamp: Uint8Array;
  get timestamp(): Uint8Array {
    return this.__timestamp;
  }
 
  /* 4 bytes */
  get timeLow(): Uint8Array {
    return this.timestamp.slice(4, 8);
  }
 
  /* 2 bytes */
  get timeMid(): Uint8Array {
    return this.timestamp.slice(2, 4);
  }
 
  /* 12 bits */
  get timeHigh(): Uint8Array {
    return this.timestamp.slice(0, 2);
  }
 
  /* 14 bits */
  private __clockSequence: Uint8Array;
  get clockSequence(): Uint8Array {
    return this.__clockSequence;
  }
 
  /* 1 byte */
  get clockSequenceLow(): Uint8Array {
    return this.clockSequence.slice(1);
  }
 
  /* 1 byte */
  get clockSequenceHigh(): Uint8Array {
    return this.clockSequence.slice(0, 1);
  }
 
  /* 4 bits. */
  /* istanbul ignore next */
  get reserved(): Uint8Array {
    return new Uint8Array([ 2, ]);
  }
 
  /* 1 byte. */
  get clockSequenceHighAndReserved(): Uint8Array {
    const clockHigh = uintArrayAsBigNumber(this.clockSequenceHigh).toString(2);
    /* istanbul ignore next */
    const reserved = this.version === UUIDVersions.Nil ?
      '0' :
      uintArrayAsBigNumber(this.reserved).toString(2);
 
    const byte = clockHigh.padStart(6, '0') + reserved.padStart(2, '0');
    return new Uint8Array([ parseInt(byte, 2), ]);
  }
 
  /* 6 bytes */
  private __nodeIdentifier: Uint8Array;
  get nodeIdentifier(): Uint8Array {
    return this.__nodeIdentifier;
  }
 
  /* text: e.g. '103314af-205e-0080-002b-7cd2a900a098' */
  static parse(text: string): IUUID {
    const split = text.split('-');
    if (split.length !== 5) {
      throw new Error(strings.UUID_STRING_INVALID);
    }
 
    const timeLow = split[0];
    const timeMid = split[1];
    const timeHighAndVersion = split[2];
 
    const timeHigh = timeHighAndVersion.slice(0, 3);
    const version = timeHighAndVersion[0];
    const timestampHex = timeHigh + timeMid + timeLow;
    const timestampArr = [];
    for (let ii = 0; ii < 16; ii += 2) {
      timestampArr.push(parseInt(timestampHex.slice(ii, ii + 2), 16));
    }
 
    const timestamp = new Uint8Array(timestampArr);
 
    const clockSequenceHighAndReservedAndLow = split[3];
    const clockSequenceHighAndReservedHex =
      clockSequenceHighAndReservedAndLow.slice(0, 2);
    const clockSequenceHighHex =
      parseInt(
        parseInt(clockSequenceHighAndReservedHex, 16).toString(2).slice(2),
        2
      ).toString(16);
 
    const clockSequenceLowHex =
      clockSequenceHighAndReservedAndLow.slice(2, 4);
 
    const clockSequenceHex = clockSequenceLowHex + clockSequenceHighHex;
    const clockSequenceArr = [];
    for (let ii = 0; ii < 7; ii += 2) {
      clockSequenceArr.push(parseInt(clockSequenceHex.slice(ii, ii + 2), 16));
    }
 
    const clockSequence = new Uint8Array(clockSequenceArr);
 
    const nodeIdentifierHex = split[4];
    const nodeIdentifierArr = [];
    for (let ii = 0; ii < 12; ii += 2) {
      nodeIdentifierArr.push(parseInt(nodeIdentifierHex.slice(ii, ii + 2), 16));
    }
 
    const nodeIdentifier = new Uint8Array(nodeIdentifierArr);
 
    const obj = {
      __version: version,
      get version() {
        return obj.__version;
      },
 
      __timestamp: timestamp,
      get timestamp() {
        return obj.__timestamp;
      },
 
      __clockSequence: clockSequence,
      get clockSequence() {
        return obj.__clockSequence;
      },
 
      __nodeIdentifier: nodeIdentifier,
      get nodeIdentifier() {
        return obj.__nodeIdentifier;
      },
    };
 
    return Object.assign({}, this.prototype, obj);
  }
 
  toString(): string {
    const format = (value: Uint8Array, toPad: number) => (
      uintArrayAsHex(value)
        /* Pad any missing most-significant-digits. */
        .padStart(toPad, '0')
    );
 
    return (
      format(this.timeLow, 8) +
      '-' +
      format(this.timeMid, 4) +
      '-' +
      `${this.version}${format(this.timeHigh, 3)}` +
      '-' +
      `${format(this.clockSequenceHighAndReserved, 2)}${format(this.clockSequenceLow, 2)}` +
      '-' +
      format(this.nodeIdentifier, 12)
    );
  }
}
 
export default UUID;