or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

encoding.mdindex.mdparsing.mdquery.mdurl-class.mdutilities.md

utilities.mddocs/

0

# URL Utilities

1

2

Extensive collection of utility functions for URL manipulation including path joining, protocol management, slash handling, base URL operations, and URL comparison. These functions provide the building blocks for complex URL manipulation workflows.

3

4

## Capabilities

5

6

### URL Joining & Resolution

7

8

Functions for combining URL segments and resolving complex URL structures.

9

10

```typescript { .api }

11

/**

12

* Joins multiple URL segments into a single URL

13

* @param base - Base URL or path

14

* @param input - Additional URL segments to join

15

* @returns Combined URL string

16

*/

17

function joinURL(base: string, ...input: string[]): string;

18

19

/**

20

* Joins URL segments with relative path support (./ and ../)

21

* @param input - URL segments to join with relative path resolution

22

* @returns Resolved URL string

23

*/

24

function joinRelativeURL(...input: string[]): string;

25

26

/**

27

* Resolves multiple URL segments into a single URL with query merging

28

* @param base - Base URL (defaults to empty string)

29

* @param inputs - URL segments to resolve

30

* @returns Resolved URL with merged queries and paths

31

*/

32

function resolveURL(base?: string, ...inputs: string[]): string;

33

```

34

35

**Usage Examples:**

36

37

```typescript

38

import { joinURL, joinRelativeURL, resolveURL } from "ufo";

39

40

// Basic URL joining

41

const api = joinURL("https://api.example.com", "v1", "users", "123");

42

// "https://api.example.com/v1/users/123"

43

44

const path = joinURL("/app", "dashboard", "settings");

45

// "/app/dashboard/settings"

46

47

// Relative path resolution

48

const relative = joinRelativeURL("/app", "../home", "./profile");

49

// "/home/profile"

50

51

const complex = joinRelativeURL("https://example.com/app", "../../api", "./v1/users");

52

// "https://example.com/api/v1/users"

53

54

// URL resolution with query merging

55

const resolved = resolveURL(

56

"https://api.example.com/search?sort=date",

57

"users?active=true",

58

"profiles#section"

59

);

60

// "https://api.example.com/search/users/profiles?sort=date&active=true#section"

61

```

62

63

### Protocol Management

64

65

Functions for detecting, adding, removing, and changing URL protocols.

66

67

```typescript { .api }

68

/**

69

* Checks if the input has a protocol

70

* @param inputString - String to check for protocol

71

* @param opts - Options for protocol detection

72

* @returns True if protocol is present

73

*/

74

function hasProtocol(inputString: string, opts?: HasProtocolOptions): boolean;

75

76

/**

77

* Adds or replaces protocol of the input URL

78

* @param input - URL string

79

* @param protocol - Protocol to set (e.g., "https://")

80

* @returns URL with specified protocol

81

*/

82

function withProtocol(input: string, protocol: string): string;

83

84

/**

85

* Adds or replaces the URL protocol to https://

86

* @param input - URL string

87

* @returns URL with https protocol

88

*/

89

function withHttps(input: string): string;

90

91

/**

92

* Adds or replaces the URL protocol to http://

93

* @param input - URL string

94

* @returns URL with http protocol

95

*/

96

function withHttp(input: string): string;

97

98

/**

99

* Removes the protocol from the input

100

* @param input - URL string

101

* @returns URL without protocol

102

*/

103

function withoutProtocol(input: string): string;

104

105

/**

106

* Checks for dangerous script protocols

107

* @param protocol - Protocol to check

108

* @returns True if protocol is potentially dangerous

109

*/

110

function isScriptProtocol(protocol?: string): boolean;

111

112

interface HasProtocolOptions {

113

acceptRelative?: boolean;

114

strict?: boolean;

115

}

116

```

117

118

**Usage Examples:**

119

120

