@hubspot/cms-dev-server 1.1.0-prerelease.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 +3 -0
- package/dist/components/ModulesList.js +14 -0
- package/dist/components/PartialsList.js +13 -0
- package/dist/createDevServer.js +25 -0
- package/dist/createViteDevServer.js +26 -0
- package/dist/html/baseTemplate.html +12 -0
- package/dist/lib/fullOriginalUrlFromRequest.js +3 -0
- package/dist/lib/htmlHelpers.js +10 -0
- package/dist/lib/moduleGraph.js +11 -0
- package/dist/lib/proxyHelpers.js +69 -0
- package/dist/lib/proxyHelpers.test.js +136 -0
- package/dist/lib/renderComponentWithCSS.js +26 -0
- package/dist/lib/renderHelpers.js +21 -0
- package/dist/lib/renderModule.js +88 -0
- package/dist/lib/renderPartial.js +12 -0
- package/dist/lib/templates.js +49 -0
- package/dist/plugins/devMockClientEntryPlugin.js +52 -0
- package/dist/proxyPage/constants.js +4 -0
- package/dist/proxyPage/fetchContentMetadata.js +51 -0
- package/dist/proxyPage/fetchPreviewInfo.js +37 -0
- package/dist/proxyPage/proxyPage.js +167 -0
- package/dist/proxyPage/renderLocalError.js +27 -0
- package/dist/proxyPage/utils.js +38 -0
- package/dist/routes/createDevServerRoutes.js +21 -0
- package/dist/routes/homeRouteHandler.js +12 -0
- package/dist/routes/linksToAllModulesRouteHandler.js +10 -0
- package/dist/routes/linksToAllPartialsRouteHandler.js +10 -0
- package/dist/routes/module.js +26 -0
- package/dist/routes/partial.js +26 -0
- package/dist/routes/proxyPage.js +205 -0
- package/dist/routes/proxyPageResourceRedirect.js +12 -0
- package/dist/routes/proxyPageRouteHandler.js +40 -0
- package/dist/run.js +7 -0
- package/dist/run.mjs +10 -0
- package/dist/src/components/ModulesList.js +14 -0
- package/dist/src/components/PartialsList.js +13 -0
- package/dist/src/createDevServer.js +45 -0
- package/dist/src/lib/htmlHelpers.js +10 -0
- package/dist/src/lib/moduleGraph.js +9 -0
- package/dist/src/lib/proxyHelpers.js +55 -0
- package/dist/src/lib/proxyHelpers.test.js +136 -0
- package/dist/src/lib/renderComponentWithCSS.js +26 -0
- package/dist/src/lib/renderModule.js +84 -0
- package/dist/src/lib/renderPartial.js +11 -0
- package/dist/src/lib/templates.js +50 -0
- package/dist/src/plugins/devMockClientEntryPlugin.js +52 -0
- package/dist/src/proxyPage/constants.js +4 -0
- package/dist/src/proxyPage/fetchContentMetadata.js +40 -0
- package/dist/src/proxyPage/fetchPreviewInfo.js +25 -0
- package/dist/src/proxyPage/proxyPage.js +147 -0
- package/dist/src/proxyPage/renderLocalError.js +1 -0
- package/dist/src/proxyPage/utils.js +36 -0
- package/dist/src/routes/createDevServerRoutes.js +19 -0
- package/dist/src/routes/homeRouteHandler.js +12 -0
- package/dist/src/routes/linksToAllModulesRouteHandler.js +10 -0
- package/dist/src/routes/linksToAllPartialsRouteHandler.js +10 -0
- package/dist/src/routes/module.js +26 -0
- package/dist/src/routes/partial.js +26 -0
- package/dist/src/routes/proxyPageRouteHandler.js +28 -0
- package/package.json +65 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
2
|
+
export default async (accountId, portalId, contentId) => {
|
|
3
|
+
if (!contentId) {
|
|
4
|
+
throw new Error(`Invalid contentId when attempting to fetch preview info: ${contentId}`);
|
|
5
|
+
}
|
|
6
|
+
try {
|
|
7
|
+
// Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
|
|
8
|
+
const content = await hsGet(accountId, {
|
|
9
|
+
uri: `/content/api/v4/contents/${contentId}`,
|
|
10
|
+
query: { portalId },
|
|
11
|
+
json: true,
|
|
12
|
+
});
|
|
13
|
+
return {
|
|
14
|
+
previewDomain: content.previewDomain ?? content.resolvedDomain,
|
|
15
|
+
previewKey: content.previewKey,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error.statusCode === 403 &&
|
|
20
|
+
error.error.message.match(/^This oauth-token \([\w]+\) does not have proper permissions!/)) {
|
|
21
|
+
const errorMessagePrefix = `Your personal access key is missing required scopes to preview a CMS page.\nYou may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account\n`;
|
|
22
|
+
console.error('Error: ', errorMessagePrefix);
|
|
23
|
+
console.error(error.error.message);
|
|
24
|
+
throw new Error(`${errorMessagePrefix}\n${error.error.message}`);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
console.log(`fetchPreviewInfo Error`, error);
|
|
28
|
+
if (error.options) {
|
|
29
|
+
console.log(`error.options`, error.options);
|
|
30
|
+
}
|
|
31
|
+
if (error.response && error.response.headers) {
|
|
32
|
+
console.log(`error.response.headers`, error.response.headers);
|
|
33
|
+
}
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
3
|
+
/* eslint-disable no-loop-func */
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
|
|
6
|
+
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
7
|
+
import { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
|
|
8
|
+
import renderPartial from '../lib/renderPartial.js';
|
|
9
|
+
import renderModule from '../lib/renderModule.js';
|
|
10
|
+
import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
|
|
11
|
+
import { ENTRY_POINTS_PATH, MODULE_FOLDER_PATH, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
|
|
12
|
+
import { fakeRenderJsComponent } from './utils.js';
|
|
13
|
+
import renderLocalError from './renderLocalError.js';
|
|
14
|
+
import fetchPreviewInfo from './fetchPreviewInfo.js';
|
|
15
|
+
const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
|
|
16
|
+
const url = new URL(urlToProxy);
|
|
17
|
+
console.log(`Proxying request to ${url.href}`, {
|
|
18
|
+
previewKey,
|
|
19
|
+
contentId,
|
|
20
|
+
});
|
|
21
|
+
let proxiedQueryParams = {};
|
|
22
|
+
// Convert searchParams to object param format hsGet/request expects
|
|
23
|
+
for (const queryKey of url.searchParams.keys()) {
|
|
24
|
+
const values = url.searchParams.getAll(queryKey);
|
|
25
|
+
if (values.length > 1) {
|
|
26
|
+
proxiedQueryParams[queryKey] = values;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
proxiedQueryParams[queryKey] = values[0];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
proxiedQueryParams = {
|
|
33
|
+
...proxiedQueryParams,
|
|
34
|
+
hs_preview: `${previewKey}-${contentId}`,
|
|
35
|
+
hsLocalProxy: true,
|
|
36
|
+
};
|
|
37
|
+
const result = hsGet(accountId, {
|
|
38
|
+
baseUrl: url.origin,
|
|
39
|
+
uri: url.pathname,
|
|
40
|
+
query: proxiedQueryParams,
|
|
41
|
+
json: false,
|
|
42
|
+
useQuerystring: true,
|
|
43
|
+
});
|
|
44
|
+
return result.catch(error => {
|
|
45
|
+
if (error.statusCode >= 400 &&
|
|
46
|
+
error.statusCode < 500 &&
|
|
47
|
+
!!error.response.body) {
|
|
48
|
+
return error.response.body;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer, pageUrl, hsProjectJsonProjectName, webRootProjectComponent) => {
|
|
56
|
+
const { path: placeholderPath } = localRenderPlaceholder;
|
|
57
|
+
const [__projectIdentifier, projectFolder, projectComponentFolder, componentFolder, componentTypeFolder, componentFileName,] = placeholderPath.split('/');
|
|
58
|
+
const partialPath = `${componentFolder}/${componentTypeFolder}/`;
|
|
59
|
+
if (projectFolder !== hsProjectJsonProjectName) {
|
|
60
|
+
throw new Error(`Unable to render component located outside of the project folder "${hsProjectJsonProjectName}". Components should be nested within the project folder. Check that the specified path is correct: ${placeholderPath}.`);
|
|
61
|
+
}
|
|
62
|
+
else if (projectComponentFolder !== webRootProjectComponent) {
|
|
63
|
+
throw new Error(`The specified component folder "${projectComponentFolder}" does not match the webroot project component folder "${webRootProjectComponent}/${projectComponentFolder}" specified to the cms-dev-server. Components must be located within the webroot project folder. Check that the specified path is correct: ${placeholderPath}.`);
|
|
64
|
+
}
|
|
65
|
+
const resolvedPath = path.resolve(webRoot, partialPath, componentFileName);
|
|
66
|
+
if (placeholderPath.startsWith('/fake/path/to/')) {
|
|
67
|
+
return fakeRenderJsComponent(indexForThisRender);
|
|
68
|
+
}
|
|
69
|
+
else if (partialPath === ENTRY_POINTS_PATH) {
|
|
70
|
+
return renderPartial(viteServer, resolvedPath, localRenderPlaceholder.json, pageUrl);
|
|
71
|
+
}
|
|
72
|
+
else if (partialPath === MODULE_FOLDER_PATH) {
|
|
73
|
+
return renderModule(viteServer, resolvedPath, localRenderPlaceholder.json, pageUrl);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
throw new Error(`Unimplemented render of ${placeholderPath}.`);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
export default async function proxySpecificPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
|
|
80
|
+
let accountId;
|
|
81
|
+
try {
|
|
82
|
+
accountId = getAccountId(portalId);
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
response
|
|
86
|
+
.status(500)
|
|
87
|
+
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (!accountId) {
|
|
91
|
+
response
|
|
92
|
+
.status(500)
|
|
93
|
+
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
|
|
98
|
+
const { previewKey } = previewInfo;
|
|
99
|
+
const pageHtml = await makeProxyPreviewRequest(accountId, urlToProxy, previewKey, contentId);
|
|
100
|
+
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
101
|
+
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
102
|
+
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
103
|
+
const numPlaceholders = localRenderPlaceholders.length;
|
|
104
|
+
let numJsRenderFailures = 0;
|
|
105
|
+
let islands = [];
|
|
106
|
+
const renderPromisesByChunkIndex = new Array(numPlaceholders);
|
|
107
|
+
if (localRenderPlaceholders.length > 0) {
|
|
108
|
+
let offsetSoFar = 0;
|
|
109
|
+
const pageChunks = new Array(numPlaceholders + 1);
|
|
110
|
+
for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
|
|
111
|
+
const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
|
|
112
|
+
pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
|
|
113
|
+
const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer, fullOriginalUrl, projectName, projectComponentPath);
|
|
114
|
+
renderPromisesByChunkIndex[indexForThisRender] = renderPromise
|
|
115
|
+
.then(promiseResult => {
|
|
116
|
+
// eslint-disable-next-line prefer-const
|
|
117
|
+
let { html, cssNeeded, renderContext } = promiseResult;
|
|
118
|
+
console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
|
|
119
|
+
if (renderContext.islands.length > 0) {
|
|
120
|
+
islands = islands.concat(renderContext.islands);
|
|
121
|
+
}
|
|
122
|
+
if (cssNeeded) {
|
|
123
|
+
return `${cssNeeded}\n${html}`;
|
|
124
|
+
}
|
|
125
|
+
return html;
|
|
126
|
+
})
|
|
127
|
+
.catch(e => {
|
|
128
|
+
numJsRenderFailures += 1;
|
|
129
|
+
console.error(e);
|
|
130
|
+
return renderLocalError(localRenderPlaceholder.path, e);
|
|
131
|
+
});
|
|
132
|
+
offsetSoFar = localRenderPlaceholder.endOffset;
|
|
133
|
+
}
|
|
134
|
+
// Last chunk from end of last placeholder to end of HTML
|
|
135
|
+
pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
|
|
136
|
+
response.writeHead(200);
|
|
137
|
+
for (let i = 0; i < localRenderPlaceholders.length; i++) {
|
|
138
|
+
const chunk = pageChunks[i];
|
|
139
|
+
response.write(chunk);
|
|
140
|
+
const foobar = await renderPromisesByChunkIndex[i];
|
|
141
|
+
// console.log("JS rendered chunk", i, foobar);
|
|
142
|
+
response.write(foobar);
|
|
143
|
+
}
|
|
144
|
+
response.write(getServerGlobalsToInject(fullOriginalUrl));
|
|
145
|
+
if (islands.length > 0) {
|
|
146
|
+
const sortedIslandRoots = sortIslandRootsByPriority(islands);
|
|
147
|
+
const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
|
|
148
|
+
response.write(islandRuntimeAndGlobalScriptHtml);
|
|
149
|
+
}
|
|
150
|
+
// Write last string chunk located after last placeholder
|
|
151
|
+
response.write(pageChunks[pageChunks.length - 1]);
|
|
152
|
+
response.end();
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
response.writeHead(200);
|
|
156
|
+
response.write(pageHtml);
|
|
157
|
+
response.end();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
// TODO change error.stack to error.message before we publish
|
|
162
|
+
response
|
|
163
|
+
.status(500)
|
|
164
|
+
.end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import AnsiToHtmlConverter from 'ansi-to-html';
|
|
2
|
+
// Custom ansi colors pulled from tfinley's terminal theme
|
|
3
|
+
const customColors = [
|
|
4
|
+
// Normal colors
|
|
5
|
+
'#000',
|
|
6
|
+
'#ec392c',
|
|
7
|
+
'#b3e439',
|
|
8
|
+
'#fea525',
|
|
9
|
+
'#76dff3',
|
|
10
|
+
'#fd4285',
|
|
11
|
+
'#cfa3ff',
|
|
12
|
+
'#f4f4f4',
|
|
13
|
+
// Bright colors (mostly identical to ^)
|
|
14
|
+
'#646464',
|
|
15
|
+
'#ec392c',
|
|
16
|
+
'#fea525',
|
|
17
|
+
'#76dff3',
|
|
18
|
+
'#fd4285',
|
|
19
|
+
'#cfa3ff',
|
|
20
|
+
'#f4f4f4',
|
|
21
|
+
];
|
|
22
|
+
const Converter = new AnsiToHtmlConverter({ colors: customColors });
|
|
23
|
+
const darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
|
|
24
|
+
export default (path, error) => {
|
|
25
|
+
const stackWithColorClasses = Converter.toHtml(error.stack);
|
|
26
|
+
return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
|
|
27
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable prefer-promise-reject-errors */
|
|
3
|
+
import { createServerRenderContext } from '@hubspot/cms-components';
|
|
4
|
+
import { VALID_PROXY_DOMAIN_SUFFIXES } from './constants.js';
|
|
5
|
+
export const getSubDomainFromValidLocalDomain = hostname => {
|
|
6
|
+
for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
|
|
7
|
+
if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
|
|
8
|
+
return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return undefined;
|
|
12
|
+
};
|
|
13
|
+
const randomStringWithLotsOf = (char, maxLength) => {
|
|
14
|
+
return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
|
|
15
|
+
};
|
|
16
|
+
export const fakeRenderJsComponent = (indexForThisRender) => {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
|
|
19
|
+
setTimeout(() => {
|
|
20
|
+
try {
|
|
21
|
+
const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
|
|
22
|
+
resolve({
|
|
23
|
+
html: fakeJsRenderedOutput,
|
|
24
|
+
cssNeeded: '',
|
|
25
|
+
renderContext: createServerRenderContext(null),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
console.log('Error with JS render...');
|
|
30
|
+
console.error(e);
|
|
31
|
+
reject();
|
|
32
|
+
}
|
|
33
|
+
}, randomTimeout);
|
|
34
|
+
});
|
|
35
|
+
};
|
|
36
|
+
export const consoleWarn = message => {
|
|
37
|
+
console.warn('\x1b[33m%s\x1b[0m', 'WARNING:', message);
|
|
38
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import partialRouteHandler from './partial.js';
|
|
3
|
+
import linksToAllPartialsRouteHandler from './linksToAllPartialsRouteHandler.js';
|
|
4
|
+
import linksToAllModulesRouteHandler from './linksToAllModulesRouteHandler.js';
|
|
5
|
+
import moduleRouteHandler from './module.js';
|
|
6
|
+
import proxyPageRouteHandler from './proxyPageRouteHandler.js';
|
|
7
|
+
import proxyPageResourceRedirect from './proxyPageResourceRedirect.js';
|
|
8
|
+
import homeRouteHandler from './homeRouteHandler.js';
|
|
9
|
+
const createDevServerRoutes = async (viteServer) => {
|
|
10
|
+
const devServerApp = Router();
|
|
11
|
+
devServerApp.use(viteServer.middlewares);
|
|
12
|
+
devServerApp.get('/partials/', linksToAllPartialsRouteHandler);
|
|
13
|
+
devServerApp.get('/partial/:partial', partialRouteHandler);
|
|
14
|
+
devServerApp.get('/modules/', linksToAllModulesRouteHandler);
|
|
15
|
+
devServerApp.get('/module/:moduleName', moduleRouteHandler);
|
|
16
|
+
devServerApp.get('/', homeRouteHandler);
|
|
17
|
+
devServerApp.get('/*', proxyPageResourceRedirect);
|
|
18
|
+
devServerApp.get('/*', proxyPageRouteHandler);
|
|
19
|
+
return devServerApp;
|
|
20
|
+
};
|
|
21
|
+
export default createDevServerRoutes;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { findAllModulesInRoot, findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
|
|
3
|
+
import ModulesList from '../components/ModulesList.js';
|
|
4
|
+
import PartialsList from '../components/PartialsList.js';
|
|
5
|
+
const homeRouteHandler = async (request, response) => {
|
|
6
|
+
const { webRoot } = request.app.locals;
|
|
7
|
+
const { partialNames } = findAllPartialsInRoot(webRoot);
|
|
8
|
+
const { moduleNames } = findAllModulesInRoot(webRoot);
|
|
9
|
+
const { html: responseHtml } = await renderOnServer(_jsxs(_Fragment, { children: [_jsx("h2", { children: "Partials" }), _jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), _jsx("h2", { children: "Modules" }), _jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames })] }), null);
|
|
10
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
11
|
+
};
|
|
12
|
+
export default homeRouteHandler;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { findAllModulesInRoot, renderOnServer } from '@hubspot/cms-js-internal';
|
|
3
|
+
import ModulesList from '../components/ModulesList.js';
|
|
4
|
+
const linksToAllModuleRouteHandler = async (request, response) => {
|
|
5
|
+
const { webRoot } = request.app.locals;
|
|
6
|
+
const { moduleNames } = findAllModulesInRoot(webRoot);
|
|
7
|
+
const { html: responseHtml } = await renderOnServer(_jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames }), null);
|
|
8
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
+
};
|
|
10
|
+
export default linksToAllModuleRouteHandler;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
|
|
3
|
+
import PartialsList from '../components/PartialsList.js';
|
|
4
|
+
const linksToAllPartialRouteHandler = async (request, response) => {
|
|
5
|
+
const { webRoot } = request.app.locals;
|
|
6
|
+
const { partialNames } = findAllPartialsInRoot(webRoot);
|
|
7
|
+
const { html: responseHtml } = await renderOnServer(_jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), null);
|
|
8
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
+
};
|
|
10
|
+
export default linksToAllPartialRouteHandler;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
3
|
+
import renderModule from '../lib/renderModule.js';
|
|
4
|
+
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
5
|
+
const moduleRouteHandler = async (request, response) => {
|
|
6
|
+
const { webRoot, viteServer } = request.app.locals;
|
|
7
|
+
const moduleName = request.params.moduleName;
|
|
8
|
+
const baseTemplatePath = path.join(import.meta.url.replace('file://', ''), '../../html/baseTemplate.html');
|
|
9
|
+
const modulePath = path.resolve(webRoot, 'components/modules/', moduleName);
|
|
10
|
+
try {
|
|
11
|
+
const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, null, fullOriginalUrlFromRequest(request));
|
|
12
|
+
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer);
|
|
13
|
+
const html = htmlShell
|
|
14
|
+
.replace('<!--headend-->', cssNeeded)
|
|
15
|
+
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
16
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
console.error(e);
|
|
20
|
+
viteServer.ssrFixStacktrace(e);
|
|
21
|
+
response
|
|
22
|
+
.status(500)
|
|
23
|
+
.end(`Error rendering module (${moduleName})\n\n${e.stack}`);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
export default moduleRouteHandler;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
3
|
+
import renderPartial from '../lib/renderPartial.js';
|
|
4
|
+
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
5
|
+
const partialRouteHandler = async (request, response) => {
|
|
6
|
+
const { webRoot, viteServer } = request.app.locals;
|
|
7
|
+
const partialName = request.params.partial;
|
|
8
|
+
const baseTemplatePath = path.join(import.meta.url.replace('file://', ''), '../../html/baseTemplate.html');
|
|
9
|
+
const partialPath = path.resolve(webRoot, 'components/partials/', partialName);
|
|
10
|
+
try {
|
|
11
|
+
const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request));
|
|
12
|
+
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderContext, viteServer);
|
|
13
|
+
const html = htmlShell
|
|
14
|
+
.replace('<!--headend-->', cssNeeded)
|
|
15
|
+
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
16
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
console.error(e);
|
|
20
|
+
viteServer.ssrFixStacktrace(e);
|
|
21
|
+
response
|
|
22
|
+
.status(500)
|
|
23
|
+
.end(`Error rendering partial (${partialName})\n\n${e.stack}`);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
export default partialRouteHandler;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
|
|
3
|
+
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
4
|
+
import { createRenderInfoContext } from '@hubspot/cms-components';
|
|
5
|
+
import { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
|
|
6
|
+
import renderPartial from '../lib/renderPartial.js';
|
|
7
|
+
import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
|
|
8
|
+
import { rewriteAbsoluteJsAndCssPaths } from '../lib/htmlHelpers.js';
|
|
9
|
+
const fetchPreviewInfo = async (accountId, portalId, contentId) => {
|
|
10
|
+
try {
|
|
11
|
+
// Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
|
|
12
|
+
const content = await hsGet(accountId, {
|
|
13
|
+
uri: `/content/api/v4/contents/${contentId}`,
|
|
14
|
+
query: { portalId },
|
|
15
|
+
json: true,
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
previewDomain: content.previewDomain ?? content.resolvedDomain,
|
|
19
|
+
previewKey: content.previewKey,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.log(`error`, error);
|
|
24
|
+
if (error.options) {
|
|
25
|
+
console.log(`error.options`, error.options);
|
|
26
|
+
}
|
|
27
|
+
if (error.response && error.response.headers) {
|
|
28
|
+
console.log(`error.response.headers`, error.response.headers);
|
|
29
|
+
}
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const createPreviewQueryParams = (previewInfo) => {
|
|
34
|
+
const { previewKey } = previewInfo;
|
|
35
|
+
return {
|
|
36
|
+
_preview: true,
|
|
37
|
+
preview_key: previewKey,
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
const createPreviewPath = (contentId) => {
|
|
41
|
+
return `/_hcms/preview/content/${contentId}`;
|
|
42
|
+
};
|
|
43
|
+
const makeProxyPreviewRequest = (accountId, host, path, queryParams) => {
|
|
44
|
+
console.log(`Proxying request to https://${host}${path}`);
|
|
45
|
+
const result = hsGet(accountId, {
|
|
46
|
+
baseUrl: `https://${host}`,
|
|
47
|
+
uri: `${path}`,
|
|
48
|
+
query: {
|
|
49
|
+
...queryParams,
|
|
50
|
+
// Makes render_js_partial return comments instead of actually rendering
|
|
51
|
+
hsLocalProxy: true,
|
|
52
|
+
},
|
|
53
|
+
json: false,
|
|
54
|
+
});
|
|
55
|
+
console.log('hsGet', `https://${host}${path}`, queryParams);
|
|
56
|
+
return result.catch((error) => {
|
|
57
|
+
if (error.statusCode >= 400 &&
|
|
58
|
+
error.statusCode < 500 &&
|
|
59
|
+
!!error.response.body) {
|
|
60
|
+
return error.response.body;
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
const createLocalJsRenderErrorOutput = (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
|
|
68
|
+
const randomStringWithLotsOf = (char, maxLength) => {
|
|
69
|
+
return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
|
|
70
|
+
};
|
|
71
|
+
const fakeRenderJsComponent = (indexForThisRender) => {
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
|
|
74
|
+
setTimeout(() => {
|
|
75
|
+
try {
|
|
76
|
+
const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
|
|
77
|
+
resolve({
|
|
78
|
+
html: fakeJsRenderedOutput,
|
|
79
|
+
cssNeeded: '',
|
|
80
|
+
renderInfoContext: createRenderInfoContext(),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
console.log('Error with JS render...');
|
|
85
|
+
console.error(e);
|
|
86
|
+
reject();
|
|
87
|
+
}
|
|
88
|
+
}, randomTimeout);
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer) => {
|
|
92
|
+
if (localRenderPlaceholder.path.startsWith('/fake/path/to/')) {
|
|
93
|
+
return fakeRenderJsComponent(indexForThisRender);
|
|
94
|
+
}
|
|
95
|
+
else if (localRenderPlaceholder.path.startsWith('components/partials/')) {
|
|
96
|
+
const partialPath = path.resolve(webRoot, localRenderPlaceholder.path);
|
|
97
|
+
return renderPartial(viteServer, partialPath, localRenderPlaceholder.json);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
throw new Error(`Unimplemented render of ${localRenderPlaceholder.path}`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
async function proxySpecificPage(response, portalId, contentId, currentUrl, webRoot, viteServer, devServerHost, devServerPort) {
|
|
104
|
+
let accountId;
|
|
105
|
+
try {
|
|
106
|
+
accountId = getAccountId(portalId);
|
|
107
|
+
}
|
|
108
|
+
catch (e) {
|
|
109
|
+
response
|
|
110
|
+
.status(500)
|
|
111
|
+
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (!accountId) {
|
|
115
|
+
response
|
|
116
|
+
.status(500)
|
|
117
|
+
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
|
|
122
|
+
const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
|
|
123
|
+
const { previewDomain } = previewInfo;
|
|
124
|
+
const previewPath = createPreviewPath(contentId);
|
|
125
|
+
const previewQueryParams = createPreviewQueryParams(previewInfo);
|
|
126
|
+
let pageHtml = await makeProxyPreviewRequest(accountId, previewDomain, previewPath, previewQueryParams);
|
|
127
|
+
// TODO, this is only needed for asset references that happen _before_ the `<base href="...">` element
|
|
128
|
+
// Is that only a preview URL thing? Or is it in all (most?) rendered CMS pages
|
|
129
|
+
pageHtml = rewriteAbsoluteJsAndCssPaths(pageHtml, previewDomain, 'https://');
|
|
130
|
+
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
131
|
+
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
132
|
+
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
133
|
+
const numPlaceholders = localRenderPlaceholders.length;
|
|
134
|
+
const totalNumHtmlChunks = numPlaceholders * 2 + 1;
|
|
135
|
+
let numJsRenderFailures = 0;
|
|
136
|
+
let islands = [];
|
|
137
|
+
const renderPromisesByChunkIndex = new Array(numPlaceholders);
|
|
138
|
+
if (localRenderPlaceholders.length > 0) {
|
|
139
|
+
let offsetSoFar = 0;
|
|
140
|
+
const pageChunks = new Array(numPlaceholders + 1);
|
|
141
|
+
for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
|
|
142
|
+
const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
|
|
143
|
+
pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
|
|
144
|
+
const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer);
|
|
145
|
+
renderPromisesByChunkIndex[indexForThisRender] = renderPromise
|
|
146
|
+
.then((promiseResult) => {
|
|
147
|
+
// eslint-disable-next-line prefer-const
|
|
148
|
+
let { html, cssNeeded, renderInfoContext } = promiseResult;
|
|
149
|
+
console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
|
|
150
|
+
if (renderInfoContext.islands.length > 0) {
|
|
151
|
+
islands = islands.concat(renderInfoContext.islands);
|
|
152
|
+
}
|
|
153
|
+
if (cssNeeded) {
|
|
154
|
+
// Note, this is needed for cases where `<base href="...">` is output by the renderer, so
|
|
155
|
+
// that local asset URLs go to the local dev server
|
|
156
|
+
cssNeeded = rewriteAbsoluteJsAndCssPaths(cssNeeded, serverDomainAndPort, 'http://');
|
|
157
|
+
return `${cssNeeded}\n${html}`;
|
|
158
|
+
}
|
|
159
|
+
return html;
|
|
160
|
+
})
|
|
161
|
+
.catch((e) => {
|
|
162
|
+
numJsRenderFailures += 1;
|
|
163
|
+
console.error(e);
|
|
164
|
+
return createLocalJsRenderErrorOutput(localRenderPlaceholder.path, e);
|
|
165
|
+
});
|
|
166
|
+
offsetSoFar = localRenderPlaceholder.endOffset;
|
|
167
|
+
}
|
|
168
|
+
// Last chunk from end of last placeholder to end of HTML
|
|
169
|
+
pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
|
|
170
|
+
response.writeHead(200);
|
|
171
|
+
for (let i = 0; i < localRenderPlaceholders.length; i++) {
|
|
172
|
+
const chunk = pageChunks[i];
|
|
173
|
+
response.write(chunk);
|
|
174
|
+
const foobar = await renderPromisesByChunkIndex[i];
|
|
175
|
+
// console.log("JS rendered chunk", i, foobar);
|
|
176
|
+
response.write(foobar);
|
|
177
|
+
}
|
|
178
|
+
if (islands.length > 0) {
|
|
179
|
+
const sortedIslandRoots = sortIslandRootsByPriority(islands);
|
|
180
|
+
const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
|
|
181
|
+
response.write(islandRuntimeAndGlobalScriptHtml);
|
|
182
|
+
}
|
|
183
|
+
// Write last string chunk located after last placeholder
|
|
184
|
+
response.write(pageChunks[pageChunks.length - 1]);
|
|
185
|
+
response.end();
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
response.writeHead(200);
|
|
189
|
+
response.write(pageHtml);
|
|
190
|
+
response.end();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
// TODO change error.stack to error.message before we publish
|
|
195
|
+
response
|
|
196
|
+
.status(500)
|
|
197
|
+
.end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
async function proxyPageHandler(request, response) {
|
|
202
|
+
const { packageRoot, viteServer, webRoot, devServerHost, devServerPort } = request.app.locals;
|
|
203
|
+
await proxySpecificPage(response, parseInt(request.params.portalId, 10), request.params.contentId, request.originalUrl, webRoot, viteServer, devServerHost, devServerPort);
|
|
204
|
+
}
|
|
205
|
+
export default proxyPageHandler;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import request from 'request';
|
|
2
|
+
import { getSubDomainFromValidLocalDomain } from '../proxyPage/utils.js';
|
|
3
|
+
export default function proxyPageResourceRedirect(req, res, next) {
|
|
4
|
+
if (req.accepts().includes('text/html') || req.hostname === 'localhost') {
|
|
5
|
+
next();
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
const domainToProxy = getSubDomainFromValidLocalDomain(req.hostname);
|
|
9
|
+
const pathToProxy = req.originalUrl;
|
|
10
|
+
const urlToProxy = `https://${domainToProxy}${pathToProxy}`;
|
|
11
|
+
request(urlToProxy).pipe(res);
|
|
12
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/* hs-eslint ignored failing-rules */
|
|
2
|
+
/* eslint-disable consistent-return */
|
|
3
|
+
import fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';
|
|
4
|
+
import proxyPage from '../proxyPage/proxyPage.js';
|
|
5
|
+
import { getSubDomainFromValidLocalDomain, consoleWarn, } from '../proxyPage/utils.js';
|
|
6
|
+
import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
|
|
7
|
+
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
8
|
+
export default async function proxyPageRouteHandler(request, response, next) {
|
|
9
|
+
const { viteServer, webRoot, devServerHost, devServerPort, projectName, projectComponentPath, } = request.app.locals;
|
|
10
|
+
if (!request.accepts().includes('text/html')) {
|
|
11
|
+
return response.sendStatus(404);
|
|
12
|
+
}
|
|
13
|
+
const fullOriginalUrl = fullOriginalUrlFromRequest(request);
|
|
14
|
+
const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);
|
|
15
|
+
const urlToProxy = `http://${domainToProxy}${request.originalUrl}`;
|
|
16
|
+
if (!domainToProxy) {
|
|
17
|
+
if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {
|
|
18
|
+
const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;
|
|
19
|
+
consoleWarn(message);
|
|
20
|
+
return response.status(400).send(message);
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;
|
|
24
|
+
consoleWarn(message);
|
|
25
|
+
return response.status(400).send(message);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (request.query.hs_preview) {
|
|
29
|
+
const message = `Can't make a proxy request, you cannot proxy URLs that include internal query params like hs_preview`;
|
|
30
|
+
consoleWarn(message);
|
|
31
|
+
return response.status(400).send(message);
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const { portalId, contentId } = await fetchContentMetadata(urlToProxy);
|
|
35
|
+
await proxyPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, projectName, projectComponentPath, urlToProxy, fullOriginalUrl);
|
|
36
|
+
}
|
|
37
|
+
catch (e) {
|
|
38
|
+
next(e);
|
|
39
|
+
}
|
|
40
|
+
}
|