-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathvite.config.js
More file actions
266 lines (232 loc) · 6.13 KB
/
vite.config.js
File metadata and controls
266 lines (232 loc) · 6.13 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import path from 'node:path';
import react from '@vitejs/plugin-react';
import { createLogger, defineConfig } from 'vite';
import inlineEditPlugin from './plugins/visual-editor/vite-plugin-react-inline-editor.js';
import editModeDevPlugin from './plugins/visual-editor/vite-plugin-edit-mode.js';
import iframeRouteRestorationPlugin from './plugins/vite-plugin-iframe-route-restoration.js';
import selectionModePlugin from './plugins/selection-mode/vite-plugin-selection-mode.js';
const isDev = process.env.NODE_ENV !== 'production';
const configHorizonsViteErrorHandler = `
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
for (const addedNode of mutation.addedNodes) {
if (
addedNode.nodeType === Node.ELEMENT_NODE &&
(
addedNode.tagName?.toLowerCase() === 'vite-error-overlay' ||
addedNode.classList?.contains('backdrop')
)
) {
handleViteOverlay(addedNode);
}
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
function handleViteOverlay(node) {
if (!node.shadowRoot) {
return;
}
const backdrop = node.shadowRoot.querySelector('.backdrop');
if (backdrop) {
const overlayHtml = backdrop.outerHTML;
const parser = new DOMParser();
const doc = parser.parseFromString(overlayHtml, 'text/html');
const messageBodyElement = doc.querySelector('.message-body');
const fileElement = doc.querySelector('.file');
const messageText = messageBodyElement ? messageBodyElement.textContent.trim() : '';
const fileText = fileElement ? fileElement.textContent.trim() : '';
const error = messageText + (fileText ? ' File:' + fileText : '');
window.parent.postMessage({
type: 'horizons-vite-error',
error,
}, '*');
}
}
`;
const configHorizonsRuntimeErrorHandler = `
window.onerror = (message, source, lineno, colno, errorObj) => {
const errorDetails = errorObj ? JSON.stringify({
name: errorObj.name,
message: errorObj.message,
stack: errorObj.stack,
source,
lineno,
colno,
}) : null;
window.parent.postMessage({
type: 'horizons-runtime-error',
message,
error: errorDetails
}, '*');
};
`;
const configHorizonsConsoleErrroHandler = `
const originalConsoleError = console.error;
console.error = function(...args) {
originalConsoleError.apply(console, args);
let errorString = '';
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg instanceof Error) {
errorString = arg.stack || \`\${arg.name}: \${arg.message}\`;
break;
}
}
if (!errorString) {
errorString = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : String(arg)).join(' ');
}
window.parent.postMessage({
type: 'horizons-console-error',
error: errorString
}, '*');
};
`;
const configWindowFetchMonkeyPatch = `
const originalFetch = window.fetch;
window.fetch = function(...args) {
const url = args[0] instanceof Request ? args[0].url : args[0];
// Skip WebSocket URLs
if (url.startsWith('ws:') || url.startsWith('wss:')) {
return originalFetch.apply(this, args);
}
return originalFetch.apply(this, args)
.then(async response => {
const contentType = response.headers.get('Content-Type') || '';
// Exclude HTML document responses
const isDocumentResponse =
contentType.includes('text/html') ||
contentType.includes('application/xhtml+xml');
if (!response.ok && !isDocumentResponse) {
const responseClone = response.clone();
const errorFromRes = await responseClone.text();
const requestUrl = response.url;
console.error(\`Fetch error from \${requestUrl}: \${errorFromRes}\`);
}
return response;
})
.catch(error => {
if (!url.match(/\.html?$/i)) {
console.error(error);
}
throw error;
});
};
`;
const configNavigationHandler = `
if (window.navigation && window.self !== window.top) {
window.navigation.addEventListener('navigate', (event) => {
const url = event.destination.url;
try {
const destinationUrl = new URL(url);
const destinationOrigin = destinationUrl.origin;
const currentOrigin = window.location.origin;
if (destinationOrigin === currentOrigin) {
return;
}
} catch (error) {
return;
}
window.parent.postMessage({
type: 'horizons-navigation-error',
url,
}, '*');
});
}
`;
const addTransformIndexHtml = {
name: 'add-transform-index-html',
transformIndexHtml(html) {
const tags = [
{
tag: 'script',
attrs: { type: 'module' },
children: configHorizonsRuntimeErrorHandler,
injectTo: 'head',
},
{
tag: 'script',
attrs: { type: 'module' },
children: configHorizonsViteErrorHandler,
injectTo: 'head',
},
{
tag: 'script',
attrs: {type: 'module'},
children: configHorizonsConsoleErrroHandler,
injectTo: 'head',
},
{
tag: 'script',
attrs: { type: 'module' },
children: configWindowFetchMonkeyPatch,
injectTo: 'head',
},
{
tag: 'script',
attrs: { type: 'module' },
children: configNavigationHandler,
injectTo: 'head',
},
];
if (!isDev && process.env.TEMPLATE_BANNER_SCRIPT_URL && process.env.TEMPLATE_REDIRECT_URL) {
tags.push(
{
tag: 'script',
attrs: {
src: process.env.TEMPLATE_BANNER_SCRIPT_URL,
'template-redirect-url': process.env.TEMPLATE_REDIRECT_URL,
},
injectTo: 'head',
}
);
}
return {
html,
tags,
};
},
};
console.warn = () => {};
const logger = createLogger()
const loggerError = logger.error
logger.error = (msg, options) => {
if (options?.error?.toString().includes('CssSyntaxError: [postcss]')) {
return;
}
loggerError(msg, options);
}
export default defineConfig({
customLogger: logger,
plugins: [
...(isDev ? [inlineEditPlugin(), editModeDevPlugin(), iframeRouteRestorationPlugin(), selectionModePlugin()] : []),
react(),
addTransformIndexHtml
],
server: {
cors: true,
headers: {
'Cross-Origin-Embedder-Policy': 'credentialless',
},
allowedHosts: true,
},
resolve: {
extensions: ['.jsx', '.js', '.tsx', '.ts', '.json', ],
alias: {
'@': path.resolve(__dirname, './src'),
},
},
build: {
rollupOptions: {
external: [
'@babel/parser',
'@babel/traverse',
'@babel/generator',
'@babel/types'
]
}
}
});