```typescript

121

import { hasProtocol, withHttps, withHttp, withoutProtocol, isScriptProtocol } from "ufo";

122

123

// Protocol detection

124

const hasProto = hasProtocol("https://example.com");

125

// true

126

127

const relative = hasProtocol("//example.com", { acceptRelative: true });

128

// true

129

130

// Protocol manipulation

131

const secure = withHttps("http://example.com/path");

132

// "https://example.com/path"

133

134

const insecure = withHttp("https://example.com/path");

135

// "http://example.com/path"

136

137

const noProto = withoutProtocol("https://example.com/path");

138

// "example.com/path"

139

140

// Security check

141

const dangerous = isScriptProtocol("javascript:");

142

// true

143

144

const safe = isScriptProtocol("https:");

145

// false

146

```

147

148

### Slash Management

149

150

Functions for controlling leading and trailing slashes in URLs and paths.

151

152

```typescript { .api }

153

/**

154

* Checks if the input has a trailing slash

155

* @param input - String to check

156

* @param respectQueryAndFragment - Consider query/fragment in check

157

* @returns True if trailing slash is present

158

*/

159

function hasTrailingSlash(input?: string, respectQueryAndFragment?: boolean): boolean;

160

161

/**

162

* Removes the trailing slash from URL or pathname

163

* @param input - String to process

164

* @param respectQueryAndFragment - Respect query/fragment boundaries

165

* @returns String without trailing slash

166

*/

167

function withoutTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string;

168

169

/**

170

* Ensures the URL ends with a trailing slash

171

* @param input - String to process

172

* @param respectQueryAndFragment - Respect query/fragment boundaries

173

* @returns String with trailing slash

174

*/

175

function withTrailingSlash(input?: string, respectQueryAndFragment?: boolean): string;

176

177

/**

178

* Checks if the input has a leading slash

179

* @param input - String to check

180

* @returns True if leading slash is present

181

*/

182

function hasLeadingSlash(input?: string): boolean;

183

184

/**

185

* Removes leading slash from URL or pathname

186

* @param input - String to process

187

* @returns String without leading slash

188

*/

189

function withoutLeadingSlash(input?: string): string;

190

191

/**

192

* Ensures the URL or pathname has a leading slash

193

* @param input - String to process

194

* @returns String with leading slash

195

*/

196

function withLeadingSlash(input?: string): string;

197

198

/**

199

* Removes double slashes from the URL

200

* @param input - String to clean

201

* @returns String without double slashes

202

*/

203

function cleanDoubleSlashes(input?: string): string;

204

```

205

206

**Usage Examples:**

207

208

```typescript

209

import {

210

withTrailingSlash,

211

withoutTrailingSlash,

212

withLeadingSlash,

213

withoutLeadingSlash,

214

cleanDoubleSlashes

215

} from "ufo";

216

217

// Trailing slash management

218

const withSlash = withTrailingSlash("/path");

219

// "/path/"

220

221

const withoutSlash = withoutTrailingSlash("/path/");

222

// "/path"

223

224

// Respecting query parameters

225

const querySlash = withoutTrailingSlash("/path/?query=true", true);

226

// "/path?query=true"

227

228

// Leading slash management

229

const leadingSlash = withLeadingSlash("path/to/resource");

230

// "/path/to/resource"

231

232

const noLeadingSlash = withoutLeadingSlash("/path/to/resource");

233

// "path/to/resource"

234

235

// Clean double slashes

236

const cleaned = cleanDoubleSlashes("//example.com//path//to//resource");

237

// "//example.com/path/to/resource"

238

239

const protocol = cleanDoubleSlashes("http://example.com//api//v1");

240

// "http://example.com/api/v1"

241

```

242

243

### Base URL Operations

244

245

Functions for working with base URLs and relative paths.

246

247

