@hubspot/cms-dev-server 0.6.0 → 0.6.1
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/dist/index.js +0 -10
- package/dist/internalSsr.js +4 -7
- package/dist/run.js +43 -9
- package/dist/storybook/index.js +61 -46
- package/dist/{storybook → storybook-main}/main.js +24 -9
- package/dist/storybook-main/preview.js +20 -0
- package/package.json +11 -10
- package/types/storybook/getFieldsArgTypes.d.ts +1 -7
- package/types/storybook/moduleStory.d.ts +5 -2
- package/types/storybook/types.d.ts +11 -0
- package/dist/components/ModulesList.js +0 -14
- package/dist/components/PartialsList.js +0 -13
- package/dist/createDevServer.js +0 -162
- package/dist/createViteDevServer.js +0 -51
- package/dist/lib/cli.js +0 -27
- package/dist/lib/debug.js +0 -2
- package/dist/lib/errors.js +0 -22
- package/dist/lib/fullOriginalUrlFromRequest.js +0 -3
- package/dist/lib/httpsRedirectingServer.js +0 -48
- package/dist/lib/moduleGraph.js +0 -11
- package/dist/lib/proxyHelpers.js +0 -70
- package/dist/lib/proxyHelpers.test.js +0 -136
- package/dist/lib/renderComponentWithCSS.js +0 -26
- package/dist/lib/renderHelpers.js +0 -45
- package/dist/lib/renderModule.js +0 -56
- package/dist/lib/renderPartial.js +0 -15
- package/dist/lib/templates.js +0 -55
- package/dist/proxyPage/constants.js +0 -1
- package/dist/proxyPage/fetchContentMetadata.js +0 -59
- package/dist/proxyPage/fetchDomains.js +0 -29
- package/dist/proxyPage/fetchPreviewInfo.js +0 -37
- package/dist/proxyPage/proxyPage.js +0 -174
- package/dist/proxyPage/renderLocalError.js +0 -27
- package/dist/proxyPage/utils.js +0 -38
- package/dist/routes/createDevServerRoutes.js +0 -43
- package/dist/routes/homeRouteHandler.js +0 -12
- package/dist/routes/linksToAllModulesRouteHandler.js +0 -10
- package/dist/routes/linksToAllPartialsRouteHandler.js +0 -10
- package/dist/routes/module.js +0 -41
- package/dist/routes/partial.js +0 -30
- package/dist/routes/proxyPageResourceRedirect.js +0 -22
- package/dist/routes/proxyPageRouteHandler.js +0 -40
- package/dist/routes/proxyPathPageResourceRedirect.js +0 -36
- package/dist/routes/proxyPathPageRouteHandler.js +0 -43
- package/dist/shadowDevServer/createShadowDevServerRoutes.js +0 -63
- package/dist/shadowDevServer/startShadowDevServer.js +0 -31
- package/dist/storybook/getFieldsArgTypes.js +0 -54
- package/dist/storybook/getFieldsArgTypes.test.js +0 -91
- package/dist/storybook/getNestedFieldObjectForArgs.js +0 -22
- package/dist/storybook/getNestedFieldObjectForArgs.test.js +0 -40
- package/dist/storybook/moduleStory.js +0 -61
- package/dist/storybook/preview.js +0 -9
- package/dist/storybook/types.js +0 -1
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import renderComponentWithCSS from './renderComponentWithCSS.js';
|
|
2
|
-
import { logPartialInfo } from './renderHelpers.js';
|
|
3
|
-
async function renderPartial(viteServer, partialPath, props, pageUrl, environmentConfig) {
|
|
4
|
-
logPartialInfo(partialPath, props);
|
|
5
|
-
const componentModule = await viteServer.ssrLoadModule(partialPath);
|
|
6
|
-
if (!componentModule) {
|
|
7
|
-
throw new Error(`Couldn't find partial: ${partialPath}`);
|
|
8
|
-
}
|
|
9
|
-
const Component = componentModule.default;
|
|
10
|
-
if (!Component) {
|
|
11
|
-
throw new Error(`Couldn't find default export on partial: ${partialPath}`);
|
|
12
|
-
}
|
|
13
|
-
return renderComponentWithCSS(viteServer, partialPath, Component, props, pageUrl, environmentConfig);
|
|
14
|
-
}
|
|
15
|
-
export default renderPartial;
|
package/dist/lib/templates.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/* hs-eslint ignored failing-rules */
|
|
2
|
-
/* eslint-disable @typescript-eslint/no-shadow */
|
|
3
|
-
import { promises as fsPromises } from 'fs';
|
|
4
|
-
import { createIslandsGlobalJsForClientInDev, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
|
|
5
|
-
const { readFile } = fsPromises;
|
|
6
|
-
const generateIslandSetupScriptBlock = () => {
|
|
7
|
-
return `<script type="module">
|
|
8
|
-
import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
|
|
9
|
-
initConfigSingletonFromJSON(window.__hsEnvConfig);
|
|
10
|
-
</script>
|
|
11
|
-
<script type="module">
|
|
12
|
-
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
|
|
13
|
-
setupIslandHydration();
|
|
14
|
-
</script>
|
|
15
|
-
`;
|
|
16
|
-
};
|
|
17
|
-
const createdPlainHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
|
|
18
|
-
const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
|
|
19
|
-
return htmlTemplateBase.replace('<!--title-->', title).replace('<!--bodyend-->', `
|
|
20
|
-
${globalScriptBlock}
|
|
21
|
-
<!--bodyend-->`);
|
|
22
|
-
};
|
|
23
|
-
const createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
|
|
24
|
-
let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
|
|
25
|
-
htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
|
|
26
|
-
${generateIslandSetupScriptBlock()}
|
|
27
|
-
<!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
|
|
28
|
-
<!--islandsglobal-->
|
|
29
|
-
`);
|
|
30
|
-
return htmlTemplate;
|
|
31
|
-
};
|
|
32
|
-
export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer) => {
|
|
33
|
-
let htmlTemplate;
|
|
34
|
-
if (renderContext.islands.length) {
|
|
35
|
-
const globalScriptBlock = getServerGlobalsToInject(renderContext.environmentConfig, renderContext.pageUrl);
|
|
36
|
-
htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
|
|
37
|
-
htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
|
|
38
|
-
${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
|
|
39
|
-
</script>
|
|
40
|
-
`);
|
|
41
|
-
}
|
|
42
|
-
else {
|
|
43
|
-
const globalScriptBlock = getServerGlobalsToInject(renderContext.environmentConfig);
|
|
44
|
-
htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
|
|
45
|
-
}
|
|
46
|
-
return viteServer.transformIndexHtml(url, htmlTemplate);
|
|
47
|
-
};
|
|
48
|
-
export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer) => {
|
|
49
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
50
|
-
const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
51
|
-
const islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock());
|
|
52
|
-
return `${islandRuntimeScript}
|
|
53
|
-
<script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
|
|
54
|
-
`;
|
|
55
|
-
};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export const VALID_PROXY_DOMAIN_SUFFIXES = ['localhost', 'hslocal.net'];
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/* hs-eslint ignored failing-rules */
|
|
2
|
-
/* eslint-disable require-await */
|
|
3
|
-
import http from 'http';
|
|
4
|
-
import https from 'https';
|
|
5
|
-
export default async function fetchContentMetadata(url, redirects = 0, originalUrl) {
|
|
6
|
-
if (redirects > 5) {
|
|
7
|
-
throw new Error(`Hit too many redirects to HEAD requests for ${originalUrl}`);
|
|
8
|
-
}
|
|
9
|
-
return new Promise((resolve, reject) => {
|
|
10
|
-
const protocolAPI = url.startsWith('https://') ? https : http;
|
|
11
|
-
protocolAPI
|
|
12
|
-
.request(url, {
|
|
13
|
-
method: 'HEAD',
|
|
14
|
-
headers: {
|
|
15
|
-
// Keep this user agent, so we don't get 403s from the request
|
|
16
|
-
['User-Agent']: 'cms-dev-server',
|
|
17
|
-
},
|
|
18
|
-
}, async (res) => {
|
|
19
|
-
// Use a lib to better follow various redirects?
|
|
20
|
-
if (res.statusCode >= 300 &&
|
|
21
|
-
res.statusCode < 400 &&
|
|
22
|
-
res.headers.location) {
|
|
23
|
-
console.log(`Redirecting to ${res.headers.location} (from ${url})`);
|
|
24
|
-
return resolve(fetchContentMetadata(res.headers.location, redirects + 1, originalUrl ?? url));
|
|
25
|
-
}
|
|
26
|
-
const portalIdHeader = res.headers['x-hs-hub-id'];
|
|
27
|
-
const contentId = res.headers['x-hs-content-id'];
|
|
28
|
-
if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
|
|
29
|
-
return reject(new Error(`There were multiple hub ID or content ID headers in the HEAD request to ${url}`));
|
|
30
|
-
}
|
|
31
|
-
else {
|
|
32
|
-
const portalId = parseInt(portalIdHeader, 10);
|
|
33
|
-
if (res.statusCode !== 200) {
|
|
34
|
-
return reject(new Error(`${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url}. ${res.statusCode === 429 && res.headers['retry-after']
|
|
35
|
-
? `Retry after ${res.headers['retry-after']} seconds.`
|
|
36
|
-
: ''}`));
|
|
37
|
-
}
|
|
38
|
-
else if (!portalId || !contentId) {
|
|
39
|
-
return reject(new Error(`Missing hub ID or content ID headers on HEAD request to ${url}`));
|
|
40
|
-
}
|
|
41
|
-
else if (isNaN(portalId)) {
|
|
42
|
-
return reject(new Error(`Hub ID from the HEAD request is not a number: '${portalId}' (${url})`));
|
|
43
|
-
}
|
|
44
|
-
// TODO, the hubs-hublets/hublets/find/<portalId> API is internal auth only.🤔...
|
|
45
|
-
// Prior implementation of fetchHubletForPortalId that would work execept for an internal auth issue:
|
|
46
|
-
// https://git.hubteam.com/HubSpot/cms-js-platform/blob/ef6e8029df6c09fe30d65a80073606f41ca324a6/cms-dev-server/src/proxyPage/fetchHubletForPortalId.ts
|
|
47
|
-
//
|
|
48
|
-
// const hublet = await fetchHubletForPortalId(portalId);
|
|
49
|
-
const hublet = 'na1';
|
|
50
|
-
return resolve({ portalId, contentId, hublet });
|
|
51
|
-
}
|
|
52
|
-
})
|
|
53
|
-
.on('error', err => {
|
|
54
|
-
console.error(err);
|
|
55
|
-
reject(err);
|
|
56
|
-
})
|
|
57
|
-
.end();
|
|
58
|
-
});
|
|
59
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { get as hsGet } from '@hubspot/cli-lib/http.js';
|
|
2
|
-
import { isMissingScopeError, MissingScopeError } from '../lib/errors.js';
|
|
3
|
-
export async function fetchDomains(portalId) {
|
|
4
|
-
try {
|
|
5
|
-
// Works with oauth if content-custom-domain-read scope present (from cms.domains.read scope group)
|
|
6
|
-
const result = (await hsGet(portalId, {
|
|
7
|
-
uri: `/cms/v3/domains`,
|
|
8
|
-
query: { portalId },
|
|
9
|
-
json: true,
|
|
10
|
-
}));
|
|
11
|
-
return result.results;
|
|
12
|
-
}
|
|
13
|
-
catch (error) {
|
|
14
|
-
if (isMissingScopeError(error)) {
|
|
15
|
-
throw new MissingScopeError(error);
|
|
16
|
-
}
|
|
17
|
-
throw error;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
export async function fetchWebsiteDomainNames(portalId) {
|
|
21
|
-
const domains = await fetchDomains(portalId);
|
|
22
|
-
const filteredDomains = domains.filter(domain => {
|
|
23
|
-
return (domain.isUsedForBlogPost ||
|
|
24
|
-
domain.isUsedForSitePage ||
|
|
25
|
-
domain.isUsedForLandingPage);
|
|
26
|
-
});
|
|
27
|
-
const domainNames = filteredDomains.map(r => r.domain);
|
|
28
|
-
return domainNames;
|
|
29
|
-
}
|
|
@@ -1,37 +0,0 @@
|
|
|
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
|
-
};
|
|
@@ -1,174 +0,0 @@
|
|
|
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, getEnv } 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
|
-
import { buildStaticEnvConfig, } from '@hubspot/cms-components/config';
|
|
16
|
-
export const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
|
|
17
|
-
const url = new URL(urlToProxy);
|
|
18
|
-
console.log(`Proxying request to ${url.href}`, {
|
|
19
|
-
previewKey,
|
|
20
|
-
contentId,
|
|
21
|
-
});
|
|
22
|
-
let proxiedQueryParams = {};
|
|
23
|
-
// Convert searchParams to object param format hsGet/request expects
|
|
24
|
-
for (const queryKey of url.searchParams.keys()) {
|
|
25
|
-
const values = url.searchParams.getAll(queryKey);
|
|
26
|
-
if (values.length > 1) {
|
|
27
|
-
proxiedQueryParams[queryKey] = values;
|
|
28
|
-
}
|
|
29
|
-
else {
|
|
30
|
-
proxiedQueryParams[queryKey] = values[0];
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
proxiedQueryParams = {
|
|
34
|
-
...proxiedQueryParams,
|
|
35
|
-
hs_preview: `${previewKey}-${contentId}`,
|
|
36
|
-
hsLocalProxy: true,
|
|
37
|
-
};
|
|
38
|
-
const result = hsGet(accountId, {
|
|
39
|
-
baseUrl: url.origin,
|
|
40
|
-
uri: url.pathname,
|
|
41
|
-
query: proxiedQueryParams,
|
|
42
|
-
json: false,
|
|
43
|
-
useQuerystring: true,
|
|
44
|
-
});
|
|
45
|
-
return result.catch(error => {
|
|
46
|
-
if (error.statusCode >= 400 &&
|
|
47
|
-
error.statusCode < 500 &&
|
|
48
|
-
!!error.response.body) {
|
|
49
|
-
return error.response.body;
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
throw error;
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
};
|
|
56
|
-
const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer, pageUrl, environmentConfig, hsProjectJsonProjectName, webRootProjectComponent) => {
|
|
57
|
-
const { path: placeholderPath } = localRenderPlaceholder;
|
|
58
|
-
const [__projectIdentifier, projectFolder, projectComponentFolder, componentFolder, componentTypeFolder, componentFileName,] = placeholderPath.split('/');
|
|
59
|
-
const partialPath = `${componentFolder}/${componentTypeFolder}/`;
|
|
60
|
-
if (projectFolder !== hsProjectJsonProjectName) {
|
|
61
|
-
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}.`);
|
|
62
|
-
}
|
|
63
|
-
else if (projectComponentFolder !== webRootProjectComponent) {
|
|
64
|
-
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}.`);
|
|
65
|
-
}
|
|
66
|
-
const resolvedPath = path.resolve(webRoot, partialPath, componentFileName);
|
|
67
|
-
if (placeholderPath.startsWith('/fake/path/to/')) {
|
|
68
|
-
return fakeRenderJsComponent(indexForThisRender);
|
|
69
|
-
}
|
|
70
|
-
else if (partialPath === ENTRY_POINTS_PATH) {
|
|
71
|
-
return renderPartial(viteServer, resolvedPath, localRenderPlaceholder.json, pageUrl, environmentConfig);
|
|
72
|
-
}
|
|
73
|
-
else if (partialPath === MODULE_FOLDER_PATH) {
|
|
74
|
-
return renderModule(viteServer, resolvedPath, localRenderPlaceholder.json, pageUrl, environmentConfig);
|
|
75
|
-
}
|
|
76
|
-
else {
|
|
77
|
-
throw new Error(`Unimplemented render of ${placeholderPath}.`);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
export default async function proxySpecificPage(response, portalId, hublet, contentId, webRoot, viteServer, projectName, projectComponentPath, urlToProxy, fullOriginalUrl) {
|
|
81
|
-
let accountId;
|
|
82
|
-
let proxyEnv;
|
|
83
|
-
try {
|
|
84
|
-
accountId = getAccountId(portalId);
|
|
85
|
-
if (accountId === null) {
|
|
86
|
-
throw new Error();
|
|
87
|
-
}
|
|
88
|
-
proxyEnv = getEnv(accountId);
|
|
89
|
-
}
|
|
90
|
-
catch (e) {
|
|
91
|
-
response
|
|
92
|
-
.status(500)
|
|
93
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
if (!accountId) {
|
|
97
|
-
response
|
|
98
|
-
.status(500)
|
|
99
|
-
.end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
|
|
104
|
-
const { previewKey } = previewInfo;
|
|
105
|
-
const pageHtml = await makeProxyPreviewRequest(accountId, urlToProxy, previewKey, contentId);
|
|
106
|
-
const environmentConfig = buildStaticEnvConfig(portalId, hublet, proxyEnv, false);
|
|
107
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
108
|
-
const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-components');
|
|
109
|
-
const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
|
|
110
|
-
const numPlaceholders = localRenderPlaceholders.length;
|
|
111
|
-
let numJsRenderFailures = 0;
|
|
112
|
-
let islands = [];
|
|
113
|
-
const renderPromisesByChunkIndex = new Array(numPlaceholders);
|
|
114
|
-
if (localRenderPlaceholders.length > 0) {
|
|
115
|
-
let offsetSoFar = 0;
|
|
116
|
-
const pageChunks = new Array(numPlaceholders + 1);
|
|
117
|
-
for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
|
|
118
|
-
const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
|
|
119
|
-
pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
|
|
120
|
-
const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer, fullOriginalUrl, environmentConfig, projectName, projectComponentPath);
|
|
121
|
-
renderPromisesByChunkIndex[indexForThisRender] = renderPromise
|
|
122
|
-
.then(promiseResult => {
|
|
123
|
-
// eslint-disable-next-line prefer-const
|
|
124
|
-
let { html, cssNeeded, renderContext } = promiseResult;
|
|
125
|
-
console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
|
|
126
|
-
if (renderContext.islands.length > 0) {
|
|
127
|
-
islands = islands.concat(renderContext.islands);
|
|
128
|
-
}
|
|
129
|
-
if (cssNeeded) {
|
|
130
|
-
return `${cssNeeded}\n${html}`;
|
|
131
|
-
}
|
|
132
|
-
return html;
|
|
133
|
-
})
|
|
134
|
-
.catch(e => {
|
|
135
|
-
numJsRenderFailures += 1;
|
|
136
|
-
console.error(e);
|
|
137
|
-
return renderLocalError(localRenderPlaceholder.path, e);
|
|
138
|
-
});
|
|
139
|
-
offsetSoFar = localRenderPlaceholder.endOffset;
|
|
140
|
-
}
|
|
141
|
-
// Last chunk from end of last placeholder to end of HTML
|
|
142
|
-
pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
|
|
143
|
-
response.writeHead(200);
|
|
144
|
-
for (let i = 0; i < localRenderPlaceholders.length; i++) {
|
|
145
|
-
const chunk = pageChunks[i];
|
|
146
|
-
response.write(chunk);
|
|
147
|
-
const foobar = await renderPromisesByChunkIndex[i];
|
|
148
|
-
// console.log("JS rendered chunk", i, foobar);
|
|
149
|
-
response.write(foobar);
|
|
150
|
-
}
|
|
151
|
-
response.write(getServerGlobalsToInject(environmentConfig, fullOriginalUrl));
|
|
152
|
-
if (islands.length > 0) {
|
|
153
|
-
const sortedIslandRoots = sortIslandRootsByPriority(islands);
|
|
154
|
-
const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer);
|
|
155
|
-
response.write(islandRuntimeAndGlobalScriptHtml);
|
|
156
|
-
}
|
|
157
|
-
// Write last string chunk located after last placeholder
|
|
158
|
-
response.write(pageChunks[pageChunks.length - 1]);
|
|
159
|
-
response.end();
|
|
160
|
-
}
|
|
161
|
-
else {
|
|
162
|
-
response.writeHead(200);
|
|
163
|
-
response.write(pageHtml);
|
|
164
|
-
response.end();
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
catch (error) {
|
|
168
|
-
// TODO change error.stack to error.message before we publish
|
|
169
|
-
response
|
|
170
|
-
.status(500)
|
|
171
|
-
.end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
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
|
-
};
|
package/dist/proxyPage/utils.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
/* hs-eslint ignored failing-rules */
|
|
2
|
-
/* eslint-disable prefer-promise-reject-errors */
|
|
3
|
-
import { createEmptyServerRenderContext } 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: createEmptyServerRenderContext(),
|
|
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
|
-
};
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
/* hs-eslint ignored failing-rules */
|
|
2
|
-
/* eslint-disable require-await */
|
|
3
|
-
import { Router } from 'express';
|
|
4
|
-
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
5
|
-
import partialRouteHandler from './partial.js';
|
|
6
|
-
import linksToAllPartialsRouteHandler from './linksToAllPartialsRouteHandler.js';
|
|
7
|
-
import linksToAllModulesRouteHandler from './linksToAllModulesRouteHandler.js';
|
|
8
|
-
import moduleRouteHandler from './module.js';
|
|
9
|
-
import proxyPageRouteHandler from './proxyPageRouteHandler.js';
|
|
10
|
-
import proxyPageResourceRedirect from './proxyPageResourceRedirect.js';
|
|
11
|
-
import homeRouteHandler from './homeRouteHandler.js';
|
|
12
|
-
import { debug } from '../lib/debug.js';
|
|
13
|
-
import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
|
|
14
|
-
import proxyPathPageRouteHandler from './proxyPathPageRouteHandler.js';
|
|
15
|
-
import proxyPathPageResourceRedirect from './proxyPathPageResourceRedirect.js';
|
|
16
|
-
const STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(domain => `storybook.${domain}`);
|
|
17
|
-
const createDevServerRoutes = async (viteServer, storybookPort) => {
|
|
18
|
-
const devServerApp = Router();
|
|
19
|
-
// Debug incoming requests, enable with the DEBUG=cms-dev-server env variable
|
|
20
|
-
devServerApp.use((request, response, next) => {
|
|
21
|
-
const { method, url, hostname } = request;
|
|
22
|
-
debug(`${method}:${hostname}${url}`);
|
|
23
|
-
next();
|
|
24
|
-
});
|
|
25
|
-
if (storybookPort) {
|
|
26
|
-
devServerApp.use(createProxyMiddleware((__pathname, req) => STORYBOOK_DOMAINS.includes(req.hostname), {
|
|
27
|
-
logLevel: 'warn',
|
|
28
|
-
target: `http://localhost:${storybookPort}`,
|
|
29
|
-
}));
|
|
30
|
-
}
|
|
31
|
-
devServerApp.use(viteServer.middlewares);
|
|
32
|
-
devServerApp.get('/proxy', proxyPathPageRouteHandler);
|
|
33
|
-
devServerApp.get('/partials/', linksToAllPartialsRouteHandler);
|
|
34
|
-
devServerApp.get('/partial/:partial', partialRouteHandler);
|
|
35
|
-
devServerApp.get('/modules/', linksToAllModulesRouteHandler);
|
|
36
|
-
devServerApp.get('/module/:moduleName', moduleRouteHandler);
|
|
37
|
-
devServerApp.get('/', homeRouteHandler);
|
|
38
|
-
devServerApp.get('/*', proxyPathPageResourceRedirect);
|
|
39
|
-
devServerApp.get('/*', proxyPageResourceRedirect);
|
|
40
|
-
devServerApp.get('/*', proxyPageRouteHandler);
|
|
41
|
-
return devServerApp;
|
|
42
|
-
};
|
|
43
|
-
export default createDevServerRoutes;
|
|
@@ -1,12 +0,0 @@
|
|
|
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, storybookEnabled, devServerPort } = request.app.locals;
|
|
7
|
-
const { partialNames } = findAllPartialsInRoot(webRoot);
|
|
8
|
-
const { moduleNames } = findAllModulesInRoot(webRoot);
|
|
9
|
-
const { html: responseHtml } = await renderOnServer(_jsxs(_Fragment, { children: [storybookEnabled ? (_jsx("h2", { children: _jsx("a", { href: `//storybook.${request.hostname}:${devServerPort}`, children: "Storybook" }) })) : null, _jsx("h2", { children: "Partials" }), _jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), _jsx("h2", { children: "Modules" }), _jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames })] }), null, null);
|
|
10
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
11
|
-
};
|
|
12
|
-
export default homeRouteHandler;
|
|
@@ -1,10 +0,0 @@
|
|
|
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, null);
|
|
8
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
-
};
|
|
10
|
-
export default linksToAllModuleRouteHandler;
|
|
@@ -1,10 +0,0 @@
|
|
|
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, null);
|
|
8
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
|
|
9
|
-
};
|
|
10
|
-
export default linksToAllPartialRouteHandler;
|
package/dist/routes/module.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { buildStaticEnvConfig } from '@hubspot/cms-components/config';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import url from 'url';
|
|
4
|
-
import { normalizePath } from 'vite';
|
|
5
|
-
import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
|
|
6
|
-
import renderModule from '../lib/renderModule.js';
|
|
7
|
-
import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
|
|
8
|
-
const moduleRouteHandler = async (request, response) => {
|
|
9
|
-
const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer } = request.app.locals;
|
|
10
|
-
const moduleName = request.params.moduleName;
|
|
11
|
-
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
12
|
-
const modulePath = normalizePath(path.resolve(webRoot, 'components/modules/', moduleName));
|
|
13
|
-
let fieldOverrides = null;
|
|
14
|
-
if (request.query.fields) {
|
|
15
|
-
try {
|
|
16
|
-
if (typeof request.query.fields === 'string') {
|
|
17
|
-
fieldOverrides = JSON.parse(request.query.fields);
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
catch (e) {
|
|
21
|
-
console.error(`Error parsing field param for module ${moduleName}: ${request.query.fields}`);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
const environmentConfig = buildStaticEnvConfig(authedPortalId, authedHublet, authedEnv, false);
|
|
25
|
-
try {
|
|
26
|
-
const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, fieldOverrides, fullOriginalUrlFromRequest(request), environmentConfig);
|
|
27
|
-
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderContext, viteServer);
|
|
28
|
-
const html = htmlShell
|
|
29
|
-
.replace('<!--headend-->', cssNeeded)
|
|
30
|
-
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
31
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
32
|
-
}
|
|
33
|
-
catch (e) {
|
|
34
|
-
console.error(e);
|
|
35
|
-
viteServer.ssrFixStacktrace(e);
|
|
36
|
-
response
|
|
37
|
-
.status(500)
|
|
38
|
-
.end(`Error rendering module (${moduleName})\n\n${e.stack}`);
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
export default moduleRouteHandler;
|
package/dist/routes/partial.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
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
|
-
import { buildStaticEnvConfig } from '@hubspot/cms-components/config';
|
|
8
|
-
const partialRouteHandler = async (request, response) => {
|
|
9
|
-
const { authedPortalId, authedEnv, authedHublet, webRoot, viteServer } = request.app.locals;
|
|
10
|
-
const partialName = request.params.partial;
|
|
11
|
-
const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../html/baseTemplate.html');
|
|
12
|
-
const partialPath = normalizePath(path.resolve(webRoot, 'components/partials/', partialName));
|
|
13
|
-
const environmentConfig = buildStaticEnvConfig(authedPortalId, authedHublet, authedEnv, false);
|
|
14
|
-
try {
|
|
15
|
-
const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request), environmentConfig);
|
|
16
|
-
const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderContext, viteServer);
|
|
17
|
-
const html = htmlShell
|
|
18
|
-
.replace('<!--headend-->', cssNeeded)
|
|
19
|
-
.replace(`<!--ssr-outlet-->`, renderedHtml);
|
|
20
|
-
response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
|
21
|
-
}
|
|
22
|
-
catch (e) {
|
|
23
|
-
console.error(e);
|
|
24
|
-
viteServer.ssrFixStacktrace(e);
|
|
25
|
-
response
|
|
26
|
-
.status(500)
|
|
27
|
-
.end(`Error rendering partial (${partialName})\n\n${e.stack}`);
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
export default partialRouteHandler;
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import request from 'request';
|
|
2
|
-
import { getSubDomainFromValidLocalDomain } from '../proxyPage/utils.js';
|
|
3
|
-
import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
|
|
4
|
-
// From(ish) https://git.hubteam.com/HubSpot/cloudflare-workers/blob/master/worker-lib/src/Constants.ts
|
|
5
|
-
const HCMS_PATH = '/_hcms/';
|
|
6
|
-
const HS_FS_PATH = '/hs-fs/';
|
|
7
|
-
const HUB_FS_PATH = '/hubfs/';
|
|
8
|
-
const isInternalCMSRoute = (req) => req.path.startsWith(HCMS_PATH) ||
|
|
9
|
-
req.path.startsWith(HS_FS_PATH) ||
|
|
10
|
-
req.path.startsWith(HUB_FS_PATH);
|
|
11
|
-
export default function proxyPageResourceRedirect(req, res, next) {
|
|
12
|
-
const isAHtmlRequest = req.accepts().includes('text/html');
|
|
13
|
-
if ((isAHtmlRequest && !isInternalCMSRoute(req)) ||
|
|
14
|
-
VALID_PROXY_DOMAIN_SUFFIXES.includes(req.hostname)) {
|
|
15
|
-
next();
|
|
16
|
-
return;
|
|
17
|
-
}
|
|
18
|
-
const domainToProxy = getSubDomainFromValidLocalDomain(req.hostname);
|
|
19
|
-
const pathToProxy = req.originalUrl;
|
|
20
|
-
const urlToProxy = `https://${domainToProxy}${pathToProxy}`;
|
|
21
|
-
request(urlToProxy).pipe(res);
|
|
22
|
-
}
|