@hubspot/cms-dev-server 1.1.0-prerelease.6 → 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.
Files changed (35) hide show
  1. package/dist/plugins/devMockClientEntryPlugin.js +52 -0
  2. package/dist/routes/proxyPage.js +205 -0
  3. package/dist/run.mjs +10 -0
  4. package/dist/src/components/ModulesList.js +14 -0
  5. package/dist/src/components/PartialsList.js +13 -0
  6. package/dist/src/createDevServer.js +45 -0
  7. package/dist/src/lib/htmlHelpers.js +10 -0
  8. package/dist/src/lib/moduleGraph.js +9 -0
  9. package/dist/src/lib/proxyHelpers.js +55 -0
  10. package/dist/src/lib/proxyHelpers.test.js +136 -0
  11. package/dist/src/lib/renderComponentWithCSS.js +26 -0
  12. package/dist/src/lib/renderModule.js +84 -0
  13. package/dist/src/lib/renderPartial.js +11 -0
  14. package/dist/src/lib/templates.js +50 -0
  15. package/dist/src/plugins/devMockClientEntryPlugin.js +52 -0
  16. package/dist/src/proxyPage/constants.js +4 -0
  17. package/dist/src/proxyPage/fetchContentMetadata.js +40 -0
  18. package/dist/src/proxyPage/fetchPreviewInfo.js +25 -0
  19. package/dist/src/proxyPage/proxyPage.js +147 -0
  20. package/dist/src/proxyPage/renderLocalError.js +1 -0
  21. package/dist/src/proxyPage/utils.js +36 -0
  22. package/dist/src/routes/createDevServerRoutes.js +19 -0
  23. package/dist/src/routes/homeRouteHandler.js +12 -0
  24. package/dist/src/routes/linksToAllModulesRouteHandler.js +10 -0
  25. package/dist/src/routes/linksToAllPartialsRouteHandler.js +10 -0
  26. package/dist/src/routes/module.js +26 -0
  27. package/dist/src/routes/partial.js +26 -0
  28. package/dist/src/routes/proxyPageRouteHandler.js +28 -0
  29. package/package.json +7 -4
  30. package/dist/lib/createIslandsGlobalJsForClientInDev.js +0 -32
  31. package/dist/lib/traverseFieldsJson.js +0 -78
  32. package/dist/render/renderOnServer.js +0 -40
  33. package/dist/render/renderOnServer.test.js +0 -24
  34. package/dist/render/renderStreamToPromise.js +0 -35
  35. package/dist/resolveSharedDeps.js +0 -28