```typescript { .api }

248

/**

249

* Ensures the URL or pathname starts with base

250

* @param input - URL to modify

251

* @param base - Base URL to ensure

252

* @returns URL with base prefix

253

*/

254

function withBase(input: string, base: string): string;

255

256

/**

257

* Removes the base from the URL or pathname

258

* @param input - URL to modify

259

* @param base - Base URL to remove

260

* @returns URL without base prefix

261

*/

262

function withoutBase(input: string, base: string): string;

263

264

/**

265

* Checks if a path starts with ./ or ../

266

* @param inputString - Path to check

267

* @returns True if path is relative

268

*/

269

function isRelative(inputString: string): boolean;

270

```

271

272

**Usage Examples:**

273

274

```typescript

275

import { withBase, withoutBase, isRelative } from "ufo";

276

277

// Add base to URL

278

const withBasePath = withBase("/api/users", "/v1");

279

// "/v1/api/users"

280

281

const withBaseUrl = withBase("users/123", "https://api.example.com");

282

// "https://api.example.com/users/123"

283

284

// Remove base from URL

285

const withoutBasePath = withoutBase("/v1/api/users", "/v1");

286

// "/api/users"

287

288

// Relative path detection

289

const isRel1 = isRelative("./path/to/file");

290

// true

291

292

const isRel2 = isRelative("../parent/file");

293

// true

294

295

const isRel3 = isRelative("/absolute/path");

296

// false

297

```

298

299

### Query and Fragment Management

300

301

Functions for manipulating query parameters and URL fragments.

302

303

```typescript { .api }

304

/**

305

* Add/Replace the query section of the URL

306

* @param input - URL string

307

* @param query - Query object to merge

308

* @returns URL with merged query parameters

309

*/

310

function withQuery(input: string, query: QueryObject): string;

311

312

/**

313

* Filters query parameters based on a predicate function

314

* @param input - URL string

315

* @param predicate - Function to test each query parameter

316

* @returns URL with filtered query parameters

317

*/

318

function filterQuery(

319

input: string,

320

predicate: (key: string, value: string | string[]) => boolean

321

): string;

322

323

/**

324

* Parses and decodes the query object from a URL string

325

* @param input - Complete URL string

326

* @returns Parsed query object

327

*/

328

function getQuery<T extends ParsedQuery = ParsedQuery>(input: string): T;

329

330

/**

331

* Adds or replaces the fragment section of the URL

332

* @param input - URL string

333

* @param hash - Fragment/hash to set

334

* @returns URL with specified fragment

335

*/

336

function withFragment(input: string, hash: string): string;

337

338

/**

339

* Removes the fragment section from the URL

340

* @param input - URL string

341

* @returns URL without fragment

342

*/

343

function withoutFragment(input: string): string;

344

345

/**

346

* Removes the host from the URL while preserving everything else

347

* @param input - URL string

348

* @returns Path with query and fragment only

349

*/

350

function withoutHost(input: string): string;

351

352

type QueryObject = Record<string, QueryValue | QueryValue[]>;

353

type QueryValue = string | number | undefined | null | boolean | Array<QueryValue> | Record<string, any>;

354

type ParsedQuery = Record<string, string | string[]>;

355

```

356

357

**Usage Examples:**

358

359

```typescript

360

import { withQuery, filterQuery, getQuery, withFragment, withoutFragment, withoutHost } from "ufo";

361

362

// Add query parameters

363

const withParams = withQuery("/search", { q: "javascript", limit: 10 });

364

// "/search?q=javascript&limit=10"

365

366

// Merge with existing query

367

const merged = withQuery("/search?sort=date", { q: "javascript", limit: 10 });

368

// "/search?sort=date&q=javascript&limit=10"

369

370

// Filter query parameters

371

const filtered = filterQuery("/search?a=1&b=2&c=3", (key) => key !== "b");

372

// "/search?a=1&c=3"

373

374

// Extract query from URL

375

const query = getQuery("https://api.example.com/search?q=javascript&limit=10&sort=date");

376

// { q: 'javascript', limit: '10', sort: 'date' }

377

378

// Works with relative URLs

379

const relative = getQuery("/search?category=web&tags=js&tags=api");

380

// { category: 'web', tags: ['js', 'api'] }

381

382

// Fragment management

383

const withHash = withFragment("/page", "section1");

384

// "/page#section1"

385

386

const noHash = withoutFragment("/page#section1");

387

// "/page"

388

389

// Remove host

390

const pathOnly = withoutHost("https://example.com/api/users?active=true#list");

391

// "/api/users?active=true#list"

392

```

