forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathload-proxy-config.ts
198 lines (172 loc) · 6.06 KB
/
load-proxy-config.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { extname, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { makeRe as makeRegExpFromGlob } from 'picomatch';
import { isDynamicPattern } from 'tinyglobby';
import { assertIsError } from './error';
import { loadEsmModule } from './load-esm';
export async function loadProxyConfiguration(
root: string,
proxyConfig: string | undefined,
): Promise<Record<string, object> | undefined> {
if (!proxyConfig) {
return undefined;
}
const proxyPath = resolve(root, proxyConfig);
if (!existsSync(proxyPath)) {
throw new Error(`Proxy configuration file ${proxyPath} does not exist.`);
}
let proxyConfiguration;
switch (extname(proxyPath)) {
case '.json': {
const content = await readFile(proxyPath, 'utf-8');
const { parse, printParseErrorCode } = await import('jsonc-parser');
const parseErrors: import('jsonc-parser').ParseError[] = [];
proxyConfiguration = parse(content, parseErrors, { allowTrailingComma: true });
if (parseErrors.length > 0) {
let errorMessage = `Proxy configuration file ${proxyPath} contains parse errors:`;
for (const parseError of parseErrors) {
const { line, column } = getJsonErrorLineColumn(parseError.offset, content);
errorMessage += `\n[${line}, ${column}] ${printParseErrorCode(parseError.error)}`;
}
throw new Error(errorMessage);
}
break;
}
case '.mjs':
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
proxyConfiguration = (await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)))
.default;
break;
case '.cjs':
proxyConfiguration = require(proxyPath);
break;
default:
// The file could be either CommonJS or ESM.
// CommonJS is tried first then ESM if loading fails.
try {
proxyConfiguration = require(proxyPath);
break;
} catch (e) {
assertIsError(e);
if (e.code === 'ERR_REQUIRE_ESM') {
// Load the ESM configuration file using the TypeScript dynamic import workaround.
// Once TypeScript provides support for keeping the dynamic import this workaround can be
// changed to a direct dynamic import.
proxyConfiguration = (await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath)))
.default;
break;
}
throw e;
}
}
return normalizeProxyConfiguration(proxyConfiguration);
}
/**
* Converts glob patterns to regular expressions to support Vite's proxy option.
* Also converts the Webpack supported array form to an object form supported by both.
*
* @param proxy A proxy configuration object.
*/
function normalizeProxyConfiguration(
proxy: Record<string, object> | object[],
): Record<string, object> {
let normalizedProxy: Record<string, object> | undefined;
if (Array.isArray(proxy)) {
// Construct an object-form proxy configuration from the array
normalizedProxy = {};
for (const proxyEntry of proxy) {
if (!('context' in proxyEntry)) {
continue;
}
if (!Array.isArray(proxyEntry.context)) {
continue;
}
// Array-form entries contain a context string array with the path(s)
// to use for the configuration entry.
const context = proxyEntry.context;
delete proxyEntry.context;
for (const contextEntry of context) {
if (typeof contextEntry !== 'string') {
continue;
}
normalizedProxy[contextEntry] = proxyEntry;
}
}
} else {
normalizedProxy = proxy;
}
// TODO: Consider upstreaming glob support
for (const key of Object.keys(normalizedProxy)) {
if (key[0] !== '^' && isDynamicPattern(key)) {
const pattern = makeRegExpFromGlob(key).source;
normalizedProxy[pattern] = normalizedProxy[key];
delete normalizedProxy[key];
}
}
// Replace `pathRewrite` field with a `rewrite` function
for (const proxyEntry of Object.values(normalizedProxy)) {
if (
typeof proxyEntry === 'object' &&
'pathRewrite' in proxyEntry &&
proxyEntry.pathRewrite &&
typeof proxyEntry.pathRewrite === 'object'
) {
// Preprocess path rewrite entries
const pathRewriteEntries: [RegExp, string][] = [];
for (const [pattern, value] of Object.entries(
proxyEntry.pathRewrite as Record<string, string>,
)) {
pathRewriteEntries.push([new RegExp(pattern), value]);
}
(proxyEntry as Record<string, unknown>).rewrite = pathRewriter.bind(
undefined,
pathRewriteEntries,
);
delete proxyEntry.pathRewrite;
}
}
return normalizedProxy;
}
function pathRewriter(pathRewriteEntries: [RegExp, string][], path: string): string {
for (const [pattern, value] of pathRewriteEntries) {
const updated = path.replace(pattern, value);
if (path !== updated) {
return updated;
}
}
return path;
}
/**
* Calculates the line and column for an error offset in the content of a JSON file.
* @param location The offset error location from the beginning of the content.
* @param content The full content of the file containing the error.
* @returns An object containing the line and column
*/
function getJsonErrorLineColumn(offset: number, content: string) {
if (offset === 0) {
return { line: 1, column: 1 };
}
let line = 0;
let position = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
++line;
const nextNewline = content.indexOf('\n', position);
if (nextNewline === -1 || nextNewline > offset) {
break;
}
position = nextNewline + 1;
}
return { line, column: offset - position + 1 };
}