@hubspot/cms-dev-server 1.1.0-prerelease.5 → 1.1.0-prerelease.7
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/dist/lib/templates.js +2 -3
- package/dist/plugins/devMockClientEntryPlugin.js +52 -0
- package/dist/proxyPage/proxyPage.js +1 -1
- package/dist/routes/proxyPage.js +205 -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 +8 -4
- package/dist/lib/createIslandsGlobalJsForClientInDev.js +0 -32
- package/dist/lib/traverseFieldsJson.js +0 -78
- package/dist/render/renderOnServer.js +0 -40
- package/dist/render/renderOnServer.test.js +0 -24
- package/dist/render/renderStreamToPromise.js +0 -35
- package/dist/resolveSharedDeps.js +0 -28
package/LICENSE
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Copyright 2022 HubSpot, Inc.
|
|
2
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
+
you may not use this file except in compliance with the License.
|
|
4
|
+
You may obtain a copy of the License at
|
|
5
|
+
|
|
6
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
|
|
8
|
+
Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
See the License for the specific language governing permissions and
|
|
12
|
+
limitations under the License.
|
package/dist/lib/templates.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/* hs-eslint ignored failing-rules */
|
|
2
2
|
/* eslint-disable @typescript-eslint/no-shadow */
|
|
3
3
|
import { promises as fsPromises } from 'fs';
|
|
4
|
-
import {
|
|
4
|
+
import { createIslandsGlobalJsForClientInDev, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
|
|
5
5
|
const { readFile } = fsPromises;
|
|
6
6
|
const ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK = `<script type="module">
|
|
7
7
|
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
|
|
@@ -25,9 +25,8 @@ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath,
|
|
|
25
25
|
let htmlTemplate;
|
|
26
26
|
if (renderContext.islands.length) {
|
|
27
27
|
htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title);
|
|
28
|
-
const sortedIslandRoots = sortIslandRootsByPriority(renderContext.islands);
|
|
29
28
|
htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
|
|
30
|
-
${createIslandsGlobalJsForClientInDev(
|
|
29
|
+
${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
|
|
31
30
|
</script>
|
|
32
31
|
${getServerGlobalsToInject(renderContext.pageUrl)}
|
|
33
32
|
`);
|
|
@@ -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) {
|
|
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
|
+
}
|
|
@@ -98,7 +98,7 @@ export default async function proxySpecificPage(response, portalId, contentId, w
|
|
|
98
98
|
const { previewKey } = previewInfo;
|
|
99
99
|
const pageHtml = await makeProxyPreviewRequest(accountId, urlToProxy, previewKey, contentId);
|
|
100
100
|
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
101
|
-
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-
|
|
101
|
+
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-components');
|
|
102
102
|
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
103
103
|
const numPlaceholders = localRenderPlaceholders.length;
|
|
104
104
|
let numJsRenderFailures = 0;
|
|
@@ -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;
|
package/dist/run.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import createDevServer from './src/createDevServer.js';
|
|
3
|
+
import { dirname } from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
const packageRoot = dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
const webRoot = process.argv[2];
|
|
7
|
+
if (!webRoot) {
|
|
8
|
+
throw new Error(`No web root path argument specified`);
|
|
9
|
+
}
|
|
10
|
+
createDevServer(packageRoot, webRoot);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
function EmptyModulesList({ webRoot }) {
|
|
3
|
+
return (_jsxs("p", { children: ["No modules in ", _jsxs("code", { children: [webRoot, "components/modules"] })] }));
|
|
4
|
+
}
|
|
5
|
+
function ModuleLinkInLI({ moduleName }) {
|
|
6
|
+
return (_jsx("li", { children: _jsx("a", { href: `/module/${moduleName}`, children: moduleName }) }));
|
|
7
|
+
}
|
|
8
|
+
function ModulesList({ webRoot, moduleNames }) {
|
|
9
|
+
if (moduleNames.length === 0) {
|
|
10
|
+
return _jsx(EmptyModulesList, { webRoot: webRoot });
|
|
11
|
+
}
|
|
12
|
+
return (_jsx("ul", { children: moduleNames.map((moduleName) => (_jsx(ModuleLinkInLI, { moduleName: moduleName }, moduleName))) }));
|
|
13
|
+
}
|
|
14
|
+
export default ModulesList;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
function EmptyPartialsList({ webRoot }) {
|
|
3
|
+
return (_jsxs("p", { children: ["No partials in ", _jsxs("code", { children: [webRoot, "components/partials"] })] }));
|
|
4
|
+
}
|
|
5
|
+
function PartialLinkInLI({ partialName }) {
|
|
6
|
+
return (_jsx("li", { children: _jsx("a", { href: `/partial/${partialName}`, children: partialName }) }));
|
|
7
|
+
}
|
|
8
|
+
export default function PartialsList({ webRoot, partialNames }) {
|
|
9
|
+
if (partialNames.length === 0) {
|
|
10
|
+
return _jsx(EmptyPartialsList, { webRoot: webRoot });
|
|
11
|
+
}
|
|
12
|
+
return (_jsx("ul", { children: partialNames.map((partialName) => (_jsx(PartialLinkInLI, { partialName: partialName }, partialName))) }));
|
|
13
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import { createServer as createViteServer } from 'vite';
|
|
3
|
+
import { default as react } from '@vitejs/plugin-react';
|
|
4
|
+
import createDevServerRoutes from './routes/createDevServerRoutes.js';
|
|
5
|
+
import devMockClientEntryPlugin from './plugins/devMockClientEntryPlugin.js';
|
|
6
|
+
import { resolveIslandPlugin, resolveWebRootDepsPlugin, } from '@hubspot/cms-js-internal';
|
|
7
|
+
const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD;
|
|
8
|
+
const BASE_PATH = '/';
|
|
9
|
+
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
|
|
10
|
+
async function createDevServer(packageRoot, webRoot) {
|
|
11
|
+
const expressServer = express();
|
|
12
|
+
const viteServer = await createViteServer({
|
|
13
|
+
appType: 'custom',
|
|
14
|
+
server: {
|
|
15
|
+
middlewareMode: true,
|
|
16
|
+
origin: `http://localhost:${PORT}`,
|
|
17
|
+
},
|
|
18
|
+
ssr: {
|
|
19
|
+
// TODO: might need more entries here to get things to resolve through
|
|
20
|
+
// resolveWebRootDepsPlugin
|
|
21
|
+
noExternal: '@hubspot/cms-components',
|
|
22
|
+
},
|
|
23
|
+
optimizeDeps: {
|
|
24
|
+
include: ['react', 'react-dom', 'react-dom/client'],
|
|
25
|
+
},
|
|
26
|
+
build: {},
|
|
27
|
+
plugins: [
|
|
28
|
+
react({ jsxRuntime: 'automatic' }),
|
|
29
|
+
// @ts-ignore
|
|
30
|
+
devMockClientEntryPlugin(webRoot),
|
|
31
|
+
// @ts-ignore
|
|
32
|
+
resolveIslandPlugin(),
|
|
33
|
+
resolveWebRootDepsPlugin(webRoot, packageRoot),
|
|
34
|
+
],
|
|
35
|
+
});
|
|
36
|
+
expressServer.locals.devServerHost = 'localhost';
|
|
37
|
+
expressServer.locals.devServerPort = PORT;
|
|
38
|
+
expressServer.locals.packageRoot = packageRoot;
|
|
39
|
+
expressServer.locals.webRoot = webRoot;
|
|
40
|
+
expressServer.locals.viteServer = viteServer;
|
|
41
|
+
expressServer.use(BASE_PATH, await createDevServerRoutes(packageRoot, webRoot, viteServer));
|
|
42
|
+
expressServer.listen(PORT);
|
|
43
|
+
console.log(`HubSpot CMS dev server listening at http://localhost:${PORT}`);
|
|
44
|
+
}
|
|
45
|
+
export default createDevServer;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const rewriteAbsoluteJsAndCssPaths = (body, host, protocol = 'https://') => {
|
|
2
|
+
// TODO, do we need to worry about any fully relative references? (./whatever/...)
|
|
3
|
+
// Maybe the renderer doesn't typically output those, and when customers do that manually
|
|
4
|
+
// it (probably?) is after the `<base>` element?
|
|
5
|
+
return body.replace(/(src|href)="(\/[^/])/g, `$1="${protocol}${host}$2`);
|
|
6
|
+
};
|
|
7
|
+
export const addBaseTag = (html, urlToProxy) => {
|
|
8
|
+
const baseDomain = new URL(urlToProxy).origin;
|
|
9
|
+
return html.replace('<head>', `<head>\n<base href="${baseDomain}">\n`);
|
|
10
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { COMPONENT_EXTENSIONS } from '@hubspot/cms-js-internal';
|
|
2
|
+
export const findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
|
|
3
|
+
for (let extension of COMPONENT_EXTENSIONS) {
|
|
4
|
+
const pathToTry = `${modulePathNoExtension}${extension}`;
|
|
5
|
+
if (moduleGraph.fileToModulesMap.has(pathToTry)) {
|
|
6
|
+
return pathToTry;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
const localJsRenderStartString = '<!-- proxy local render of "';
|
|
2
|
+
// const localJsRenderStartRegex = /<!-- proxy local render of "([^"]+)"/;
|
|
3
|
+
const localJsRenderEndString = 'end proxy local render -->';
|
|
4
|
+
export const findLocalRenderPlaceholders = (body) => {
|
|
5
|
+
let offsetSoFar = 0;
|
|
6
|
+
const result = [];
|
|
7
|
+
while (offsetSoFar < body.length && offsetSoFar !== -1) {
|
|
8
|
+
// Get start of local render block
|
|
9
|
+
const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
|
|
10
|
+
offsetSoFar = startOffset;
|
|
11
|
+
if (startOffset >= 0) {
|
|
12
|
+
const nextNewlineOffset = body.indexOf('\n', startOffset + localJsRenderStartString.length);
|
|
13
|
+
const pathEndOffset = body.indexOf('"', startOffset + localJsRenderStartString.length);
|
|
14
|
+
const nearestNewlineOrQuoteAfterBlockOpen = Math.min(nextNewlineOffset, pathEndOffset);
|
|
15
|
+
// Keep on moving our "where we've scanned so far" pointer
|
|
16
|
+
offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
|
|
17
|
+
if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
|
|
18
|
+
// Pull the path out of double quotes after the block opening
|
|
19
|
+
const path = body.substring(startOffset + localJsRenderStartString.length, pathEndOffset);
|
|
20
|
+
offsetSoFar = pathEndOffset + 1;
|
|
21
|
+
// console.log(`${startOffset}: path = ${path}`);
|
|
22
|
+
// If we're in a valid bloc so far that exists and has a path...
|
|
23
|
+
if (startOffset >= 0 && path) {
|
|
24
|
+
const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);
|
|
25
|
+
const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
|
|
26
|
+
offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
|
|
27
|
+
// Make sure that there is an ending to the block and there is not another
|
|
28
|
+
// HTML end comment string before it
|
|
29
|
+
if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
|
|
30
|
+
// Then pull out the JSON in the middle and try to parse it
|
|
31
|
+
const jsonString = body
|
|
32
|
+
.substring(pathEndOffset + 1, endOffset)
|
|
33
|
+
.trim();
|
|
34
|
+
// console.log(`${endOffset}: jsonString = ${jsonString}`);
|
|
35
|
+
try {
|
|
36
|
+
const json = JSON.parse(jsonString);
|
|
37
|
+
result.push({
|
|
38
|
+
startOffset,
|
|
39
|
+
endOffset: endOffset + localJsRenderEndString.length,
|
|
40
|
+
path,
|
|
41
|
+
json,
|
|
42
|
+
});
|
|
43
|
+
offsetSoFar = endOffset + localJsRenderEndString.length;
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
console.error(`Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`);
|
|
47
|
+
offsetSoFar = endOffset;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { findLocalRenderPlaceholders } from './proxyHelpers.js';
|
|
3
|
+
describe('proxyHelpers', () => {
|
|
4
|
+
describe('findLocalRenderPlaceholders', () => {
|
|
5
|
+
it('should do nothing with an empty string', () => {
|
|
6
|
+
const result = findLocalRenderPlaceholders('');
|
|
7
|
+
expect(result).toEqual([]);
|
|
8
|
+
});
|
|
9
|
+
it('should do nothing with a regular HTML comment', () => {
|
|
10
|
+
const result = findLocalRenderPlaceholders('<!-- -->');
|
|
11
|
+
expect(result).toEqual([]);
|
|
12
|
+
});
|
|
13
|
+
it('should do nothing with a regular HTML comment across newlines', () => {
|
|
14
|
+
const result = findLocalRenderPlaceholders(`<!--
|
|
15
|
+
-->`);
|
|
16
|
+
expect(result).toEqual([]);
|
|
17
|
+
});
|
|
18
|
+
it('should do nothing with a never ending HTML comment', () => {
|
|
19
|
+
const result = findLocalRenderPlaceholders(`<!--`);
|
|
20
|
+
expect(result).toEqual([]);
|
|
21
|
+
});
|
|
22
|
+
it('extracts placeholder with nothing before or after it', () => {
|
|
23
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
24
|
+
{
|
|
25
|
+
"the": "props",
|
|
26
|
+
"that": ["need", "to"],
|
|
27
|
+
"be": {
|
|
28
|
+
"passed": "along"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
end proxy local render -->`);
|
|
32
|
+
expect(result.length).toBe(1);
|
|
33
|
+
expect(result[0]).toMatchSnapshot();
|
|
34
|
+
});
|
|
35
|
+
it('extracts placeholder with some HTML around it', () => {
|
|
36
|
+
const result = findLocalRenderPlaceholders(`
|
|
37
|
+
<p>asdf</p>
|
|
38
|
+
<div>
|
|
39
|
+
<!-- proxy local render of "/some/path/to/entry.js"
|
|
40
|
+
{
|
|
41
|
+
"the": "props",
|
|
42
|
+
"that": ["need", "to"],
|
|
43
|
+
"be": {
|
|
44
|
+
"passed": "along"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
end proxy local render -->
|
|
48
|
+
</div>
|
|
49
|
+
|
|
50
|
+
<em>FIN</em>
|
|
51
|
+
`);
|
|
52
|
+
expect(result.length).toBe(1);
|
|
53
|
+
expect(result[0]).toMatchSnapshot();
|
|
54
|
+
});
|
|
55
|
+
it('extacts two placholder blocks immediately after one another', () => {
|
|
56
|
+
const result = findLocalRenderPlaceholders(`<p>asdf</p>
|
|
57
|
+
<div>
|
|
58
|
+
<!-- proxy local render of "/some/path/to/entry.js"
|
|
59
|
+
{
|
|
60
|
+
"the": "props",
|
|
61
|
+
"that": ["need", "to"],
|
|
62
|
+
"be": {
|
|
63
|
+
"passed": "along"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
end proxy local render --><!-- proxy local render of "/some/path/to/entry2.js"
|
|
67
|
+
{
|
|
68
|
+
"the": "props22222",
|
|
69
|
+
"that": ["need", "to"],
|
|
70
|
+
"be": {
|
|
71
|
+
"passed": "along"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
end proxy local render -->
|
|
75
|
+
</div>
|
|
76
|
+
|
|
77
|
+
<em>FIN</em>
|
|
78
|
+
`);
|
|
79
|
+
expect(result.length).toBe(2);
|
|
80
|
+
expect(result[0]).toMatchSnapshot();
|
|
81
|
+
expect(result[1]).toMatchSnapshot();
|
|
82
|
+
});
|
|
83
|
+
it('extacts a placeholder with empty json', () => {
|
|
84
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
85
|
+
{
|
|
86
|
+
}
|
|
87
|
+
end proxy local render -->`);
|
|
88
|
+
expect(result.length).toBe(1);
|
|
89
|
+
expect(result[0]).toMatchSnapshot();
|
|
90
|
+
});
|
|
91
|
+
it('extacts a placeholder with empty json - 2', () => {
|
|
92
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
93
|
+
{}
|
|
94
|
+
end proxy local render -->`);
|
|
95
|
+
expect(result.length).toBe(1);
|
|
96
|
+
expect(result[0]).toMatchSnapshot();
|
|
97
|
+
});
|
|
98
|
+
it('extacts one placholder after a broken incomplete path', () => {
|
|
99
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "incomplete path
|
|
100
|
+
-->
|
|
101
|
+
<!-- proxy local render of "/some/path/to/afterMissingPath.js"
|
|
102
|
+
{
|
|
103
|
+
}
|
|
104
|
+
end proxy local render -->`);
|
|
105
|
+
expect(result.length).toBe(1);
|
|
106
|
+
expect(result[0]).toMatchSnapshot();
|
|
107
|
+
});
|
|
108
|
+
it('extacts one placholder after a uncompleted regular HTML comment', () => {
|
|
109
|
+
const result = findLocalRenderPlaceholders(`<!-- WHATEVER
|
|
110
|
+
-->
|
|
111
|
+
<!-- proxy local render of "/some/path/to/afterBustedHtmlComment.js"
|
|
112
|
+
{
|
|
113
|
+
}
|
|
114
|
+
end proxy local render -->`);
|
|
115
|
+
expect(result.length).toBe(1);
|
|
116
|
+
expect(result[0]).toMatchSnapshot();
|
|
117
|
+
});
|
|
118
|
+
it('extacts one placeholder after one with broken missing json', () => {
|
|
119
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "path/Before/missingJson"
|
|
120
|
+
-->
|
|
121
|
+
<!-- proxy local render of "/some/path/to/afterMissingJson.js"
|
|
122
|
+
{
|
|
123
|
+
}
|
|
124
|
+
end proxy local render -->`);
|
|
125
|
+
expect(result.length).toBe(1);
|
|
126
|
+
expect(result[0]).toMatchSnapshot();
|
|
127
|
+
});
|
|
128
|
+
it('does not extact broken placeholder with invalid json', () => {
|
|
129
|
+
const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
|
|
130
|
+
Invalid json
|
|
131
|
+
}
|
|
132
|
+
end proxy local render -->`);
|
|
133
|
+
expect(result).toEqual([]);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { hasComponentExtension, removeComponentExtension, } from '@hubspot/cms-js-internal';
|
|
2
|
+
import { findFullPathInModuleGraph } from './moduleGraph.js';
|
|
3
|
+
async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl) {
|
|
4
|
+
// Need to make sure rendering happens in Vite SSR context
|
|
5
|
+
const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
6
|
+
let componentPathWithExtension;
|
|
7
|
+
let componentPathNoExtension;
|
|
8
|
+
// Support paths with or without an extension (do we need/want both?)
|
|
9
|
+
if (hasComponentExtension(componentPath)) {
|
|
10
|
+
componentPathWithExtension = componentPath;
|
|
11
|
+
componentPathNoExtension = removeComponentExtension(componentPath);
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
componentPathNoExtension = componentPath;
|
|
15
|
+
}
|
|
16
|
+
const { html, renderInfoContext } = await renderComponentOnServer(Component, props, pageUrl);
|
|
17
|
+
if (!componentPathWithExtension) {
|
|
18
|
+
componentPathWithExtension = findFullPathInModuleGraph(componentPathNoExtension, viteServer.moduleGraph);
|
|
19
|
+
if (!componentPathWithExtension) {
|
|
20
|
+
throw new Error(`Couldn't find full path to component: ${componentPathNoExtension}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
|
|
24
|
+
return { html, cssNeeded, renderInfoContext };
|
|
25
|
+
}
|
|
26
|
+
export default renderComponentWithCSS;
|