@hubspot/cms-dev-server 0.4.2 → 0.4.4
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 +36 -6
- package/dist/internalSsr.js +87 -12
- package/dist/run.js +174 -45
- package/package.json +4 -4
- package/types/createViteDevServer.d.ts +1 -1
- package/dist/components/ModulesList.js +0 -14
- package/dist/components/PartialsList.js +0 -13
- package/dist/createDevServer.js +0 -164
- package/dist/createDevServerConfiguration.js +0 -155
- package/dist/createViteDevServer.js +0 -52
- 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/getDevServerConfiguration.js +0 -63
- 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 -66
- 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/main.js +0 -31
- package/dist/storybook/moduleStory.js +0 -61
- package/dist/storybook/preview.js +0 -9
- package/dist/storybook/types.js +0 -1
|
@@ -1,136 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { hasComponentExtension, removeComponentExtension, } from '@hubspot/cms-js-internal';
|
|
2
|
-
import { findFullPathInModuleGraph } from './moduleGraph.js';
|
|
3
|
-
async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl, environmentConfig) {
|
|
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, renderContext } = await renderComponentOnServer(Component, props, pageUrl, environmentConfig);
|
|
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, renderContext };
|
|
25
|
-
}
|
|
26
|
-
export default renderComponentWithCSS;
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
function getByteSizeOf(props) {
|
|
2
|
-
return Buffer.from(JSON.stringify(props)).length;
|
|
3
|
-
}
|
|
4
|
-
function formatBytesToString(bytes) {
|
|
5
|
-
if (bytes > 1000000) {
|
|
6
|
-
// If byte size is > 1mb, show size in red
|
|
7
|
-
return ['\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`, `\x1b[0m`];
|
|
8
|
-
}
|
|
9
|
-
else if (bytes > 10000) {
|
|
10
|
-
// if byte size is between 10kb and 1mb, show size in yellow
|
|
11
|
-
return ['\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`, `\x1b[0m`];
|
|
12
|
-
}
|
|
13
|
-
else {
|
|
14
|
-
// Show size in green
|
|
15
|
-
return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`, `\x1b[0m`];
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
const getPropsInfo = (props, reportOptions = { showNestedKeySizeIfGreater: null }, recursionDepth = 0) => {
|
|
19
|
-
if (recursionDepth > 8) {
|
|
20
|
-
return [];
|
|
21
|
-
}
|
|
22
|
-
const propsSizeInBytes = getByteSizeOf(props);
|
|
23
|
-
const result = formatBytesToString(propsSizeInBytes);
|
|
24
|
-
if (!Array.isArray(props) &&
|
|
25
|
-
Object.keys(props).length > 0 &&
|
|
26
|
-
reportOptions.showNestedKeySizeIfGreater != null &&
|
|
27
|
-
propsSizeInBytes > reportOptions.showNestedKeySizeIfGreater) {
|
|
28
|
-
for (const [key, value] of Object.entries(props)) {
|
|
29
|
-
const size = getPropsInfo(value, reportOptions, recursionDepth + 1);
|
|
30
|
-
if (Array.isArray(value)) {
|
|
31
|
-
result.push('\n', `${key}[${value.length}]`, ...size);
|
|
32
|
-
}
|
|
33
|
-
else {
|
|
34
|
-
result.push('\n', key, ...size);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return result.flat();
|
|
39
|
-
};
|
|
40
|
-
export const logPartialInfo = (partialPath, props) => {
|
|
41
|
-
console.log('Rendering partial', partialPath);
|
|
42
|
-
console.group();
|
|
43
|
-
console.log('Props size: ', ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 }));
|
|
44
|
-
console.groupEnd();
|
|
45
|
-
};
|
package/dist/lib/renderModule.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { join as joinPosix } from 'path/posix';
|
|
2
|
-
import renderComponentWithCSS from './renderComponentWithCSS.js';
|
|
3
|
-
import { traverseFieldsJSON } from '@hubspot/cms-components/fields';
|
|
4
|
-
import { hasComponentExtension, setIn, renderFieldsToJson, } from '@hubspot/cms-js-internal';
|
|
5
|
-
const lookForModuleInFolder = async (modulePath, viteServer) => {
|
|
6
|
-
let componentModule;
|
|
7
|
-
const insideFolderPath = joinPosix(modulePath, 'index');
|
|
8
|
-
try {
|
|
9
|
-
componentModule = await viteServer.ssrLoadModule(insideFolderPath);
|
|
10
|
-
}
|
|
11
|
-
catch (e) {
|
|
12
|
-
if (!e.message.includes('Failed to load url')) {
|
|
13
|
-
throw e;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
return [componentModule, insideFolderPath];
|
|
17
|
-
};
|
|
18
|
-
async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}, pageUrl, environmentConfig) {
|
|
19
|
-
console.log('Rendering module', requestedModulePath);
|
|
20
|
-
let componentModule;
|
|
21
|
-
let foundPath;
|
|
22
|
-
if (!hasComponentExtension(requestedModulePath)) {
|
|
23
|
-
[componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
|
|
24
|
-
}
|
|
25
|
-
if (!componentModule) {
|
|
26
|
-
// Look for non-folder module
|
|
27
|
-
componentModule = await viteServer.ssrLoadModule(requestedModulePath);
|
|
28
|
-
foundPath = componentModule ? requestedModulePath : undefined;
|
|
29
|
-
}
|
|
30
|
-
if (!componentModule) {
|
|
31
|
-
throw new Error(`Couldn't find module: ${requestedModulePath}`);
|
|
32
|
-
}
|
|
33
|
-
const Component = componentModule.Component;
|
|
34
|
-
const fields = componentModule.fields;
|
|
35
|
-
const meta = componentModule.meta;
|
|
36
|
-
if (!Component) {
|
|
37
|
-
throw new Error(`Module does not have a named Component export: ${foundPath}`);
|
|
38
|
-
}
|
|
39
|
-
else if (!fields) {
|
|
40
|
-
throw new Error(`Module does not have a named fields export: ${foundPath}`);
|
|
41
|
-
}
|
|
42
|
-
else if (!meta) {
|
|
43
|
-
throw new Error(`Module does not have a named meta export: ${foundPath}`);
|
|
44
|
-
}
|
|
45
|
-
const fieldsJSON = renderFieldsToJson(fields);
|
|
46
|
-
const props = getPropsForModule(fieldsJSON, fieldOverrides);
|
|
47
|
-
return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl, environmentConfig);
|
|
48
|
-
}
|
|
49
|
-
function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
|
|
50
|
-
const props = {};
|
|
51
|
-
traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
|
|
52
|
-
setIn(props, fieldPathArray, value);
|
|
53
|
-
});
|
|
54
|
-
return props;
|
|
55
|
-
}
|
|
56
|
-
export default renderModule;
|
|
@@ -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,66 +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 = sharedDepsEnabled => {
|
|
7
|
-
if (sharedDepsEnabled) {
|
|
8
|
-
return `<script type="module">
|
|
9
|
-
import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
|
|
10
|
-
initConfigSingletonFromJSON(window.__hsEnvConfig);
|
|
11
|
-
</script>
|
|
12
|
-
<script type="module">
|
|
13
|
-
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime-shared';
|
|
14
|
-
setupIslandHydration();
|
|
15
|
-
</script>
|
|
16
|
-
`;
|
|
17
|
-
}
|
|
18
|
-
return `<script type="module">
|
|
19
|
-
import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
|
|
20
|
-
initConfigSingletonFromJSON(window.__hsEnvConfig);
|
|
21
|
-
</script>
|
|
22
|
-
<script type="module">
|
|
23
|
-
import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
|
|
24
|
-
setupIslandHydration();
|
|
25
|
-
</script>
|
|
26
|
-
`;
|
|
27
|
-
};
|
|
28
|
-
const createdPlainHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock) => {
|
|
29
|
-
const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
|
|
30
|
-
return htmlTemplateBase.replace('<!--title-->', title).replace('<!--bodyend-->', `
|
|
31
|
-
${globalScriptBlock}
|
|
32
|
-
<!--bodyend-->`);
|
|
33
|
-
};
|
|
34
|
-
const createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock, sharedDepsEnabled) => {
|
|
35
|
-
let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
|
|
36
|
-
htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
|
|
37
|
-
${generateIslandSetupScriptBlock(sharedDepsEnabled)}
|
|
38
|
-
<!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
|
|
39
|
-
<!--islandsglobal-->
|
|
40
|
-
`);
|
|
41
|
-
return htmlTemplate;
|
|
42
|
-
};
|
|
43
|
-
export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer, sharedDepsEnabled) => {
|
|
44
|
-
let htmlTemplate;
|
|
45
|
-
if (renderContext.islands.length) {
|
|
46
|
-
const globalScriptBlock = getServerGlobalsToInject(renderContext.environmentConfig, renderContext.pageUrl);
|
|
47
|
-
htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title, globalScriptBlock, sharedDepsEnabled);
|
|
48
|
-
htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
|
|
49
|
-
${createIslandsGlobalJsForClientInDev(renderContext.islands, viteServer, 4)}
|
|
50
|
-
</script>
|
|
51
|
-
`);
|
|
52
|
-
}
|
|
53
|
-
else {
|
|
54
|
-
const globalScriptBlock = getServerGlobalsToInject(renderContext.environmentConfig);
|
|
55
|
-
htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title, globalScriptBlock);
|
|
56
|
-
}
|
|
57
|
-
return viteServer.transformIndexHtml(url, htmlTemplate);
|
|
58
|
-
};
|
|
59
|
-
export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, sharedDepsEnabled) => {
|
|
60
|
-
// Loading through vite so all of nested `@hubspot/cms-*` imports work
|
|
61
|
-
const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
|
|
62
|
-
const islandRuntimeScript = await viteServer.transformIndexHtml('/', generateIslandSetupScriptBlock(sharedDepsEnabled));
|
|
63
|
-
return `${islandRuntimeScript}
|
|
64
|
-
<script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
|
|
65
|
-
`;
|
|
66
|
-
};
|
|
@@ -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, sharedDepsEnabled, 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, sharedDepsEnabled);
|
|
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
|
-
}
|