@metricinsights/pp-dev 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -41
- package/bin/pp-dev.js +4 -10
- package/dist/cjs/cli.js +589 -0
- package/dist/cjs/cli.js.map +1 -0
- package/dist/cjs/helpers.js +29 -0
- package/dist/cjs/helpers.js.map +1 -0
- package/dist/cjs/index-ab672d81.js +292 -0
- package/dist/cjs/index-ab672d81.js.map +1 -0
- package/dist/cjs/index.js +27 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +113 -0
- package/dist/cjs/plugin-24dd0a43.js +878 -0
- package/dist/cjs/plugin-24dd0a43.js.map +1 -0
- package/dist/cjs/plugin.js +20 -0
- package/dist/cjs/plugin.js.map +1 -0
- package/dist/{cli.js → esm/cli.js} +210 -23
- package/dist/esm/cli.js.map +1 -0
- package/dist/esm/helpers.js +25 -0
- package/dist/esm/helpers.js.map +1 -0
- package/dist/{index.js → esm/index-d2c8ad2e.js} +98 -12
- package/dist/esm/index-d2c8ad2e.js.map +1 -0
- package/dist/esm/index.js +19 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +113 -0
- package/dist/esm/plugin-ecb1c54a.js +843 -0
- package/dist/esm/plugin-ecb1c54a.js.map +1 -0
- package/dist/esm/plugin.js +14 -0
- package/dist/esm/plugin.js.map +1 -0
- package/dist/types/cli.d.ts +3 -0
- package/dist/types/helpers.d.ts +24 -0
- package/dist/types/index.d.ts +18 -0
- package/dist/{plugin.d.ts → types/plugin.d.ts} +4 -2
- package/package.json +23 -8
- package/pp-dev.d.ts +1 -1
- package/dist/api/assets.d.ts +0 -15
- package/dist/api/assets.js +0 -58
- package/dist/api/assets.js.map +0 -1
- package/dist/api/base.d.ts +0 -5
- package/dist/api/base.js +0 -7
- package/dist/api/base.js.map +0 -1
- package/dist/api/constants.d.ts +0 -1
- package/dist/api/constants.js +0 -2
- package/dist/api/constants.js.map +0 -1
- package/dist/api/index.d.ts +0 -2
- package/dist/api/index.js +0 -3
- package/dist/api/index.js.map +0 -1
- package/dist/api/page.d.ts +0 -16
- package/dist/api/page.js +0 -43
- package/dist/api/page.js.map +0 -1
- package/dist/banner/header.d.ts +0 -2
- package/dist/banner/header.js +0 -10
- package/dist/banner/header.js.map +0 -1
- package/dist/cli.d.ts +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/client/rollup.config.d.ts +0 -2
- package/dist/constants.d.ts +0 -6
- package/dist/constants.js +0 -18
- package/dist/constants.js.map +0 -1
- package/dist/index.d.ts +0 -13
- package/dist/index.js.map +0 -1
- package/dist/lib/client.service.d.ts +0 -16
- package/dist/lib/client.service.js +0 -59
- package/dist/lib/client.service.js.map +0 -1
- package/dist/lib/dist.service.d.ts +0 -31
- package/dist/lib/dist.service.js +0 -148
- package/dist/lib/dist.service.js.map +0 -1
- package/dist/lib/helpers/content-encoding.helper.d.ts +0 -3
- package/dist/lib/helpers/content-encoding.helper.js +0 -26
- package/dist/lib/helpers/content-encoding.helper.js.map +0 -1
- package/dist/lib/helpers/server.d.ts +0 -14
- package/dist/lib/helpers/server.js +0 -40
- package/dist/lib/helpers/server.js.map +0 -1
- package/dist/lib/helpers/url.helper.d.ts +0 -7
- package/dist/lib/helpers/url.helper.js +0 -40
- package/dist/lib/helpers/url.helper.js.map +0 -1
- package/dist/lib/load-pp-data.middleware.d.ts +0 -5
- package/dist/lib/load-pp-data.middleware.js +0 -28
- package/dist/lib/load-pp-data.middleware.js.map +0 -1
- package/dist/lib/pp-redirect.middleware.d.ts +0 -3
- package/dist/lib/pp-redirect.middleware.js +0 -21
- package/dist/lib/pp-redirect.middleware.js.map +0 -1
- package/dist/lib/pp.middleware.d.ts +0 -27
- package/dist/lib/pp.middleware.js +0 -155
- package/dist/lib/pp.middleware.js.map +0 -1
- package/dist/lib/proxy-cache.middleware.d.ts +0 -18
- package/dist/lib/proxy-cache.middleware.js +0 -51
- package/dist/lib/proxy-cache.middleware.js.map +0 -1
- package/dist/lib/proxy-pass.middleware.d.ts +0 -11
- package/dist/lib/proxy-pass.middleware.js +0 -90
- package/dist/lib/proxy-pass.middleware.js.map +0 -1
- package/dist/lib/rewrite-response.middleware.d.ts +0 -6
- package/dist/lib/rewrite-response.middleware.js +0 -23
- package/dist/lib/rewrite-response.middleware.js.map +0 -1
- package/dist/plugin.js +0 -76
- package/dist/plugin.js.map +0 -1
- package/dist/plugins/client-injection-plugin.d.ts +0 -12
- package/dist/plugins/client-injection-plugin.js +0 -57
- package/dist/plugins/client-injection-plugin.js.map +0 -1
- package/dist/shortcuts.d.ts +0 -12
- package/dist/shortcuts.js +0 -93
- package/dist/shortcuts.js.map +0 -1
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
|
|
2
|
+
import { fileURLToPath, URL as URL$1 } from 'url';
|
|
3
|
+
import axios from 'axios';
|
|
4
|
+
import { JSDOM } from 'jsdom';
|
|
5
|
+
import * as memoryCache from 'memory-cache';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { promises } from 'fs';
|
|
8
|
+
import * as crypto from 'crypto';
|
|
9
|
+
import * as process from 'process';
|
|
10
|
+
import * as child_process from 'child_process';
|
|
11
|
+
import * as console from 'console';
|
|
12
|
+
import { deflateSync, brotliDecompressSync, unzipSync, inflateSync, brotliCompressSync, gzipSync } from 'zlib';
|
|
13
|
+
|
|
14
|
+
const urlReplacer = (originalHost, destinationHost, content) => {
|
|
15
|
+
const urlReplaceRegExp = new RegExp(`(!!)?(https?(:(\\\\)?/(\\\\)?/)${originalHost})`, 'gi');
|
|
16
|
+
return content.replace(urlReplaceRegExp, (substring, ...args) => {
|
|
17
|
+
if (substring.startsWith('!!')) {
|
|
18
|
+
return args[1];
|
|
19
|
+
}
|
|
20
|
+
return `http${args[2]}${destinationHost}`;
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
const urlPathReplacer = (urlPath, destinationPath, content) => {
|
|
24
|
+
const urlReplaceRegExp = new RegExp(`${urlPath.replace(/\\*\//gi, '\\\\/')}`, 'gi');
|
|
25
|
+
return content.replace(urlReplaceRegExp, destinationPath);
|
|
26
|
+
};
|
|
27
|
+
const redirect = (res, url, statusCode) => {
|
|
28
|
+
res.setHeader('location', url);
|
|
29
|
+
res.statusCode = statusCode || 302;
|
|
30
|
+
res.end();
|
|
31
|
+
};
|
|
32
|
+
function cutUrlParams(url) {
|
|
33
|
+
const urlParts = url.split('?');
|
|
34
|
+
return urlParts[0];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const hostOriginRegExp = /^(https?:\/\/)([^/]+)(\/.*)?$/i;
|
|
38
|
+
const PROXY_HEADER = 'X-PP-Proxy';
|
|
39
|
+
function initProxy(opts) {
|
|
40
|
+
const { rewritePath = /^\/(?!pt).*/i, baseURL = '', devServer } = opts;
|
|
41
|
+
if (!baseURL) {
|
|
42
|
+
throw new Error('Base url is required');
|
|
43
|
+
}
|
|
44
|
+
const host = baseURL.replace(hostOriginRegExp, '$2');
|
|
45
|
+
const origin = baseURL.replace(hostOriginRegExp, '$1$2');
|
|
46
|
+
const fileType = import('file-type');
|
|
47
|
+
return createProxyMiddleware((pathname) => {
|
|
48
|
+
if ((opts.proxyIgnore || []).some((value) => {
|
|
49
|
+
if (typeof value === 'string') {
|
|
50
|
+
return pathname.startsWith(value);
|
|
51
|
+
}
|
|
52
|
+
else if (typeof value.test === 'function') {
|
|
53
|
+
return value.test(pathname);
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
})) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
if (typeof rewritePath === 'string') {
|
|
60
|
+
return pathname.startsWith(rewritePath);
|
|
61
|
+
}
|
|
62
|
+
else if (Array.isArray(rewritePath)) {
|
|
63
|
+
return rewritePath.some((rP) => pathname.startsWith(rP));
|
|
64
|
+
}
|
|
65
|
+
else if (typeof rewritePath.test === 'function') {
|
|
66
|
+
return rewritePath.test(pathname);
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}, {
|
|
70
|
+
/**
|
|
71
|
+
* IMPORTANT: avoid res.end being called automatically
|
|
72
|
+
**/
|
|
73
|
+
selfHandleResponse: true,
|
|
74
|
+
target: baseURL,
|
|
75
|
+
changeOrigin: true,
|
|
76
|
+
autoRewrite: true,
|
|
77
|
+
logLevel: 'silent',
|
|
78
|
+
headers: {
|
|
79
|
+
host,
|
|
80
|
+
origin,
|
|
81
|
+
},
|
|
82
|
+
onProxyReq(proxyReq, req, res) {
|
|
83
|
+
const host = req.headers.host;
|
|
84
|
+
const referer = proxyReq.getHeader('referer');
|
|
85
|
+
devServer.config.logger.info(`Proxies request: ${req.method} ${req.url} -> ${proxyReq.method} ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`);
|
|
86
|
+
if (host && referer && typeof referer === 'string') {
|
|
87
|
+
proxyReq.setHeader('referer', referer.replace(new RegExp(`https?://${host}`), baseURL));
|
|
88
|
+
}
|
|
89
|
+
req.socket.on('close', () => {
|
|
90
|
+
setTimeout(() => {
|
|
91
|
+
if (!proxyReq.destroyed) {
|
|
92
|
+
proxyReq.destroy();
|
|
93
|
+
}
|
|
94
|
+
}, 200);
|
|
95
|
+
});
|
|
96
|
+
return proxyReq;
|
|
97
|
+
},
|
|
98
|
+
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
|
|
99
|
+
res.setHeader(PROXY_HEADER, 1);
|
|
100
|
+
const type = await (await fileType).fileTypeFromBuffer(responseBuffer);
|
|
101
|
+
if (type) {
|
|
102
|
+
return responseBuffer;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
let response = responseBuffer.toString('utf8'); // convert buffer to string
|
|
106
|
+
try {
|
|
107
|
+
const reqUrl = new URL(req.url ?? '', `http://${host}`);
|
|
108
|
+
if (reqUrl.searchParams && reqUrl.searchParams.has('proxyRedirect')) {
|
|
109
|
+
response +=
|
|
110
|
+
'<script>' +
|
|
111
|
+
'const params = new URLSearchParams(window.location.search);' +
|
|
112
|
+
"if (params.has('proxyRedirect')) {" +
|
|
113
|
+
" setTimeout(() => { window.location = params.get('proxyRedirect'); }, 50);" +
|
|
114
|
+
'}' +
|
|
115
|
+
'</script>';
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
//
|
|
120
|
+
}
|
|
121
|
+
const reqHost = req.headers.host ?? '';
|
|
122
|
+
// manipulate response and return the result
|
|
123
|
+
return urlPathReplacer('/auth/saml/login', '/login', urlReplacer(host, reqHost, response));
|
|
124
|
+
}
|
|
125
|
+
}),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
class BaseAPI {
|
|
130
|
+
axios;
|
|
131
|
+
constructor(axios) {
|
|
132
|
+
this.axios = axios;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
class AssetsAPI extends BaseAPI {
|
|
137
|
+
// Import for CJS and ESM
|
|
138
|
+
formdataModulePromise = import('formdata-node');
|
|
139
|
+
constructor(axios) {
|
|
140
|
+
super(axios);
|
|
141
|
+
}
|
|
142
|
+
async downloadPageAssets(portalPageId, headers) {
|
|
143
|
+
return this.axios
|
|
144
|
+
.get(`/admin/page/downloadassets/id/${portalPageId}`, {
|
|
145
|
+
withCredentials: true,
|
|
146
|
+
headers: Object.assign({}, headers, { accept: '*/*' }),
|
|
147
|
+
responseType: 'arraybuffer',
|
|
148
|
+
})
|
|
149
|
+
.then((res) => res.data);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Upload page assets.
|
|
153
|
+
* @param portalPageId
|
|
154
|
+
* @param file - Zip file with assets
|
|
155
|
+
* @param headers
|
|
156
|
+
*/
|
|
157
|
+
async uploadPageAssets(portalPageId, file, headers) {
|
|
158
|
+
const formData = new (await this.formdataModulePromise).FormData();
|
|
159
|
+
const assetFile = new File([file.buffer], 'file.zip', { type: 'application/zip' });
|
|
160
|
+
formData.append('file', assetFile);
|
|
161
|
+
const url = `/admin/page/uploadassets/id/${portalPageId}`;
|
|
162
|
+
return this.axios
|
|
163
|
+
.post(`/admin/page/uploadassets/id/${portalPageId}`, formData, {
|
|
164
|
+
withCredentials: true,
|
|
165
|
+
headers: Object.assign({}, headers, {
|
|
166
|
+
accept: 'application/json',
|
|
167
|
+
'Content-Type': 'multipart/form-data',
|
|
168
|
+
Referer: this.axios.getUri({ url }),
|
|
169
|
+
}),
|
|
170
|
+
})
|
|
171
|
+
.then((res) => res.data);
|
|
172
|
+
}
|
|
173
|
+
async downloadTemplateAssets(templateId, headers) {
|
|
174
|
+
return this.axios
|
|
175
|
+
.get(`/admin/pagetemplate/downloadassets/id/${templateId}`, {
|
|
176
|
+
withCredentials: true,
|
|
177
|
+
headers: Object.assign({}, headers, { accept: '*/*' }),
|
|
178
|
+
responseType: 'arraybuffer',
|
|
179
|
+
})
|
|
180
|
+
.then((res) => res.data);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Upload template assets.
|
|
184
|
+
* @param templateId
|
|
185
|
+
* @param file - Zip file with assets
|
|
186
|
+
* @param headers
|
|
187
|
+
*/
|
|
188
|
+
async uploadTemplateAssets(templateId, file, headers) {
|
|
189
|
+
const formData = new (await this.formdataModulePromise).FormData();
|
|
190
|
+
const assetFile = new (await this.formdataModulePromise).File([file.buffer], 'file.zip', {
|
|
191
|
+
type: 'application/zip',
|
|
192
|
+
});
|
|
193
|
+
formData.append('file', assetFile, 'file.zip');
|
|
194
|
+
const url = `/admin/pagetemplate/uploadassets/id/${templateId}`;
|
|
195
|
+
return this.axios
|
|
196
|
+
.post(url, formData, {
|
|
197
|
+
withCredentials: true,
|
|
198
|
+
headers: Object.assign({}, headers, {
|
|
199
|
+
accept: 'application/json',
|
|
200
|
+
'Content-Type': 'multipart/form-data',
|
|
201
|
+
Referer: this.axios.getUri({ url }),
|
|
202
|
+
}),
|
|
203
|
+
})
|
|
204
|
+
.then((res) => res.data);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
class PageAPI extends BaseAPI {
|
|
209
|
+
async getAll(headers) {
|
|
210
|
+
return (await this.axios.get('/api/page', {
|
|
211
|
+
withCredentials: true,
|
|
212
|
+
headers: Object.assign({}, headers, {
|
|
213
|
+
Accept: 'application/json',
|
|
214
|
+
'Content-Type': 'application/json',
|
|
215
|
+
'Cache-Control': 'no-cache',
|
|
216
|
+
Pragma: 'no-cache',
|
|
217
|
+
Expires: '0',
|
|
218
|
+
}),
|
|
219
|
+
})).data.pages;
|
|
220
|
+
}
|
|
221
|
+
async get(id, headers) {
|
|
222
|
+
return (await this.axios.get(`/api/page/id/${id}`, {
|
|
223
|
+
withCredentials: true,
|
|
224
|
+
headers: Object.assign({}, headers, {
|
|
225
|
+
accept: 'application/json',
|
|
226
|
+
'content-type': 'application/json',
|
|
227
|
+
}),
|
|
228
|
+
})).data.page;
|
|
229
|
+
}
|
|
230
|
+
async getPageContent(internalPageName, headers) {
|
|
231
|
+
return (await this.axios.get(`/p/${internalPageName}`, {
|
|
232
|
+
withCredentials: true,
|
|
233
|
+
headers: Object.assign({}, headers, {
|
|
234
|
+
accept: 'text/html',
|
|
235
|
+
'content-type': 'application/json',
|
|
236
|
+
}),
|
|
237
|
+
})).data;
|
|
238
|
+
}
|
|
239
|
+
async create(page, headers) {
|
|
240
|
+
return (await this.axios.post('/api/page', page, {
|
|
241
|
+
withCredentials: true,
|
|
242
|
+
headers: Object.assign({}, headers, {
|
|
243
|
+
accept: 'application/json',
|
|
244
|
+
'content-type': 'application/json',
|
|
245
|
+
}),
|
|
246
|
+
})).data.page;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
class MiAPI {
|
|
251
|
+
#headers;
|
|
252
|
+
#axios;
|
|
253
|
+
#pageTemplate = null;
|
|
254
|
+
#pageTitle;
|
|
255
|
+
#pageVars;
|
|
256
|
+
#templateLoaded;
|
|
257
|
+
#templateLoadedResolve;
|
|
258
|
+
portalPageId;
|
|
259
|
+
templateLess;
|
|
260
|
+
assetsApi;
|
|
261
|
+
pageApi;
|
|
262
|
+
constructor(baseURL, opts) {
|
|
263
|
+
const { headers = {}, portalPageId, templateLess = true } = opts || {};
|
|
264
|
+
this.#headers = headers;
|
|
265
|
+
this.#pageVars = [];
|
|
266
|
+
this.#pageTitle = '';
|
|
267
|
+
this.#templateLoaded = new Promise((resolve) => {
|
|
268
|
+
this.#templateLoadedResolve = resolve;
|
|
269
|
+
});
|
|
270
|
+
this.#axios = axios.create({ baseURL, headers });
|
|
271
|
+
this.portalPageId = portalPageId;
|
|
272
|
+
this.templateLess = templateLess;
|
|
273
|
+
this.assetsApi = new AssetsAPI(this.#axios);
|
|
274
|
+
this.pageApi = new PageAPI(this.#axios);
|
|
275
|
+
}
|
|
276
|
+
async isTemplateLoaded() {
|
|
277
|
+
return this.#templateLoaded;
|
|
278
|
+
}
|
|
279
|
+
#clearHeaders(headers) {
|
|
280
|
+
const obj = Object.assign({}, headers, { host: undefined });
|
|
281
|
+
Object.keys(obj).forEach((key) => obj[key] === undefined && delete obj[key]);
|
|
282
|
+
this.#headers = obj;
|
|
283
|
+
return obj;
|
|
284
|
+
}
|
|
285
|
+
updateHeaders(headers) {
|
|
286
|
+
this.#clearHeaders(headers);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Get page template
|
|
290
|
+
* @param headers
|
|
291
|
+
*/
|
|
292
|
+
async getPageTemplate(headers) {
|
|
293
|
+
if (this.#pageTemplate) {
|
|
294
|
+
return Promise.resolve(this.#pageTemplate);
|
|
295
|
+
}
|
|
296
|
+
if (typeof this.templateLess === 'undefined') {
|
|
297
|
+
this.templateLess = false;
|
|
298
|
+
}
|
|
299
|
+
const pageList = await this.pageApi.getAll(this.#clearHeaders(headers));
|
|
300
|
+
let page = pageList.find((p) => p.name === '[DEV PAGE. DO NOT DELETE]');
|
|
301
|
+
if (!page) {
|
|
302
|
+
page = await this.pageApi.create({
|
|
303
|
+
enabled: 'Y',
|
|
304
|
+
name: '[DEV PAGE. DO NOT DELETE]',
|
|
305
|
+
internal_name: 'dev-page-template',
|
|
306
|
+
visible_in_homepage: 'Y',
|
|
307
|
+
}, this.#clearHeaders(headers));
|
|
308
|
+
}
|
|
309
|
+
return await this.pageApi
|
|
310
|
+
.getPageContent(page.internal_name, this.#clearHeaders(headers))
|
|
311
|
+
.then((response) => {
|
|
312
|
+
this.#pageTemplate = response;
|
|
313
|
+
return response;
|
|
314
|
+
})
|
|
315
|
+
.finally(() => {
|
|
316
|
+
this.#templateLoadedResolve(true);
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Get page template variables
|
|
321
|
+
*
|
|
322
|
+
* @param pageId
|
|
323
|
+
* @param headers
|
|
324
|
+
*/
|
|
325
|
+
async getPageVariables(pageId, headers) {
|
|
326
|
+
this.#pageTemplate = await this.getPageTemplate(headers);
|
|
327
|
+
if (!this.portalPageId) {
|
|
328
|
+
this.portalPageId = pageId;
|
|
329
|
+
this.templateLess = false;
|
|
330
|
+
}
|
|
331
|
+
return await this.pageApi
|
|
332
|
+
.get(pageId, this.#clearHeaders(headers))
|
|
333
|
+
.then((response) => {
|
|
334
|
+
const { tags = '[]', name, template } = response;
|
|
335
|
+
if (template && tags) {
|
|
336
|
+
const parsed = JSON.parse(tags);
|
|
337
|
+
this.#pageVars = parsed;
|
|
338
|
+
this.#pageTitle = name;
|
|
339
|
+
return parsed;
|
|
340
|
+
}
|
|
341
|
+
this.#pageVars = [];
|
|
342
|
+
this.#pageTitle = name;
|
|
343
|
+
return [];
|
|
344
|
+
})
|
|
345
|
+
.catch((reason) => {
|
|
346
|
+
if (reason.response?.status === 404) {
|
|
347
|
+
throw new Error(`Portal Page with id "${pageId}" not found on instance ${this.#axios.getUri()}`);
|
|
348
|
+
}
|
|
349
|
+
throw reason;
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Build page with variables
|
|
354
|
+
*
|
|
355
|
+
* @param content
|
|
356
|
+
* @param miHudLess
|
|
357
|
+
*/
|
|
358
|
+
buildPage(content, miHudLess = false) {
|
|
359
|
+
let result = typeof content === 'string' ? content : content.toString('utf-8');
|
|
360
|
+
for (const v of this.#pageVars) {
|
|
361
|
+
result = result.replace(new RegExp(`\\[${v.name}\\]`, 'g'), v.value);
|
|
362
|
+
}
|
|
363
|
+
const dom = new JSDOM(miHudLess ? result : this.#pageTemplate);
|
|
364
|
+
const placeholderText = '%%PLACEHOLDER%%';
|
|
365
|
+
if (!miHudLess) {
|
|
366
|
+
const placeholder = dom.window.document.createElement('div');
|
|
367
|
+
placeholder.innerHTML = placeholderText;
|
|
368
|
+
const container = dom.window.document.querySelector('.main-side');
|
|
369
|
+
if (container) {
|
|
370
|
+
const scripts = container.querySelectorAll('script');
|
|
371
|
+
if (scripts.length) {
|
|
372
|
+
container.insertBefore(placeholder, scripts.item(scripts.length - 1));
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
container.append(placeholder);
|
|
376
|
+
}
|
|
377
|
+
const head = dom.window.document.querySelector('head');
|
|
378
|
+
const title = head.querySelector('title');
|
|
379
|
+
if (title) {
|
|
380
|
+
title.text = this.#pageTitle;
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
head.innerHTML += `<title>${this.#pageTitle}</title>`;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const serializedDom = dom.serialize();
|
|
388
|
+
return serializedDom.replace(new RegExp(`<div>\\s*${placeholderText}\\s*<\\/div>`, 'i'), result);
|
|
389
|
+
}
|
|
390
|
+
async getAssets() {
|
|
391
|
+
if (this.portalPageId) {
|
|
392
|
+
if (this.templateLess) {
|
|
393
|
+
return await this.assetsApi.downloadPageAssets(this.portalPageId, this.#headers);
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
const pageInfo = await this.pageApi.get(this.portalPageId, this.#headers);
|
|
397
|
+
if (pageInfo.template) {
|
|
398
|
+
return await this.assetsApi.downloadTemplateAssets(pageInfo.template, this.#headers);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
async updateAssets(assets) {
|
|
404
|
+
if (this.portalPageId) {
|
|
405
|
+
if (this.templateLess) {
|
|
406
|
+
return await this.assetsApi.uploadPageAssets(this.portalPageId, assets, this.#headers);
|
|
407
|
+
}
|
|
408
|
+
else {
|
|
409
|
+
const pageInfo = await this.pageApi.get(this.portalPageId, this.#headers);
|
|
410
|
+
if (pageInfo.template) {
|
|
411
|
+
return await this.assetsApi.uploadTemplateAssets(pageInfo.template, assets, this.#headers);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
class ClientService {
|
|
419
|
+
server;
|
|
420
|
+
opts;
|
|
421
|
+
eventMap;
|
|
422
|
+
constructor(server, opts) {
|
|
423
|
+
this.server = server;
|
|
424
|
+
this.opts = opts || {};
|
|
425
|
+
this.eventMap = new Map();
|
|
426
|
+
this.eventMap.set('info-data:request', this.onInfoDataRequest.bind(this));
|
|
427
|
+
this.eventMap.set('template:sync', this.onTemplateSync.bind(this));
|
|
428
|
+
this.init();
|
|
429
|
+
}
|
|
430
|
+
init() {
|
|
431
|
+
const { ws } = this.server;
|
|
432
|
+
for (const [event, handler] of this.eventMap) {
|
|
433
|
+
ws.on(event, handler);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
onInfoDataRequest() {
|
|
437
|
+
this.server.ws.send({
|
|
438
|
+
type: 'custom',
|
|
439
|
+
event: 'info-data:response',
|
|
440
|
+
data: {},
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
async onTemplateSync() {
|
|
444
|
+
if (this.opts.distService && this.opts.miAPI) {
|
|
445
|
+
const { distService, miAPI } = this.opts;
|
|
446
|
+
const currentAssets = await miAPI?.getAssets();
|
|
447
|
+
const newAssets = currentAssets
|
|
448
|
+
? await distService?.saveBackupAndBuild(currentAssets)
|
|
449
|
+
: await distService?.buildNewAssets();
|
|
450
|
+
if (newAssets) {
|
|
451
|
+
const updateResult = await miAPI?.updateAssets(newAssets);
|
|
452
|
+
if (updateResult?.status === 'OK') {
|
|
453
|
+
const backupMeta = distService?.getBackupMeta();
|
|
454
|
+
const { lastBackupName: backupFilename, lastBackupHash: currentHash, lastBackupDate: backupDate, } = backupMeta || { lastBackupName: '', lastBackupHash: '', lastBackupDate: new Date().toISOString() };
|
|
455
|
+
this.server.ws.send('template:sync:response', {
|
|
456
|
+
syncedAt: new Date(backupDate),
|
|
457
|
+
currentHash,
|
|
458
|
+
backupFilename,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
else {
|
|
462
|
+
this.server.ws.send('template:sync:response', { error: 'Failed to update assets' });
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
else {
|
|
466
|
+
this.server.ws.send('template:sync:response', { error: 'Failed to build new assets' });
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
this.server.ws.send('template:sync:response', { error: 'Dist service or MiAPI is not defined' });
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const cache = new memoryCache.Cache();
|
|
478
|
+
const testCacheUrlRegExp = /\.[a-z0-9]+$/i;
|
|
479
|
+
function initProxyCache(opts) {
|
|
480
|
+
const { devServer, ttl = 10 * 60 * 1000 } = opts;
|
|
481
|
+
devServer.cache = cache;
|
|
482
|
+
return (req, res, next) => {
|
|
483
|
+
const url = req.originalUrl || req.url || '';
|
|
484
|
+
if (testCacheUrlRegExp.test(url.split('?')[0] || '')) {
|
|
485
|
+
const cacheItem = cache.get(url);
|
|
486
|
+
if (cacheItem && devServer.config) {
|
|
487
|
+
devServer.config.logger.info(`Proxies request: ${req.method} ${url} -> Cache ${url}`);
|
|
488
|
+
for (const [header, value] of Object.entries(cacheItem.headers)) {
|
|
489
|
+
res.setHeader(header, value);
|
|
490
|
+
}
|
|
491
|
+
res.write(cacheItem.content);
|
|
492
|
+
res.end();
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
const end = res.end;
|
|
496
|
+
const write = res.write;
|
|
497
|
+
let buffer = Buffer.from('', 'utf8');
|
|
498
|
+
// Rewrite response method and get the content.
|
|
499
|
+
res.write = function (data, encoding, callback) {
|
|
500
|
+
if (!res.hasHeader(PROXY_HEADER)) {
|
|
501
|
+
return write.call(this, data, encoding, callback);
|
|
502
|
+
}
|
|
503
|
+
buffer = Buffer.concat([buffer, data]);
|
|
504
|
+
return true;
|
|
505
|
+
};
|
|
506
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
507
|
+
// @ts-ignore
|
|
508
|
+
res.end = function (chunk, encoding, cb) {
|
|
509
|
+
if (!res.hasHeader(PROXY_HEADER)) {
|
|
510
|
+
return end.call(this, chunk, encoding, cb);
|
|
511
|
+
}
|
|
512
|
+
if (typeof chunk === 'string') {
|
|
513
|
+
buffer = Buffer.concat([buffer, Buffer.from(chunk, encoding)]);
|
|
514
|
+
}
|
|
515
|
+
if (Buffer.isBuffer(chunk)) {
|
|
516
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
517
|
+
}
|
|
518
|
+
if (res.hasHeader(PROXY_HEADER)) {
|
|
519
|
+
devServer.config.logger?.info(`[Cached] ${url}`);
|
|
520
|
+
cache.put(url, { headers: res.getHeaders(), content: buffer }, ttl);
|
|
521
|
+
}
|
|
522
|
+
end.call(this, buffer, encoding, cb);
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
next();
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const TEMPLATE_PART_PAGE_NAME = 'pageName';
|
|
530
|
+
const TEMPLATE_PART_DATE = 'date';
|
|
531
|
+
const DIRNAME = path.dirname((typeof __filename !== 'undefined' && __filename) || fileURLToPath(import.meta.url));
|
|
532
|
+
const pluginPath = path.resolve(DIRNAME, '..', '..');
|
|
533
|
+
const node_modules_path = path.resolve(pluginPath, '..', '..');
|
|
534
|
+
const metaDirName = '.pp-dev-meta';
|
|
535
|
+
const metaDirPath = path.resolve(node_modules_path, metaDirName);
|
|
536
|
+
const metaFilePath = path.resolve(metaDirPath, 'sync-service.meta.json');
|
|
537
|
+
class DistService {
|
|
538
|
+
backupFolder;
|
|
539
|
+
backupNameTemplate;
|
|
540
|
+
dateFormat;
|
|
541
|
+
pageName;
|
|
542
|
+
currentMeta = null;
|
|
543
|
+
constructor(pageName, syncOptions) {
|
|
544
|
+
const { backupFolder = path.resolve(process.cwd(), 'backups'), backupNameTemplate = `{${TEMPLATE_PART_PAGE_NAME}}-{${TEMPLATE_PART_DATE}}.zip`, dateFormat = (date) => date.toISOString().replace(/:/g, '-').replace(/\..*$/, ''), } = syncOptions || {};
|
|
545
|
+
this.backupFolder = backupFolder;
|
|
546
|
+
this.backupNameTemplate = backupNameTemplate;
|
|
547
|
+
this.dateFormat = dateFormat;
|
|
548
|
+
this.pageName = pageName;
|
|
549
|
+
this.syncMeta();
|
|
550
|
+
}
|
|
551
|
+
async checkMeta() {
|
|
552
|
+
try {
|
|
553
|
+
await promises.stat(metaDirPath);
|
|
554
|
+
}
|
|
555
|
+
catch {
|
|
556
|
+
await promises.mkdir(metaDirPath);
|
|
557
|
+
}
|
|
558
|
+
try {
|
|
559
|
+
await promises.stat(this.backupFolder);
|
|
560
|
+
}
|
|
561
|
+
catch {
|
|
562
|
+
await promises.mkdir(this.backupFolder);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
async readMetaFile() {
|
|
566
|
+
await this.checkMeta();
|
|
567
|
+
return await promises
|
|
568
|
+
.readFile(metaFilePath, {
|
|
569
|
+
encoding: 'utf-8',
|
|
570
|
+
})
|
|
571
|
+
.catch(() => '{}');
|
|
572
|
+
}
|
|
573
|
+
async writeMetaFile(meta) {
|
|
574
|
+
await this.checkMeta();
|
|
575
|
+
return await promises.writeFile(metaFilePath, JSON.stringify(meta, null, 2), {
|
|
576
|
+
encoding: 'utf-8',
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
async syncMeta() {
|
|
580
|
+
if (!this.currentMeta) {
|
|
581
|
+
this.currentMeta = JSON.parse(await this.readMetaFile());
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
await this.writeMetaFile(this.currentMeta);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
async getLatestSavedBackup() {
|
|
588
|
+
const { lastBackupName } = this.currentMeta;
|
|
589
|
+
if (!lastBackupName) {
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
const backupPath = path.resolve(this.backupFolder, lastBackupName);
|
|
593
|
+
try {
|
|
594
|
+
await promises.stat(backupPath);
|
|
595
|
+
return backupPath;
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
backupName(pageName, date = new Date()) {
|
|
602
|
+
return this.backupNameTemplate
|
|
603
|
+
.replace(`{${TEMPLATE_PART_PAGE_NAME}}`, pageName)
|
|
604
|
+
.replace(`{${TEMPLATE_PART_DATE}}`, this.dateFormat(date));
|
|
605
|
+
}
|
|
606
|
+
getBackupMeta() {
|
|
607
|
+
return this.currentMeta;
|
|
608
|
+
}
|
|
609
|
+
async saveBackup(backupFile) {
|
|
610
|
+
const backupFileHash = crypto.createHash('md5').update(backupFile).digest('hex');
|
|
611
|
+
const lastSavedBackup = await this.getLatestSavedBackup();
|
|
612
|
+
if (lastSavedBackup) {
|
|
613
|
+
const { lastBackupHash } = this.currentMeta;
|
|
614
|
+
if (lastBackupHash === backupFileHash) {
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const backupDate = new Date();
|
|
619
|
+
const filename = this.backupName(this.pageName, backupDate);
|
|
620
|
+
this.currentMeta.lastBackupName = filename;
|
|
621
|
+
this.currentMeta.lastBackupHash = backupFileHash;
|
|
622
|
+
this.currentMeta.lastBackupDate = backupDate.toISOString();
|
|
623
|
+
await this.syncMeta();
|
|
624
|
+
return await promises.writeFile(path.resolve(this.backupFolder, filename), backupFile);
|
|
625
|
+
}
|
|
626
|
+
async buildNewAssets() {
|
|
627
|
+
const buildCommand = new Promise(function (resolve, reject) {
|
|
628
|
+
let data = '';
|
|
629
|
+
// Colorized log output with message about build start
|
|
630
|
+
console.log('\x1b[36m%s\x1b[0m', '[DistService] Build started');
|
|
631
|
+
const proc = child_process.spawn('node', [path.resolve(pluginPath, './bin/pp-dev.js'), 'build'], {
|
|
632
|
+
cwd: process.cwd(),
|
|
633
|
+
env: process.env,
|
|
634
|
+
stdio: 'inherit',
|
|
635
|
+
});
|
|
636
|
+
proc.on('message', (msg) => {
|
|
637
|
+
data += msg;
|
|
638
|
+
});
|
|
639
|
+
proc.on('close', (code) => {
|
|
640
|
+
if (code !== 0) {
|
|
641
|
+
reject(new Error(`build command exited with code ${code}`));
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
resolve(data);
|
|
645
|
+
});
|
|
646
|
+
proc.on('error', (err) => {
|
|
647
|
+
reject(err);
|
|
648
|
+
});
|
|
649
|
+
});
|
|
650
|
+
try {
|
|
651
|
+
await buildCommand.finally(() => {
|
|
652
|
+
// Colorized log output with message about build end
|
|
653
|
+
console.log('\x1b[36m%s\x1b[0m', '[DistService] Build finished');
|
|
654
|
+
});
|
|
655
|
+
const assetFile = path.resolve(process.cwd(), `./dist-zip/${this.pageName}.zip`);
|
|
656
|
+
if (!(await promises.stat(assetFile))) {
|
|
657
|
+
throw new Error(`File ${assetFile} not found`);
|
|
658
|
+
}
|
|
659
|
+
return await promises.readFile(assetFile);
|
|
660
|
+
}
|
|
661
|
+
catch (e) {
|
|
662
|
+
console.log(e);
|
|
663
|
+
throw e;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
async saveBackupAndBuild(backupFile) {
|
|
667
|
+
await this.saveBackup(backupFile);
|
|
668
|
+
return await this.buildNewAssets();
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function decodeContent(content, contentEncoding) {
|
|
673
|
+
switch (contentEncoding) {
|
|
674
|
+
case 'gzip':
|
|
675
|
+
return unzipSync(content);
|
|
676
|
+
case 'br':
|
|
677
|
+
return brotliDecompressSync(content);
|
|
678
|
+
case 'deflate':
|
|
679
|
+
return deflateSync(content);
|
|
680
|
+
default:
|
|
681
|
+
return content;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function encodeContent(content, contentEncoding) {
|
|
685
|
+
switch (contentEncoding) {
|
|
686
|
+
case 'gzip':
|
|
687
|
+
return gzipSync(content);
|
|
688
|
+
case 'br':
|
|
689
|
+
return brotliCompressSync(content);
|
|
690
|
+
case 'deflate':
|
|
691
|
+
return inflateSync(content);
|
|
692
|
+
default:
|
|
693
|
+
return content;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Rewrite response middleware
|
|
699
|
+
*
|
|
700
|
+
* @param predicate Check if need to rewrite response data
|
|
701
|
+
* @param rewrite Rewrite response content handler
|
|
702
|
+
*/
|
|
703
|
+
function initRewriteResponse(predicate, rewrite) {
|
|
704
|
+
return (req, res, next) => {
|
|
705
|
+
if (predicate(req.url ?? '', req, res)) {
|
|
706
|
+
const end = res.end;
|
|
707
|
+
const buffers = [];
|
|
708
|
+
res.write = function (body) {
|
|
709
|
+
buffers.push(body);
|
|
710
|
+
return true;
|
|
711
|
+
};
|
|
712
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
713
|
+
// @ts-ignore
|
|
714
|
+
res.end = function (chunk, encoding, cb) {
|
|
715
|
+
if (typeof chunk === 'string') {
|
|
716
|
+
buffers.push(Buffer.from(chunk));
|
|
717
|
+
}
|
|
718
|
+
const contentEncoding = res.getHeader('content-encoding');
|
|
719
|
+
const content = decodeContent(Buffer.from(Buffer.concat(buffers)), contentEncoding);
|
|
720
|
+
end.call(this, encodeContent(rewrite(content, req, res), contentEncoding), encoding, cb);
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
next();
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function initPPRedirect(base, templateName) {
|
|
728
|
+
base = base.startsWith('/') ? base : `/${base}`;
|
|
729
|
+
base = base.endsWith('/') ? base : `${base}/`;
|
|
730
|
+
const baseWithoutTrailingSlash = base.endsWith('/') ? base.slice(0, -1) : base;
|
|
731
|
+
return (req, res, next) => {
|
|
732
|
+
const parsedUrl = new URL$1(req.url ?? '', 'http://localhost');
|
|
733
|
+
const { pathname, search } = parsedUrl;
|
|
734
|
+
const findPaths = ['/', baseWithoutTrailingSlash];
|
|
735
|
+
if (templateName) {
|
|
736
|
+
findPaths.push(`/pt/${templateName}`);
|
|
737
|
+
}
|
|
738
|
+
// Redirect from `/` and `/pt/${templateName}` and `${base}` (without a training slash) to portal page address
|
|
739
|
+
if (findPaths.includes(pathname)) {
|
|
740
|
+
const redirectUrl = `${base}${search}`;
|
|
741
|
+
return redirect(res, redirectUrl, 302);
|
|
742
|
+
}
|
|
743
|
+
next();
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function initLoadPPData(applyUrlRegExp, mi, opts) {
|
|
748
|
+
const { templateLess = false, miHudLess = false, portalPageId } = opts;
|
|
749
|
+
return (req, res, next) => {
|
|
750
|
+
const isNeedTemplateLoad = !(templateLess && miHudLess);
|
|
751
|
+
const isApplyRequest = applyUrlRegExp.test(cutUrlParams(req.url ?? ''));
|
|
752
|
+
if (isNeedTemplateLoad && isApplyRequest) {
|
|
753
|
+
const headers = (req.headers ?? {});
|
|
754
|
+
const loadPageData = !templateLess && typeof portalPageId !== 'undefined'
|
|
755
|
+
? mi.getPageVariables(portalPageId, headers)
|
|
756
|
+
: mi.getPageTemplate(headers);
|
|
757
|
+
loadPageData
|
|
758
|
+
.then(() => {
|
|
759
|
+
next();
|
|
760
|
+
})
|
|
761
|
+
.catch((reason) => {
|
|
762
|
+
if (reason.response) {
|
|
763
|
+
return redirect(res, `/home?proxyRedirect=${encodeURIComponent('/')}`, 302);
|
|
764
|
+
}
|
|
765
|
+
next(reason);
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
else {
|
|
769
|
+
next();
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function vitePPDev(options) {
|
|
775
|
+
const { templateName, templateLess = false, backendBaseURL, miHudLess = false, portalPageId, enableProxyCache = true, proxyCacheTTL = 10 * 60 * 1000, } = options || {};
|
|
776
|
+
// Avoid server caching for index.html file when first loading
|
|
777
|
+
let isFirstRequest = true;
|
|
778
|
+
return {
|
|
779
|
+
name: 'vite-pp-dev',
|
|
780
|
+
apply: 'serve',
|
|
781
|
+
config: (config) => {
|
|
782
|
+
config.clientInjectionPlugin = { backendBaseURL, portalPageId, templateLess };
|
|
783
|
+
return config;
|
|
784
|
+
},
|
|
785
|
+
transformIndexHtml: async (html, ctx) => {
|
|
786
|
+
const result = { html, tags: [] };
|
|
787
|
+
if (isFirstRequest) {
|
|
788
|
+
isFirstRequest = false;
|
|
789
|
+
result.tags.push({
|
|
790
|
+
tag: 'script',
|
|
791
|
+
injectTo: 'body',
|
|
792
|
+
children: `${Math.random()}`,
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
return result;
|
|
796
|
+
},
|
|
797
|
+
configureServer: (server) => {
|
|
798
|
+
let base = server.config.base;
|
|
799
|
+
if (!base.endsWith('/')) {
|
|
800
|
+
base += '/';
|
|
801
|
+
}
|
|
802
|
+
const baseWithoutTrailingSlash = base.substring(0, base.lastIndexOf('/'));
|
|
803
|
+
server.middlewares.use(initPPRedirect(base, templateName));
|
|
804
|
+
if (backendBaseURL) {
|
|
805
|
+
const baseUrlHost = new URL(backendBaseURL).host;
|
|
806
|
+
const mi = new MiAPI(backendBaseURL, {
|
|
807
|
+
headers: {
|
|
808
|
+
host: baseUrlHost,
|
|
809
|
+
referer: backendBaseURL,
|
|
810
|
+
origin: backendBaseURL.replace(/^(https?:\/\/)([^/]+)(\/.*)?$/i, '$1$2'),
|
|
811
|
+
},
|
|
812
|
+
portalPageId,
|
|
813
|
+
templateLess,
|
|
814
|
+
});
|
|
815
|
+
if (enableProxyCache) {
|
|
816
|
+
let ttl = +proxyCacheTTL;
|
|
817
|
+
if (!ttl || Number.isNaN(ttl) || ttl < 0) {
|
|
818
|
+
ttl = 10 * 60 * 1000; // 10 minutes
|
|
819
|
+
}
|
|
820
|
+
server.middlewares.use(initProxyCache({ devServer: server, ttl }));
|
|
821
|
+
}
|
|
822
|
+
server.middlewares.use(initProxy({
|
|
823
|
+
devServer: server,
|
|
824
|
+
baseURL: backendBaseURL,
|
|
825
|
+
proxyIgnore: ['/@vite', '/@metricinsights', '/@', baseWithoutTrailingSlash],
|
|
826
|
+
}));
|
|
827
|
+
const isIndexRegExp = new RegExp(`^((${base})|/)$`);
|
|
828
|
+
// Get portal page variables from the backend (also, redirect magic)
|
|
829
|
+
server.middlewares.use(initLoadPPData(isIndexRegExp, mi, options));
|
|
830
|
+
server.middlewares.use(initRewriteResponse((url) => {
|
|
831
|
+
return isIndexRegExp.test(cutUrlParams(url));
|
|
832
|
+
}, (response, req) => {
|
|
833
|
+
return Buffer.from(urlReplacer(baseUrlHost, req.headers.host ?? '', mi.buildPage(response, miHudLess)));
|
|
834
|
+
}));
|
|
835
|
+
const distService = new DistService(templateName);
|
|
836
|
+
new ClientService(server, { distService, miAPI: mi });
|
|
837
|
+
}
|
|
838
|
+
},
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
export { MiAPI as M, initProxyCache as a, initProxy as b, initLoadPPData as c, initRewriteResponse as d, cutUrlParams as e, initPPRedirect as i, urlReplacer as u, vitePPDev as v };
|
|
843
|
+
//# sourceMappingURL=plugin-ecb1c54a.js.map
|