@@ -0,0 +1,11 @@
1
+ import renderComponentWithCSS from './renderComponentWithCSS.js';
2
+ async function renderPartial(viteServer, partialPath, props, pageUrl) {
3
+ console.log('Rendering partial', partialPath);
4
+ const componentModule = await viteServer.ssrLoadModule(partialPath);
5
+ const Component = componentModule.default;
6
+ if (!componentModule) {
7
+ throw new Error(`Couldn't find partial: ${partialPath}`);
8
+ }
9
+ return renderComponentWithCSS(viteServer, partialPath, Component, props, pageUrl);
10
+ }
11
+ export default renderPartial;
@@ -0,0 +1,50 @@
1
+ import { promises as fsPromises } from 'fs';
2
+ import { rewriteAbsoluteJsAndCssPaths } from './htmlHelpers.js';
3
+ import { sortIslandRootsByPriority, createIslandsGlobalJsForClientInDev, } from '@hubspot/cms-js-internal';
4
+ const { readFile } = fsPromises;
5
+ const ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK = `<script type="module">
6
+ import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
7
+ setupIslandHydration();
8
+ </script>
9
+ `;
10
+ const createdPlainHtmlTemplate = async (baseTemplatePath, title) => {
11
+ const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
12
+ return htmlTemplateBase.replace('<!--title-->', title);
13
+ };
14
+ const createIslandHtmlTemplate = async (baseTemplatePath, title) => {
15
+ let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
16
+ htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
17
+ ${ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK}
18
+ <!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
19
+ <!--islandsglobal-->
20
+ `);
21
+ return htmlTemplate;
22
+ };
23
+ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderInfoContext, viteServer) => {
24
+ let htmlTemplate;
25
+ if (renderInfoContext.islands.length) {
26
+ htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title);
27
+ const sortedIslandRoots = sortIslandRootsByPriority(renderInfoContext.islands);
28
+ htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
29
+ ${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}
30
+ </script>`);
31
+ }
32
+ else {
33
+ htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
34
+ }
35
+ return await viteServer.transformIndexHtml(url, htmlTemplate);
36
+ };
37
+ export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, devServerHost, devServerPort) => {
38
+ const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
39
+ // Loading through vite so all of nested `@hubspot/cms-*` imports work
40
+ const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
41
+ let islandRuntimeScript = await viteServer.transformIndexHtml('/', ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK);
42
+ // Need to write JS module URLs to be absolute to localhost for when this island code
43
+ // is injected into a HTML document with a differnt <base> url set
44
+ // Note, :sadtrombone: that https://github.com/vitejs/vite/issues/2196 was closed
45
+ // and that https://github.com/vitejs/vite/pull/5104 doesn't help for JS assets
46
+ islandRuntimeScript = rewriteAbsoluteJsAndCssPaths(islandRuntimeScript, serverDomainAndPort, 'http://');
47
+ islandRuntimeScript = islandRuntimeScript.replace('import RefreshRuntime from "/@react-refresh"', `import RefreshRuntime from "http://${serverDomainAndPort}/@react-refresh"`);
48
+ return `${islandRuntimeScript}
49
+ <script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>`;
50
+ };
@@ -0,0 +1,52 @@
1
+ import path from 'path';
2
+ import { readdirSync } from 'fs';
3
+ const PARTIAL_SOURCE_DIR = 'components/partials';
4
+ function getAllComponentFilenamesIn(dirPath) {
5
+ return readdirSync(dirPath).filter((filename) => {
6
+ const ext = path.extname(filename);
7
+ return ext === '.jsx' || ext === '.tsx';
8
+ });
9
+ }
10
+ const buildMockPartialModule = (entryPointsFileNames) => {
11
+ return entryPointsFileNames
12
+ .map((filename) => {
13
+ const ext = path.extname(filename);
14
+ const withoutExtension = path.basename(filename, ext);
15
+ return `export const ${withoutExtension} = () => import('/${PARTIAL_SOURCE_DIR}/${filename}');`;
16
+ })
17
+ .join('\n');
18
+ };
19
+ // Not needed in dev unless some code wants to do `import { SomePartial } from 'components/partials'`
20
+ export default function devMockClientEntryPlugin(webRoot) {
21
+ const ENTRY_POINTS_PATH = path.resolve(webRoot, PARTIAL_SOURCE_DIR);
22
+ const MOCK_ENTRY_PATH = `${ENTRY_POINTS_PATH}/index.js`;
23
+ return {
24
+ enforce: 'pre',
25
+ name: 'client-entry',
26
+ options(options) {
27
+ if (!options.input) {
28
+ return {
29
+ ...options,
30
+ input: [MOCK_ENTRY_PATH],
31
+ };
32
+ }
33
+ return options;
34
+ },
35
+ async resolveId(source, importer, options) {
36
+ if (source === PARTIAL_SOURCE_DIR /*&& options.isEntry*/) {
37
+ return {
38
+ id: source,
39
+ moduleSideEffects: 'no-treeshake',
40
+ };
41
+ }
42
+ return null;
43
+ },
44
+ load(id) {
45
+ if (id === PARTIAL_SOURCE_DIR) {
46
+ const entryPointsFileNames = getAllComponentFilenamesIn(ENTRY_POINTS_PATH);
47
+ return buildMockPartialModule(entryPointsFileNames);
48
+ }
49
+ return null;
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,4 @@
1
+ export const VALID_PROXY_DOMAIN_SUFFIXES = [
2
+ 'localhost',
3
+ // 'hslocal.dev', // TODO not real yet
4
+ ];
@@ -0,0 +1,40 @@
1
+ import http from 'http';
2
+ import https from 'https';
3
+ export default async function getContentMetadata(url, redirects = 0, originalUrl) {
4
+ if (redirects > 5) {
5
+ throw new Error(`Hit too many redirects to HEAD requests for ${originalUrl}`);
6
+ }
7
+ return new Promise((resolve, reject) => {
8
+ const protocolAPI = url.startsWith('https://') ? https : http;
9
+ protocolAPI
10
+ .request(url, { method: 'HEAD' }, (res) => {
11
+ // Use a lib to better follow various redirects?
12
+ if (res.statusCode >= 300 &&
13
+ res.statusCode < 400 &&
14
+ res.headers.location) {
15
+ console.log(`Redirecting to ${res.headers.location} (from ${url})`);
16
+ return resolve(getContentMetadata(res.headers.location, redirects + 1, originalUrl ?? url));
17
+ }
18
+ const portalIdHeader = res.headers['x-hs-hub-id'];
19
+ const contentId = res.headers['x-hs-content-id'];
20
+ if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
21
+ return reject(new Error(`There were multiple hub ID or content ID headers in the HEAD request to ${url}`));
22
+ }
23
+ else {
24
+ const portalId = parseInt(portalIdHeader, 10);
25
+ if (!portalId || !contentId) {
26
+ return reject(new Error(`Missing hub ID or content ID headers on HEAD request to ${url}`));
27
+ }
28
+ else if (isNaN(portalId)) {
29
+ return reject(new Error(`Hud ID from the HEAD request is not a number: '${portalId}' (${url})`));
30
+ }
31
+ return resolve({ portalId, contentId });
32
+ }
33
+ })
34
+ .on('error', (err) => {
35
+ console.error(err);
36
+ reject(err);
37
+ })
38
+ .end();
39
+ });
40
+ }
@@ -0,0 +1,25 @@
1
+ import { get as hsGet } from '@hubspot/cli-lib/http.js';
2
+ export default async (accountId, portalId, contentId) => {
3
+ try {
4
+ // Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
5
+ const content = await hsGet(accountId, {
6
+ uri: `/content/api/v4/contents/${contentId}`,
7
+ query: { portalId },
8
+ json: true,
9
+ });
10
+ return {
11
+ previewDomain: content.previewDomain ?? content.resolvedDomain,
12
+ previewKey: content.previewKey,
13
+ };
14
+ }
15
+ catch (error) {
16
+ console.log(`error`, error);
17
+ if (error.options) {
18
+ console.log(`error.options`, error.options);
19
+ }
20
+ if (error.response && error.response.headers) {
21
+ console.log(`error.response.headers`, error.response.headers);
22
+ }
23
+ throw error;
24
+ }
25
+ };
@@ -0,0 +1,147 @@
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 { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
5
+ import renderPartial from '../lib/renderPartial.js';
6
+ import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
7
+ import { addBaseTag, rewriteAbsoluteJsAndCssPaths } from '../lib/htmlHelpers.js';
8
+ import { fakeRenderJsComponent } from './utils.js';
9
+ import renderLocalError from './renderLocalError.js';
10
+ import fetchPreviewInfo from './fetchPreviewInfo.js';
11
+ const makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId) => {
12
+ const url = new URL(urlToProxy);
13
+ console.log(`Proxying request to ${url.href}`, {
14
+ previewKey,
15
+ contentId,
16
+ });
17
+ const result = hsGet(accountId, {
18
+ baseUrl: url.origin,
19
+ uri: url.pathname,
20
+ query: {
21
+ ...url.searchParams,
22
+ hs_preview: `${previewKey}-${contentId}`,
23
+ hsLocalProxy: true
24
+ },
25
+ json: false
26
+ });
27
+ return result.catch((error) => {
28
+ if (error.statusCode >= 400 &&
29
+ error.statusCode < 500 &&
30
+ !!error.response.body) {
31
+ return error.response.body;
32
+ }
33
+ else {
34
+ throw error;
35
+ }
36
+ });
37
+ };
38
+ const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer, pageUrl) => {
39
+ if (localRenderPlaceholder.path.startsWith('/fake/path/to/')) {
40
+ return fakeRenderJsComponent(indexForThisRender);
41
+ }
42
+ else if (localRenderPlaceholder.path.startsWith('components/partials/')) {
43
+ const partialPath = path.resolve(webRoot, localRenderPlaceholder.path);
44
+ return renderPartial(viteServer, partialPath, localRenderPlaceholder.json, pageUrl);
45
+ }
46
+ else {
47
+ throw new Error(`Unimplemented render of ${localRenderPlaceholder.path}`);
48
+ }
49
+ };
50
+ export default async function proxySpecificPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, urlToProxy, originalUrl) {
51
+ let accountId;
52
+ try {
53
+ accountId = getAccountId(portalId);
54
+ }
55
+ catch (e) {
56
+ response
57
+ .status(500)
58
+ .end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
59
+ return;
60
+ }
61
+ if (!accountId) {
62
+ response
63
+ .status(500)
64
+ .end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
65
+ return;
66
+ }
67
+ try {
68
+ const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
69
+ const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
70
+ const { previewDomain, previewKey } = previewInfo;
71
+ let pageHtml;
72
+ pageHtml = await makeProxyPreviewRequest(accountId, urlToProxy, previewKey, contentId);
73
+ pageHtml = addBaseTag(pageHtml, urlToProxy);
74
+ // TODO, this is only needed for asset references that happen _before_ the `<base href="...">` element
75
+ // Is that only a preview URL thing? Or is it in all (most?) rendered CMS pages
76
+ pageHtml = rewriteAbsoluteJsAndCssPaths(pageHtml, previewDomain, 'https://');
77
+ // Loading through vite so all of nested `@hubspot/cms-*` imports work
78
+ const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
79
+ const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
80
+ const numPlaceholders = localRenderPlaceholders.length;
81
+ const totalNumHtmlChunks = numPlaceholders * 2 + 1;
82
+ let numJsRenderFailures = 0;
83
+ let islands = [];
84
+ const renderPromisesByChunkIndex = new Array(numPlaceholders);
85
+ if (localRenderPlaceholders.length > 0) {
86
+ let offsetSoFar = 0;
87
+ const pageChunks = new Array(numPlaceholders + 1);
88
+ for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
89
+ const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
90
+ pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
91
+ const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer, originalUrl);
92
+ renderPromisesByChunkIndex[indexForThisRender] = renderPromise
93
+ .then((promiseResult) => {
94
+ // eslint-disable-next-line prefer-const
95
+ let { html, cssNeeded, renderInfoContext } = promiseResult;
96
+ console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
97
+ if (renderInfoContext.islands.length > 0) {
98
+ islands = islands.concat(renderInfoContext.islands);
99
+ }
100
+ if (cssNeeded) {
101
+ // Note, this is needed for cases where `<base href="...">` is output by the renderer, so
102
+ // that local asset URLs go to the local dev server
103
+ cssNeeded = rewriteAbsoluteJsAndCssPaths(cssNeeded, serverDomainAndPort, 'http://');
104
+ return `${cssNeeded}\n${html}`;
105
+ }
106
+ return html;
107
+ })
108
+ .catch((e) => {
109
+ numJsRenderFailures += 1;
110
+ console.error(e);
111
+ return renderLocalError(localRenderPlaceholder.path, e);
112
+ });
113
+ offsetSoFar = localRenderPlaceholder.endOffset;
114
+ }
115
+ // Last chunk from end of last placeholder to end of HTML
116
+ pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
117
+ response.writeHead(200);
118
+ for (let i = 0; i < localRenderPlaceholders.length; i++) {
119
+ const chunk = pageChunks[i];
120
+ response.write(chunk);
121
+ const foobar = await renderPromisesByChunkIndex[i];
122
+ // console.log("JS rendered chunk", i, foobar);
123
+ response.write(foobar);
124
+ }
125
+ if (islands.length > 0) {
126
+ const sortedIslandRoots = sortIslandRootsByPriority(islands);
127
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
128
+ response.write(islandRuntimeAndGlobalScriptHtml);
129
+ }
130
+ // Write last string chunk located after last placeholder
131
+ response.write(pageChunks[pageChunks.length - 1]);
132
+ response.end();
133
+ }
134
+ else {
135
+ response.writeHead(200);
136
+ response.write(pageHtml);
137
+ response.end();
138
+ }
139
+ }
140
+ catch (error) {
141
+ // TODO change error.stack to error.message before we publish
142
+ response
143
+ .status(500)
144
+ .end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
145
+ return;
146
+ }
147
+ }
@@ -0,0 +1 @@
1
+ export default (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
@@ -0,0 +1,36 @@
1
+ import { createRenderInfoContext } from '@hubspot/cms-components';
2
+ import { VALID_PROXY_DOMAIN_SUFFIXES } from './constants.js';
3
+ export const getSubDomainFromValidLocalDomain = (hostname) => {
4
+ for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {
5
+ if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {
6
+ return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);
7
+ }
8
+ }
9
+ return undefined;
10
+ };
11
+ const randomStringWithLotsOf = (char, maxLength) => {
12
+ return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
13
+ };
14
+ export const fakeRenderJsComponent = (indexForThisRender) => {
15
+ return new Promise((resolve, reject) => {
16
+ const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
17
+ setTimeout(() => {
18
+ try {
19
+ const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
20
+ resolve({
21
+ html: fakeJsRenderedOutput,
22
+ cssNeeded: '',
23
+ renderInfoContext: createRenderInfoContext('fake-component'),
24
+ });
25
+ }
26
+ catch (e) {
27
+ console.log('Error with JS render...');
28
+ console.error(e);
29
+ reject();
30
+ }
31
+ }, randomTimeout);
32
+ });
33
+ };
34
+ export const consoleWarn = (message) => {
35
+ console.warn('\x1b[33m%s\x1b[0m', 'WARNING:', message);
36
+ };
@@ -0,0 +1,19 @@
1
+ import { Router } from 'express';
2
+ import partialRouteHandler from './partial.js';
3
+ import linksToAllPartialsRouteHandler from './linksToAllPartialsRouteHandler.js';
4
+ import linksToAllModulesRouteHandler from './linksToAllModulesRouteHandler.js';
5
+ import moduleRouteHandler from './module.js';
6
+ import proxyPageRouteHandler from './proxyPageRouteHandler.js';
7
+ import homeRouteHandler from './homeRouteHandler.js';
8
+ const createDevServerRoutes = async (packageRoot, webRoot, viteServer) => {
9
+ const devServerApp = Router();
10
+ devServerApp.use(viteServer.middlewares);
11
+ devServerApp.get('/partials/', linksToAllPartialsRouteHandler);
12
+ devServerApp.get('/partial/:partial', partialRouteHandler);
13
+ devServerApp.get('/modules/', linksToAllModulesRouteHandler);
14
+ devServerApp.get('/module/:moduleName', moduleRouteHandler);
15
+ devServerApp.get('/', homeRouteHandler);
16
+ devServerApp.get('/*', proxyPageRouteHandler);
17
+ return devServerApp;
18
+ };
19
+ export default createDevServerRoutes;
@@ -0,0 +1,12 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { findAllModulesInRoot, findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
3
+ import ModulesList from '../components/ModulesList.js';
4
+ import PartialsList from '../components/PartialsList.js';
5
+ const homeRouteHandler = async (request, response) => {
6
+ const { webRoot } = request.app.locals;
7
+ const { partialNames } = findAllPartialsInRoot(webRoot);
8
+ const { moduleNames } = findAllModulesInRoot(webRoot);
9
+ const { html: responseHtml } = await renderOnServer(_jsxs(_Fragment, { children: [_jsx("h2", { children: "Partials" }), _jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), _jsx("h2", { children: "Modules" }), _jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames })] }), null);
10
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
11
+ };
12
+ export default homeRouteHandler;
@@ -0,0 +1,10 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { findAllModulesInRoot, renderOnServer } from '@hubspot/cms-js-internal';
3
+ import ModulesList from '../components/ModulesList.js';
4
+ const linksToAllModuleRouteHandler = async (request, response) => {
5
+ const { webRoot } = request.app.locals;
6
+ const { moduleNames } = findAllModulesInRoot(webRoot);
7
+ const { html: responseHtml } = await renderOnServer(_jsx(ModulesList, { webRoot: webRoot, moduleNames: moduleNames }), null);
8
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
9
+ };
10
+ export default linksToAllModuleRouteHandler;
@@ -0,0 +1,10 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { findAllPartialsInRoot, renderOnServer, } from '@hubspot/cms-js-internal';
3
+ import PartialsList from '../components/PartialsList.js';
4
+ const linksToAllPartialRouteHandler = async (request, response) => {
5
+ const { webRoot } = request.app.locals;
6
+ const { partialNames } = findAllPartialsInRoot(webRoot);
7
+ const { html: responseHtml } = await renderOnServer(_jsx(PartialsList, { webRoot: webRoot, partialNames: partialNames }), null);
8
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
9
+ };
10
+ export default linksToAllPartialRouteHandler;
@@ -0,0 +1,26 @@
1
+ import path from 'path';
2
+ import renderModule from '../lib/renderModule.js';
3
+ import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
4
+ const moduleRouteHandler = async (request, response) => {
5
+ const { packageRoot, webRoot, viteServer } = request.app.locals;
6
+ const moduleName = request.params.moduleName;
7
+ const baseTemplatePath = path.resolve(packageRoot, 'src/baseTemplate.html');
8
+ const modulePath = path.resolve(webRoot, 'components/modules/', moduleName);
9
+ const pageUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
10
+ try {
11
+ const { html: renderedHtml, cssNeeded, renderInfoContext, } = await renderModule(viteServer, modulePath, null);
12
+ const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Module: ${modulePath}`, renderInfoContext, viteServer);
13
+ const html = htmlShell
14
+ .replace('<!--headend-->', cssNeeded)
15
+ .replace(`<!--ssr-outlet-->`, renderedHtml);
16
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
17
+ }
18
+ catch (e) {
19
+ console.error(e);
20
+ viteServer.ssrFixStacktrace(e);
21
+ response
22
+ .status(500)
23
+ .end(`Error rendering module (${moduleName})\n\n${e.stack}`);
24
+ }
25
+ };
26
+ export default moduleRouteHandler;
@@ -0,0 +1,26 @@
1
+ import path from 'path';
2
+ import renderPartial from '../lib/renderPartial.js';
3
+ import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
4
+ const partialRouteHandler = async (request, response) => {
5
+ const { packageRoot, webRoot, viteServer } = request.app.locals;
6
+ const partialName = request.params.partial;
7
+ const baseTemplatePath = path.resolve(packageRoot, 'src/baseTemplate.html');
8
+ const partialPath = path.resolve(webRoot, 'components/partials/', partialName);
9
+ const pageUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
10
+ try {
11
+ const { html: renderedHtml, cssNeeded, renderInfoContext, } = await renderPartial(viteServer, partialPath, {}, pageUrl);
12
+ const htmlShell = await createHtmlShellDependingOnRenderContext(baseTemplatePath, request.originalUrl, `Partial: ${partialPath}`, renderInfoContext, viteServer);
13
+ const html = htmlShell
14
+ .replace('<!--headend-->', cssNeeded)
15
+ .replace(`<!--ssr-outlet-->`, renderedHtml);
16
+ response.status(200).set({ 'Content-Type': 'text/html' }).end(html);
17
+ }
18
+ catch (e) {
19
+ console.error(e);
20
+ viteServer.ssrFixStacktrace(e);
21
+ response
22
+ .status(500)
23
+ .end(`Error rendering partial (${partialName})\n\n${e.stack}`);
24
+ }
25
+ };
26
+ export default partialRouteHandler;
@@ -0,0 +1,28 @@
1
+ import fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';
2
+ import proxyPage from '../proxyPage/proxyPage.js';
3
+ import { getSubDomainFromValidLocalDomain, consoleWarn, } from '../proxyPage/utils.js';
4
+ import { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';
5
+ export default async function proxyPageRouteHandler(request, response) {
6
+ const { viteServer, webRoot, devServerHost, devServerPort } = request.app.locals;
7
+ if (!request.accepts().includes('text/html')) {
8
+ return response.sendStatus(404);
9
+ }
10
+ const originalUrl = request.protocol + '://' + request.get('host') + request.originalUrl;
11
+ const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);
12
+ const pathToProxy = request.path;
13
+ const urlToProxy = `http://${domainToProxy}${pathToProxy}`;
14
+ if (!domainToProxy) {
15
+ if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {
16
+ const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;
17
+ consoleWarn(message);
18
+ return response.status(404).send(message);
19
+ }
20
+ else {
21
+ const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;
22
+ consoleWarn(message);
23
+ return response.status(404).send(message);
24
+ }
25
+ }
26
+ const { portalId, contentId } = await fetchContentMetadata(urlToProxy);
27
+ await proxyPage(response, portalId, contentId, webRoot, viteServer, devServerHost, devServerPort, urlToProxy, originalUrl);
28
+ }
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "1.1.0-prerelease.6",
3
+ "version": "1.1.0-prerelease.7",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/createViteDevServer.js",
7
+ "engines": {
8
+ "node": ">=16.x"
9
+ },
7
10
  "scripts": {
8
11
  "build": "tsc --build && npm run copy-html",
9
12
  "copy-html": "copyfiles -u 1 'src/html/**' 'dist'",
@@ -18,8 +21,8 @@
18
21
  },
19
22
  "dependencies": {
20
23
  "@hubspot/cli-lib": "^3.0.12",
21
- "@hubspot/cms-components": "^1.1.0-prerelease.6",
22
- "@hubspot/cms-js-internal": "^1.1.0-prerelease.6",
24
+ "@hubspot/cms-components": "^1.1.0-prerelease.7",
25
+ "@hubspot/cms-js-internal": "^1.1.0-prerelease.7",
23
26
  "@vitejs/plugin-react": "^2.0.0",
24
27
  "ansi-to-html": "0.7.x",
25
28
  "express": "^4.17.3",
@@ -61,5 +64,5 @@
61
64
  "publishConfig": {
62
65
  "access": "public"
63
66
  },
64
- "gitHead": "5c7ad978bb67ee8308c91cdffd226c00bc47d20c"
67
+ "gitHead": "254eaaa461326ec5fecb911c3e7954527aa1741b"
65
68
  }
@@ -1,32 +0,0 @@
1
- const writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
2
- const indentString = new Array(indent).fill(' ').join('');
3
- return `window.__islands = ${JSON.stringify(tweakedIslandsArray.map(({ id, moduleName, moduleId, props, hydrateOn, clientOnly, priority, url, }) => {
4
- return {
5
- id,
6
- moduleName,
7
- moduleId,
8
- props,
9
- hydrateOn,
10
- clientOnly,
11
- priority,
12
- url,
13
- };
14
- }), null, 2).replace(/\n/gm, `\n${indentString}`)};`;
15
- };
16
- function getIslandUrls(roots, viteDevServer) {
17
- return roots.map(island => {
18
- const islandModule = viteDevServer.moduleGraph.getModuleById(island.moduleId);
19
- if (!islandModule) {
20
- throw new Error(`Unknown island moduleId: ${island.moduleId}`);
21
- }
22
- const tweakedIsland = {
23
- ...island,
24
- url: islandModule.url,
25
- };
26
- return tweakedIsland;
27
- });
28
- }
29
- export const createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
30
- // Assuming island roots have already been sorted before being passed in here
31
- return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
32
- };