@larc-iu/plaid-client 0.2.0-alpha.2 → 0.2.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ids.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Ids a client mints for what it creates.
3
+ *
4
+ * A create may name the id of the row it makes, so a create sent again after
5
+ * its answer was lost lands under the same id or is told the id is taken
6
+ * (409 with `id-taken`). The server takes only a UUIDv7 (RFC 9562), shaped
7
+ * as its own ids are: a 48-bit millisecond timestamp, a 12-bit counter
8
+ * within the millisecond, then 62 random bits. Reads are id-ordered, so ids
9
+ * minted in one millisecond must still sort in the order they were made.
10
+ */
11
+
12
+ let lastMs = 0;
13
+ let counter = 0;
14
+
15
+ const hex = Array.from({ length: 256 }, (_, i) =>
16
+ i.toString(16).padStart(2, "0"),
17
+ );
18
+
19
+ /**
20
+ * A fresh UUIDv7, later than every one this page minted before it.
21
+ * @returns {string}
22
+ */
23
+ export function uuidv7() {
24
+ const now = Date.now();
25
+ if (now > lastMs) {
26
+ lastMs = now;
27
+ counter = 0;
28
+ } else if (counter < 0xfff) {
29
+ counter += 1;
30
+ } else {
31
+ // This millisecond is full: take the next one rather than repeat an order.
32
+ lastMs += 1;
33
+ counter = 0;
34
+ }
35
+ const b = new Uint8Array(16);
36
+ crypto.getRandomValues(b);
37
+ const high = Math.floor(lastMs / 0x100000000);
38
+ const low = lastMs >>> 0;
39
+ b[0] = (high >>> 8) & 0xff;
40
+ b[1] = high & 0xff;
41
+ b[2] = (low >>> 24) & 0xff;
42
+ b[3] = (low >>> 16) & 0xff;
43
+ b[4] = (low >>> 8) & 0xff;
44
+ b[5] = low & 0xff;
45
+ b[6] = 0x70 | (counter >>> 8);
46
+ b[7] = counter & 0xff;
47
+ b[8] = (b[8] & 0x3f) | 0x80;
48
+ let s = "";
49
+ for (let i = 0; i < 16; i++) {
50
+ s += hex[b[i]];
51
+ if (i === 3 || i === 5 || i === 7 || i === 9) s += "-";
52
+ }
53
+ return s;
54
+ }