All files / uuid / common.ts

100.00% Branches 2/2
100.00% Lines 15/15
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
 
 
 
x20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x20
x24
x24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x20
x20060
x20060
x20060
 
x20060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x20
x32
x36
x36
 
x40
x32






































































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { NIL_UUID } from "./constants.ts";

/**
 * Determines whether the UUID is the
 * {@link https://www.rfc-editor.org/rfc/rfc4122#section-4.1.7 | nil UUID}.
 *
 * @param id UUID value.
 *
 * @returns `true` if the UUID is the nil UUID, otherwise `false`.
 *
 * @example Usage
 * ```ts
 * import { isNil } from "@std/uuid";
 * import { assert, assertFalse } from "@std/assert";
 *
 * assert(isNil("00000000-0000-0000-0000-000000000000"));
 * assertFalse(isNil(crypto.randomUUID()));
 * ```
 */
export function isNil(id: string): boolean {
  return id === NIL_UUID;
}

/**
 * Determines whether a string is a valid UUID.
 *
 * @param uuid UUID value.
 *
 * @returns `true` if the string is a valid UUID, otherwise `false`.
 *
 * @example Usage
 * ```ts
 * import { validate } from "@std/uuid";
 * import { assert, assertFalse } from "@std/assert";
 *
 * assert(validate("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b"));
 * assertFalse(validate("not a UUID"));
 * ```
 */
export function validate(uuid: string): boolean {
  return /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-6][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i
    .test(
      uuid,
    );
}

/**
 * Detect RFC version of a UUID.
 *
 * @param uuid UUID value.
 *
 * @returns The RFC version of the UUID.
 *
 * @example Usage
 * ```ts
 * import { version } from "@std/uuid";
 * import { assertEquals } from "@std/assert";
 *
 * assertEquals(version("d9428888-122b-11e1-b85c-61cd3cbb3210"), 1);
 * assertEquals(version("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b"), 4);
 * ```
 */
export function version(uuid: string): number {
  if (!validate(uuid)) {
    throw new TypeError(`Cannot detect UUID version: received ${uuid}`);
  }

  return parseInt(uuid[14]!, 16);
}