v7.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.updateV7State = void 0;
  4. const rng_js_1 = require("./rng.js");
  5. const stringify_js_1 = require("./stringify.js");
  6. const _state = {};
  7. function v7(options, buf, offset) {
  8. let bytes;
  9. if (options) {
  10. bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset);
  11. }
  12. else {
  13. const now = Date.now();
  14. const rnds = (0, rng_js_1.default)();
  15. updateV7State(_state, now, rnds);
  16. bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
  17. }
  18. return buf ?? (0, stringify_js_1.unsafeStringify)(bytes);
  19. }
  20. function updateV7State(state, now, rnds) {
  21. state.msecs ??= -Infinity;
  22. state.seq ??= 0;
  23. if (now > state.msecs) {
  24. state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];
  25. state.msecs = now;
  26. }
  27. else {
  28. state.seq = (state.seq + 1) | 0;
  29. if (state.seq === 0) {
  30. state.msecs++;
  31. }
  32. }
  33. return state;
  34. }
  35. exports.updateV7State = updateV7State;
  36. function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
  37. if (rnds.length < 16) {
  38. throw new Error('Random bytes length must be >= 16');
  39. }
  40. if (!buf) {
  41. buf = new Uint8Array(16);
  42. offset = 0;
  43. }
  44. else {
  45. if (offset < 0 || offset + 16 > buf.length) {
  46. throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
  47. }
  48. }
  49. msecs ??= Date.now();
  50. seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];
  51. buf[offset++] = (msecs / 0x10000000000) & 0xff;
  52. buf[offset++] = (msecs / 0x100000000) & 0xff;
  53. buf[offset++] = (msecs / 0x1000000) & 0xff;
  54. buf[offset++] = (msecs / 0x10000) & 0xff;
  55. buf[offset++] = (msecs / 0x100) & 0xff;
  56. buf[offset++] = msecs & 0xff;
  57. buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f);
  58. buf[offset++] = (seq >>> 20) & 0xff;
  59. buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f);
  60. buf[offset++] = (seq >>> 6) & 0xff;
  61. buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03);
  62. buf[offset++] = rnds[11];
  63. buf[offset++] = rnds[12];
  64. buf[offset++] = rnds[13];
  65. buf[offset++] = rnds[14];
  66. buf[offset++] = rnds[15];
  67. return buf;
  68. }
  69. exports.default = v7;