or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

constants-conversions.mdindex.mduuid-generation.mduuid-utilities.md

uuid-utilities.mddocs/

0

# UUID Utilities

1

2

Essential utility functions for working with UUIDs including parsing, stringifying, validation, and version detection.

3

4

## Capabilities

5

6

### Parse UUID String

7

8

Converts a UUID string to its binary representation as a Uint8Array.

9

10

```typescript { .api }

11

/**

12

* Convert UUID string to byte array representation

13

* @param uuid - Valid UUID string in canonical format

14

* @returns Uint8Array of 16 bytes representing the UUID

15

* @throws TypeError if UUID string is invalid

16

*/

17

function parse(uuid: string): Uint8Array;

18

```

19

20

**Usage Examples:**

21

22

```typescript

23

import { parse } from "uuid";

24

25

// Parse a valid UUID string

26

const uuid = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d';

27

const bytes = parse(uuid);

28

// ⇨ Uint8Array(16) [155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109]

29

30

// Access individual bytes

31

console.log(bytes[0]); // ⇨ 155 (first byte)

32

console.log(bytes.length); // ⇨ 16

33

34

// Parse throws on invalid UUID

35

try {

36

parse('invalid-uuid');

37

} catch (error) {

38

console.log(error.message); // ⇨ 'Invalid UUID'

39

}

40

```

41

42

### Stringify Byte Array

43

44

Converts a byte array back to a UUID string in canonical format.

45

46

```typescript { .api }

47

/**

48

* Convert byte array to UUID string format

49

* @param arr - Array of 16 bytes representing a UUID

50

* @param offset - Starting offset in array (default: 0)

51

* @returns UUID string in canonical format (lowercase with hyphens)

52

* @throws TypeError if resulting UUID is invalid

53

*/

54

function stringify(arr: Uint8Array, offset?: number): string;

55

```

56

57

### Unsafe Stringify Byte Array

58

59

Converts a byte array to a UUID string without validation for performance-critical applications.

60

61

```typescript { .api }

62

/**

63

* Convert byte array to UUID string without validation

64

* @param arr - Array of 16 bytes representing a UUID

65

* @param offset - Starting offset in array (default: 0)

66

* @returns UUID string in canonical format (lowercase with hyphens)

67

* @warning No validation performed - ensure input is valid UUID bytes

68

*/

69

function unsafeStringify(arr: Uint8Array, offset?: number): string;

70

```

71

72

**Usage Examples:**

73

74

```typescript

75

import { stringify, unsafeStringify, parse } from "uuid";

76

77

// Create byte array manually

78

const bytes = new Uint8Array([

79

155, 29, 235, 77, 59, 125, 75, 173,

80

155, 221, 43, 13, 123, 61, 203, 109

81

]);

82

83

const uuidString = stringify(bytes);

84

// ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

85

86

// Performance-critical path with known valid bytes

87

const fastUuid = unsafeStringify(bytes);

88

// ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' (no validation)

89

90

// Round-trip conversion

91

const original = '550e8400-e29b-41d4-a716-446655440000';

92

const parsed = parse(original);

93

const restored = stringify(parsed);

94

console.log(original === restored); // ⇨ true

95

96

// Using offset for buffer operations

97

const buffer = new Uint8Array(32);

98

// ... UUID bytes written starting at position 8

99

const uuidFromBuffer = stringify(buffer, 8);

100

const fastUuidFromBuffer = unsafeStringify(buffer, 8);

101

```

102

103

### Validate UUID

104

105

Tests whether a value is a valid UUID string according to RFC9562 format.

106

107

```typescript { .api }

108

/**

109

* Test if value is a valid UUID string

110

* @param uuid - Value to test (can be any type)

111

* @returns Boolean indicating whether the value is a valid UUID string

112

*/

113

function validate(uuid: unknown): boolean;

114

```

115

116

**Usage Examples:**

117

118

```typescript

119

import { validate } from "uuid";

120

121

// Valid UUIDs

122

console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d')); // ⇨ true

123

console.log(validate('00000000-0000-0000-0000-000000000000')); // ⇨ true (NIL UUID)

124

console.log(validate('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF')); // ⇨ true (case insensitive)

125

126

// Invalid UUIDs

127

console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6')); // ⇨ false (too short)

128

console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6dd')); // ⇨ false (too long)

129

console.log(validate('9b1deb4d_3b7d_4bad_9bdd_2b0d7b3dcb6d')); // ⇨ false (wrong separator)

130

console.log(validate('not-a-uuid')); // ⇨ false

131

console.log(validate(null)); // ⇨ false

132

console.log(validate(undefined)); // ⇨ false

133

console.log(validate(123)); // ⇨ false

134

135

// Type guard usage

136

function processUuid(value: unknown) {

137

if (validate(value)) {

138

// TypeScript knows value is a valid UUID string

139

console.log(`Processing UUID: ${value.toUpperCase()}`);

140

} else {

141

console.log('Invalid UUID provided');

142

}

143

}

144

```

145

146

### Get UUID Version

147

148

Extracts and returns the version number from a UUID string.

149

150

