@hubspot/cms-dev-server 0.2.11
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/LICENSE +12 -0
- package/README.md +3 -0
- package/dist/components/ModulesList.js +14 -0
- package/dist/components/PartialsList.js +13 -0
- package/dist/createDevServer.js +63 -0
- package/dist/createViteDevServer.js +26 -0
- package/dist/html/baseTemplate.html +12 -0
- package/dist/lib/argHelpers.js +6 -0
- package/dist/lib/cli.js +23 -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 +70 -0
- package/dist/lib/proxyHelpers.test.js +136 -0
- package/dist/lib/renderComponentWithCSS.js +26 -0
- package/dist/lib/renderHelpers.js +45 -0
- package/dist/lib/renderModule.js +88 -0
- package/dist/lib/renderPartial.js +12 -0
- package/dist/lib/templates.js +48 -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 +28 -0
- package/dist/routes/partial.js +28 -0
- package/dist/routes/proxyPageResourceRedirect.js +12 -0
- package/dist/routes/proxyPageRouteHandler.js +40 -0
- package/dist/run.js +8 -0
- package/package.json +68 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { readdirSync } from 'fs';
|
|
3
|
+
const PARTIAL_SOURCE_DIR = 'components/partials';
|
|
4
|
+
function getAllComponentFilenamesIn(dirPath) {
|
|
5
|
+
return readdirSync(dirPath).filter(filename => {
|
|
6
|
+
const ext = path.extname(filename);
|
|
7
|
+
return ext === '.jsx' || ext === '.tsx';
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
const buildMockPartialModule = entryPointsFileNames => {
|
|
11
|
+
return entryPointsFileNames
|
|
12
|
+
.map(filename => {
|
|
13
|
+
const ext = path.extname(filename);
|
|
14
|
+
const withoutExtension = path.basename(filename, ext);
|
|
15
|
+
return `export const ${withoutExtension} = () => import('/${PARTIAL_SOURCE_DIR}/${filename}');`;
|
|
16
|
+
})
|
|
17
|
+
.join('\n');
|
|
18
|
+
};
|
|
19
|
+
// Not needed in dev unless some code wants to do `import { SomePartial } from 'components/partials'`
|
|
20
|
+
export default function devMockClientEntryPlugin(webRoot) {
|
|
21
|
+
const ENTRY_POINTS_PATH = path.resolve(webRoot, PARTIAL_SOURCE_DIR);
|
|
22
|
+
const MOCK_ENTRY_PATH = `${ENTRY_POINTS_PATH}/index.js`;
|
|
23
|
+
return {
|
|
24
|
+
enforce: 'pre',
|
|
25
|
+
name: 'client-entry',
|
|
26
|
+
options(options) {
|
|
27
|
+
if (!options.input) {
|
|
28
|
+
return {
|
|
29
|
+
...options,
|
|
30
|
+
input: [MOCK_ENTRY_PATH],
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return options;
|
|
34
|
+
},
|
|
35
|
+
async resolveId(source, importer, options) {
|
|
36
|
+
if (source === PARTIAL_SOURCE_DIR /*&& options.isEntry*/) {
|
|
37
|
+
return {
|
|
38
|
+
id: source,
|
|
39
|
+
moduleSideEffects: 'no-treeshake',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
},
|
|
44
|
+
load(id) {
|
|
45
|
+
if (id === PARTIAL_SOURCE_DIR) {
|
|
46
|
+
const entryPointsFileNames = getAllComponentFilenamesIn(ENTRY_POINTS_PATH);
|
|
47
|
+
return buildMockPartialModule(entryPointsFileNames);
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import http from 'http';
|
|
2
|
+
import https from 'https';
|
|
3
|
+
export default async function getContentMetadata(url, redirects = 0, originalUrl) {
|
|
4
|
+
if (redirects > 5) {
|
|
5
|
+
throw new Error(`Hit too many redirects to HEAD requests for ${originalUrl}`);
|
|
6
|
+
}
|
|
7
|
+
return new Promise((resolve, reject) => {
|
|
8
|
+
const protocolAPI = url.startsWith('https://') ? https : http;
|
|
9
|
+
protocolAPI
|
|
10
|
+
.request(url, {
|
|
11
|
+
method: 'HEAD',
|
|
12
|
+
headers: {
|
|
13
|
+
// Keep this user agent, so we don't get 403s from the request
|
|
14
|
+
['User-Agent']: 'cms-dev-server',
|
|
15
|
+
},
|
|
16
|
+
}, res => {
|
|
17
|
+
// Use a lib to better follow various redirects?
|
|
18
|
+
if (res.statusCode >= 300 &&
|
|
19
|
+
res.statusCode < 400 &&
|
|
20
|
+
res.headers.location) {
|
|
21
|
+
console.log(`Redirecting to ${res.headers.location} (from ${url})`);
|
|
22
|
+
return resolve(getContentMetadata(res.headers.location, redirects + 1, originalUrl ?? url));
|
|
23
|
+
}
|
|
24
|
+
const portalIdHeader = res.headers['x-hs-hub-id'];
|
|
25
|
+
const contentId = res.headers['x-hs-content-id'];
|
|
26
|
+
if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
|
|
27
|
+
return reject(new Error(`There were multiple hub ID or content ID headers in the HEAD request to ${url}`));
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const portalId = parseInt(portalIdHeader, 10);
|
|
31
|
+
if (res.statusCode !== 200) {
|
|
32
|
+
return reject(new Error(`${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url}. ${res.statusCode === 429 && res.headers['retry-after']
|
|
33
|
+
? `Retry after ${res.headers['retry-after']} seconds.`
|
|
34
|
+
: ''}`));
|
|
35
|
+
}
|
|
36
|
+
else if (!portalId || !contentId) {
|
|
37
|
+
return reject(new Error(`Missing hub ID or content ID headers on HEAD request to ${url}`));
|
|
38
|
+
}
|
|
39
|
+
else if (isNaN(portalId)) {
|
|
40
|
+
return reject(new Error(`Hub ID from the HEAD request is not a number: '${portalId}' (${url})`));
|
|
41
|
+
}
|
|
42
|
+
return resolve({ portalId, contentId });
|
|
43
|
+
}
|
|
44
|
+
})
|
|
45
|
+
.on('error', err => {
|
|
46
|
+
console.error(err);
|
|
47
|
+
reject(err);
|
|
48
|
+
})
|
|
49
|
+
.end();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
@@ -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-components');
|
|
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,28 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import url from 'url';
|
|
3
|
+
import { normalizePath } from 'vite';
|
|
4
|
+
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
5
|
+
import renderModule from '../lib/renderModule.js';
|
|
6
|
+
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
7
|
+
const moduleRouteHandler = async (request, response) => {
|
|
8
|
+
const { webRoot, viteServer } = request.app.locals;
|
|
9
|
+
const moduleName = request.params.moduleName;
|
|
10
|
+
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
11
|
+
const modulePath = normalizePath(path.resolve(webRoot, 'components/modules/', moduleName));
|
|
12
|
+
try {
|
|
13
|
+
const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, null, fullOriginalUrlFromRequest(request));
|
|
14
|
+
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer);
|
|
15
|
+
const html = htmlShell
|
|
16
|
+
.replace('<!--headend-->', cssNeeded)
|
|
17
|
+
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
18
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
console.error(e);
|
|
22
|
+
viteServer.ssrFixStacktrace(e);
|
|
23
|
+
response
|
|
24
|
+
.status(500)
|
|
25
|
+
.end(`Error rendering module (${moduleName})\n\n${e.stack}`);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
export default moduleRouteHandler;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import url from 'url';
|
|
3
|
+
import { normalizePath } from 'vite';
|
|
4
|
+
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
5
|
+
import renderPartial from '../lib/renderPartial.js';
|
|
6
|
+
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
7
|
+
const partialRouteHandler = async (request, response) => {
|
|
8
|
+
const { webRoot, viteServer } = request.app.locals;
|
|
9
|
+
const partialName = request.params.partial;
|
|
10
|
+
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
11
|
+
const partialPath = normalizePath(path.resolve(webRoot, 'components/partials/', partialName));
|
|
12
|
+
try {
|
|
13
|
+
const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request));
|
|
14
|
+
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderContext, viteServer);
|
|
15
|
+
const html = htmlShell
|
|
16
|
+
.replace('<!--headend-->', cssNeeded)
|
|
17
|
+
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
18
|
+
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
console.error(e);
|
|
22
|
+
viteServer.ssrFixStacktrace(e);
|
|
23
|
+
response
|
|
24
|
+
.status(500)
|
|
25
|
+
.end(`Error rendering partial (${partialName})\n\n${e.stack}`);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
export default partialRouteHandler;
|
|
@@ -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
|
+
}
|
package/dist/run.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { getDevServerCommandLineOptions } from './lib/cli.js';
|
|
3
|
+
import createDevServer from './createDevServer.js';
|
|
4
|
+
const { webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption } = getDevServerCommandLineOptions(process.argv);
|
|
5
|
+
if (!webRoot) {
|
|
6
|
+
throw new Error(`No web root path argument specified`);
|
|
7
|
+
}
|
|
8
|
+
createDevServer(webRoot, hubspotCliConfigPathOption, hubspotCliAccountNameOption);
|
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hubspot/cms-dev-server",
|
|
3
|
+
"version": "0.2.11",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/createViteDevServer.js",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=16.x"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "tsc --build && npm run copy-html",
|
|
12
|
+
"copy-html": "copyfiles -u 1 'src/html/**' 'dist'",
|
|
13
|
+
"clean": "tsc --build --clean",
|
|
14
|
+
"dev": "nodemon --exec 'ts-node-esm --transpileOnly runWhenDeveloping.ts'",
|
|
15
|
+
"dev-inspect": "nodemon --exec 'node --loader ts-node/esm --inspect runWhenDeveloping.ts'",
|
|
16
|
+
"es-watch": "esbuild --outfile=dist-esbuild/runWhenDeveloping.cjs --bundle --watch --platform=node --external:fsevents --external:vite --external:react-refresh runWhenDeveloping.ts",
|
|
17
|
+
"package": "npm run build && npm pack",
|
|
18
|
+
"prepare": "npm run build",
|
|
19
|
+
"runBuild": "node run.mjs",
|
|
20
|
+
"test": "NODE_ENV=test vitest"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@hubspot/cli-lib": "^3.0.12",
|
|
24
|
+
"@hubspot/cms-components": "^0.2.11",
|
|
25
|
+
"@hubspot/cms-js-internal": "^0.2.11",
|
|
26
|
+
"@vitejs/plugin-react": "^2.0.0",
|
|
27
|
+
"ansi-to-html": "0.7.x",
|
|
28
|
+
"express": "^4.17.3",
|
|
29
|
+
"react": "^18.1.0",
|
|
30
|
+
"react-dom": "^18.1.0",
|
|
31
|
+
"request": "^2.88.2",
|
|
32
|
+
"typescript": "~4.7.0",
|
|
33
|
+
"vite": "^3.0.2",
|
|
34
|
+
"vite-plugin-inspect": "^0.4.3"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/express": "^4.17.13",
|
|
38
|
+
"@types/react": "^18.0.0",
|
|
39
|
+
"@types/react-dom": "^18.0.0",
|
|
40
|
+
"copyfiles": "^2.4.1",
|
|
41
|
+
"nodemon": "^2.0.15",
|
|
42
|
+
"ts-node": "^10.7.0",
|
|
43
|
+
"vitest": "0.23.4"
|
|
44
|
+
},
|
|
45
|
+
"bin": {
|
|
46
|
+
"hs-cms-dev-server": "./dist/run.js"
|
|
47
|
+
},
|
|
48
|
+
"files": [
|
|
49
|
+
"dist/**/*"
|
|
50
|
+
],
|
|
51
|
+
"nodemonConfig": {
|
|
52
|
+
"ext": "js,json,ts,tsx,jsx,html",
|
|
53
|
+
"ignore": [
|
|
54
|
+
"testApp/*",
|
|
55
|
+
"dist/*"
|
|
56
|
+
],
|
|
57
|
+
"watch": [
|
|
58
|
+
"src",
|
|
59
|
+
"package.json",
|
|
60
|
+
"yarn.lock",
|
|
61
|
+
"tsconfig.json"
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
},
|
|
67
|
+
"gitHead": "12a8018212555054fb781aa65524179669bcc76d"
|
|
68
|
+
}
|