/
util.ts
209 lines (181 loc) · 6.26 KB
/
util.ts
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import eol from 'eol';
import fs from 'fs';
import path from 'path';
import resolve from 'resolve';
import slash from 'slash';
import { fileURLToPath, pathToFileURL } from 'url';
import type { ErrorPayload } from 'vite';
import type { AstroConfig } from '../@types/astro';
import { removeTrailingForwardSlash } from './path.js';
// process.env.PACKAGE_VERSION is injected when we build and publish the astro package.
export const ASTRO_VERSION = process.env.PACKAGE_VERSION ?? 'development';
/** Returns true if argument is an object of any prototype/class (but not null). */
export function isObject(value: unknown): value is Record<string, any> {
return typeof value === 'object' && value != null;
}
/** Wraps an object in an array. If an array is passed, ignore it. */
export function arraify<T>(target: T | T[]): T[] {
return Array.isArray(target) ? target : [target];
}
export function padMultilineString(source: string, n = 2) {
const lines = source.split(/\r?\n/);
return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
}
const STATUS_CODE_REGEXP = /^\/?[0-9]{3}$/;
/**
* Get the correct output filename for a route, based on your config.
* Handles both "/foo" and "foo" `name` formats.
* Handles `/404` and `/` correctly.
*/
export function getOutputFilename(astroConfig: AstroConfig, name: string) {
if (name === '/' || name === '') {
return path.posix.join(name, 'index.html');
}
if (astroConfig.build.format === 'directory' && !STATUS_CODE_REGEXP.test(name)) {
return path.posix.join(name, 'index.html');
}
return `${removeTrailingForwardSlash(name || 'index')}.html`;
}
/** is a specifier an npm package? */
export function parseNpmName(
spec: string
): { scope?: string; name: string; subpath?: string } | undefined {
// not an npm package
if (!spec || spec[0] === '.' || spec[0] === '/') return undefined;
let scope: string | undefined;
let name = '';
let parts = spec.split('/');
if (parts[0][0] === '@') {
scope = parts[0];
name = parts.shift() + '/';
}
name += parts.shift();
let subpath = parts.length ? `./${parts.join('/')}` : undefined;
return {
scope,
name,
subpath,
};
}
/** Coalesce any throw variable to an Error instance. */
export function createSafeError(err: any): Error {
return err instanceof Error || (err && err.name && err.message)
? err
: new Error(JSON.stringify(err));
}
/** generate code frame from esbuild error */
export function codeFrame(src: string, loc: ErrorPayload['err']['loc']): string {
if (!loc) return '';
const lines = eol
.lf(src)
.split('\n')
.map((ln) => ln.replace(/\t/g, ' '));
// grab 2 lines before, and 3 lines after focused line
const visibleLines = [];
for (let n = -2; n <= 2; n++) {
if (lines[loc.line + n]) visibleLines.push(loc.line + n);
}
// figure out gutter width
let gutterWidth = 0;
for (const lineNo of visibleLines) {
let w = `> ${lineNo}`;
if (w.length > gutterWidth) gutterWidth = w.length;
}
// print lines
let output = '';
for (const lineNo of visibleLines) {
const isFocusedLine = lineNo === loc.line - 1;
output += isFocusedLine ? '> ' : ' ';
output += `${lineNo + 1} | ${lines[lineNo]}\n`;
if (isFocusedLine)
output += `${Array.from({ length: gutterWidth }).join(' ')} | ${Array.from({
length: loc.column,
}).join(' ')}^\n`;
}
return output;
}
export function resolveDependency(dep: string, projectRoot: URL) {
const resolved = resolve.sync(dep, {
basedir: fileURLToPath(projectRoot),
});
// For Windows compat, we need a fully resolved `file://` URL string
return pathToFileURL(resolved).toString();
}
/**
* Convert file URL to ID for viteServer.moduleGraph.idToModuleMap.get(:viteID)
* Format:
* Linux/Mac: /Users/astro/code/my-project/src/pages/index.astro
* Windows: C:/Users/astro/code/my-project/src/pages/index.astro
*/
export function viteID(filePath: URL): string {
return slash(fileURLToPath(filePath));
}
export const VALID_ID_PREFIX = `/@id/`;
// Strip valid id prefix. This is prepended to resolved Ids that are
// not valid browser import specifiers by the importAnalysis plugin.
export function unwrapId(id: string): string {
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id;
}
/** An fs utility, similar to `rimraf` or `rm -rf` */
export function removeDir(_dir: URL): void {
const dir = fileURLToPath(_dir);
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 });
}
export function emptyDir(_dir: URL, skip?: Set<string>): void {
const dir = fileURLToPath(_dir);
if (!fs.existsSync(dir)) return undefined;
for (const file of fs.readdirSync(dir)) {
if (skip?.has(file)) {
continue;
}
fs.rmSync(path.resolve(dir, file), { recursive: true, force: true, maxRetries: 3 });
}
}
export function resolvePages(config: AstroConfig) {
return new URL('./pages', config.srcDir);
}
function isInPagesDir(file: URL, config: AstroConfig): boolean {
const pagesDir = resolvePages(config);
return file.toString().startsWith(pagesDir.toString());
}
function isPublicRoute(file: URL, config: AstroConfig): boolean {
const pagesDir = resolvePages(config);
const parts = file.toString().replace(pagesDir.toString(), '').split('/').slice(1);
for (const part of parts) {
if (part.startsWith('_')) return false;
}
return true;
}
function endsWithPageExt(file: URL, config: AstroConfig): boolean {
for (const ext of config._ctx.pageExtensions) {
if (file.toString().endsWith(ext)) return true;
}
return false;
}
export function isPage(file: URL, config: AstroConfig): boolean {
if (!isInPagesDir(file, config)) return false;
if (!isPublicRoute(file, config)) return false;
return endsWithPageExt(file, config);
}
export function isModeServerWithNoAdapter(config: AstroConfig): boolean {
return config.output === 'server' && !config._ctx.adapter;
}
export function relativeToSrcDir(config: AstroConfig, idOrUrl: URL | string) {
let id: string;
if (typeof idOrUrl !== 'string') {
id = unwrapId(viteID(idOrUrl));
} else {
id = idOrUrl;
}
return id.slice(slash(fileURLToPath(config.srcDir)).length);
}
export function emoji(char: string, fallback: string) {
return process.platform !== 'win32' ? char : fallback;
}
export function getLocalAddress(serverAddress: string, host: string | boolean): string {
if (typeof host === 'boolean' || host === 'localhost') {
return 'localhost';
} else {
return serverAddress;
}
}