```typescript { .api }

151

/**

152

* Extract and return the version number from UUID string

153

* @param uuid - Valid UUID string

154

* @returns Version number (1-7) indicating the UUID type

155

* @throws TypeError if UUID string is invalid

156

*/

157

function version(uuid: string): number;

158

```

159

160

**Usage Examples:**

161

162

```typescript

163

import { version, v1, v3, v4, v5, v6, v7 } from "uuid";

164

165

// Check versions of generated UUIDs

166

const v1Id = v1();

167

const v4Id = v4();

168

const v7Id = v7();

169

170

console.log(version(v1Id)); // ⇨ 1

171

console.log(version(v4Id)); // ⇨ 4

172

console.log(version(v7Id)); // ⇨ 7

173

174

// Version-specific processing

175

function handleUuid(uuid: string) {

176

if (!validate(uuid)) {

177

throw new Error('Invalid UUID');

178

}

179

180

const ver = version(uuid);

181

182

switch (ver) {

183

case 1:

184

case 6:

185

console.log('Timestamp-based UUID');

186

break;

187

case 3:

188

case 5:

189

console.log('Namespace-based UUID');

190

break;

191

case 4:

192

console.log('Random UUID');

193

break;

194

case 7:

195

console.log('Unix Epoch time UUID');

196

break;

197

default:

198

console.log(`UUID version ${ver}`);

199

}

200

}

201

202

// Check existing UUID versions

203

console.log(version('550e8400-e29b-41d4-a716-446655440000')); // ⇨ 4

204

console.log(version('6ba7b810-9dad-11d1-80b4-00c04fd430c8')); // ⇨ 1

205

206

// Version extraction throws on invalid UUID

207

try {

208

version('invalid-uuid');

209

} catch (error) {

210

console.log(error.message); // ⇨ 'Invalid UUID'

211

}

212

```

213

214

### String to Bytes Conversion

215

216

Converts a string to its UTF-8 byte array representation for use with namespace-based UUID generation.

217

218

```typescript { .api }

219

/**

220

* Convert string to byte array using UTF-8 encoding

221

* @param str - String to convert to bytes

222

* @returns Uint8Array representation of the string in UTF-8

223

*/

224

function stringToBytes(str: string): Uint8Array;

225

```

226

227

**Usage Examples:**

228

229

```typescript

230

import { stringToBytes, v5 } from "uuid";

231

232

// Convert string for namespace UUID generation

233

const nameBytes = stringToBytes("my-resource-name");

234

const resourceId = v5(nameBytes, v5.DNS);

235

236

// Compare with direct string usage (equivalent)

237

const directId = v5("my-resource-name", v5.DNS);

238

console.log(resourceId === directId); // ⇨ true

239

240

// Useful for non-ASCII strings

241

const unicodeBytes = stringToBytes("資源名称");

242

const unicodeId = v5(unicodeBytes, v5.DNS);

243

244

// Manual UTF-8 encoding comparison

245

const manualBytes = new TextEncoder().encode("my-resource-name");

246

console.log(stringToBytes("my-resource-name").every((byte, i) => byte === manualBytes[i])); // ⇨ true

247

```

248

249

### Internal Testing Functions

250

251

Functions exported for internal testing purposes only. These should not be used in production code.

252

253

```typescript { .api }

254

/**

255

* Update V1 state (exported for testing only)

256

* @param state - V1 state object

257

* @param now - Current timestamp

258

* @param rnds - Random bytes

259

* @returns Updated state object

260

* @internal

261

*/

262

function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State;

263

264

/**

265

* Update V7 state (exported for testing only)

266

* @param state - V7 state object

267

* @param now - Current timestamp

268

* @param rnds - Random bytes

269

* @returns Updated state object

270

* @internal

271

*/

272

function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State;

273

```

274

275

⚠️ **Warning**: These functions are exported for internal testing purposes only and should not be used in production code. Their behavior may change without notice.

276

277

## Combined Usage Patterns

278

279

Common patterns combining multiple utility functions:

280

281

```typescript

282

import { v4, parse, stringify, validate, version } from "uuid";

283

284

// Safe UUID processing pipeline

285

function processUuidSafely(input: unknown): { valid: boolean; info?: any } {

286

if (!validate(input)) {

287

return { valid: false };

288

}

289

290

const ver = version(input as string);

291

const bytes = parse(input as string);

292

const canonical = stringify(bytes);

293

294

return {

295

valid: true,

296

info: {

297

version: ver,

298

canonical: canonical,

299

bytes: Array.from(bytes),

300

length: bytes.length

301

}

302

};

303

}

304

305

// UUID normalization

306

function normalizeUuid(uuid: string): string {

307

if (!validate(uuid)) {

308

throw new Error('Invalid UUID format');

309

}

310

311

// Parse and stringify to ensure canonical format

312

return stringify(parse(uuid));

313

}

314

315

// Example: normalize mixed case UUID

316

const mixedCase = 'A1B2C3D4-E5F6-1234-ABCD-123456789ABC';

317

const normalized = normalizeUuid(mixedCase);

318

// ⇨ 'a1b2c3d4-e5f6-1234-abcd-123456789abc'

319

```