393

394

### URL Validation and Comparison

395

396

Functions for validating and comparing URLs.

397

398

```typescript { .api }

399

/**

400

* Checks if the input URL is empty or just "/"

401

* @param url - URL to check

402

* @returns True if URL is empty

403

*/

404

function isEmptyURL(url: string): boolean;

405

406

/**

407

* Checks if the input URL is neither empty nor "/"

408

* @param url - URL to check

409

* @returns True if URL is non-empty

410

*/

411

function isNonEmptyURL(url: string): boolean;

412

413

/**

414

* Check if two paths are equal ignoring trailing slash and encoding

415

* @param p1 - First path

416

* @param p2 - Second path

417

* @returns True if paths are equivalent

418

*/

419

function isSamePath(p1: string, p2: string): boolean;

420

421

/**

422

* Flexible URL comparison with configurable options

423

* @param a - First URL

424

* @param b - Second URL

425

* @param options - Comparison options

426

* @returns True if URLs are equivalent under given options

427

*/

428

function isEqual(a: string, b: string, options?: CompareURLOptions): boolean;

429

430

interface CompareURLOptions {

431

trailingSlash?: boolean;

432

leadingSlash?: boolean;

433

encoding?: boolean;

434

}

435

```

436

437

**Usage Examples:**

438

439

```typescript

440

import { isEmptyURL, isNonEmptyURL, isSamePath, isEqual } from "ufo";

441

442

// URL emptiness checks

443

const empty1 = isEmptyURL("");

444

// true

445

446

const empty2 = isEmptyURL("/");

447

// true

448

449

const nonEmpty = isNonEmptyURL("/home");

450

// true

451

452

// Path comparison

453

const samePath = isSamePath("/foo", "/foo/");

454

// true (ignores trailing slash)

455

456

const sameEncoded = isSamePath("/foo bar", "/foo%20bar");

457

// true (ignores encoding differences)

458

459

// Flexible URL comparison

460

const flexible = isEqual("/foo", "foo");

461

// true (ignores leading slash by default)

462

463

const strict = isEqual("/foo", "foo", { leadingSlash: true });

464

// false (strict leading slash comparison)

465

466

const encodingStrict = isEqual("/foo bar", "/foo%20bar", { encoding: true });

467

// false (strict encoding comparison)

468

```

469

470

### URL Normalization

471

472

Function for normalizing URLs to a consistent format.

473

474

```typescript { .api }

475

/**

476

* Normalizes the input URL by ensuring proper encoding and format

477

* @param input - URL string to normalize

478

* @returns Normalized URL string

479

*/

480

function normalizeURL(input: string): string;

481

```

482

483

**Usage Examples:**

484

485

```typescript

486

import { normalizeURL } from "ufo";

487

488

// Normalize encoding and format

489

const normalized = normalizeURL("test?query=123 123#hash, test");

490

// "test?query=123%20123#hash,%20test"

491

492

// Clean up double slashes while preserving protocol

493

const cleaned = normalizeURL("http://example.com//path//to//resource");

494

// "http://example.com/path/to/resource"

495

496

// Normalize international domains

497

const international = normalizeURL("https://пример.рф/путь");

498

// "https://xn--e1afmkfd.xn--p1ai/%D0%BF%D1%83%D1%82%D1%8C"

499

```