summaryrefslogtreecommitdiff
path: root/packages/integrations/image/src/utils/paths.ts
blob: a6618ff1e9d52c9d1f02fce34faa05dc4f857aa9 (plain) (blame)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import type { TransformOptions } from '../loaders/index.js';
import { shorthash } from './shorthash.js';

export function isRemoteImage(src: string) {
	return /^(https?:)?\/\//.test(src);
}

function removeQueryString(src: string) {
	const index = src.lastIndexOf('?');
	return index > 0 ? src.substring(0, index) : src;
}

export function extname(src: string) {
	const base = basename(src);
	const index = base.lastIndexOf('.');

	if (index <= 0) {
		return '';
	}

	return base.substring(index);
}

function removeExtname(src: string) {
	const index = src.lastIndexOf('.');

	if (index <= 0) {
		return src;
	}

	return src.substring(0, index);
}

function basename(src: string) {
	return removeQueryString(src.replace(/^.*[\\\/]/, ''));
}

export function propsToFilename(transform: TransformOptions, serviceEntryPoint: string) {
	// strip off the querystring first, then remove the file extension
	let filename = removeQueryString(transform.src);
	// take everything from transform except alt, which is not used in the hash
	const { alt, ...rest } = transform;
	const hashFields = { ...rest, serviceEntryPoint };
	filename = basename(filename);
	const ext = extname(filename);
	filename = removeExtname(filename);

	const outputExt = transform.format ? `.${transform.format}` : ext;

	return `/${filename}_${shorthash(JSON.stringify(hashFields))}${outputExt}`;
}

export function appendForwardSlash(path: string) {
	return path.endsWith('/') ? path : path + '/';
}

export function prependForwardSlash(path: string) {
	return path[0] === '/' ? path : '/' + path;
}

export function removeTrailingForwardSlash(path: string) {
	return path.endsWith('/') ? path.slice(0, path.length - 1) : path;
}

export function removeLeadingForwardSlash(path: string) {
	return path.startsWith('/') ? path.substring(1) : path;
}

export function trimSlashes(path: string) {
	return path.replace(/^\/|\/$/g, '');
}

function isString(path: unknown): path is string {
	return typeof path === 'string' || path instanceof String;
}

export function joinPaths(...paths: (string | undefined)[]) {
	return paths
		.filter(isString)
		.map((path, i) => {
			if (i === 0) {
				return removeTrailingForwardSlash(path);
			} else if (i === paths.length - 1) {
				return removeLeadingForwardSlash(path);
			} else {
				return trimSlashes(path);
			}
		})
		.join('/');
}