@hubspot/cms-dev-server 1.1.0-prerelease.2

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 (60) hide show
  1. package/README.md +3 -0
  2. package/dist/components/ModulesList.js +14 -0
  3. package/dist/components/PartialsList.js +13 -0
  4. package/dist/createDevServer.js +25 -0
  5. package/dist/createViteDevServer.js +26 -0
  6. package/dist/html/baseTemplate.html +12 -0
  7. package/dist/lib/fullOriginalUrlFromRequest.js +3 -0
  8. package/dist/lib/htmlHelpers.js +10 -0
  9. package/dist/lib/moduleGraph.js +11 -0
  10. package/dist/lib/proxyHelpers.js +69 -0
  11. package/dist/lib/proxyHelpers.test.js +136 -0
  12. package/dist/lib/renderComponentWithCSS.js +26 -0
  13. package/dist/lib/renderHelpers.js +21 -0
  14. package/dist/lib/renderModule.js +88 -0
  15. package/dist/lib/renderPartial.js +12 -0
  16. package/dist/lib/templates.js +49 -0
  17. package/dist/plugins/devMockClientEntryPlugin.js +52 -0
  18. package/dist/proxyPage/constants.js +4 -0
  19. package/dist/proxyPage/fetchContentMetadata.js +51 -0
  20. package/dist/proxyPage/fetchPreviewInfo.js +37 -0
  21. package/dist/proxyPage/proxyPage.js +167 -0
  22. package/dist/proxyPage/renderLocalError.js +27 -0
  23. package/dist/proxyPage/utils.js +38 -0
  24. package/dist/routes/createDevServerRoutes.js +21 -0
  25. package/dist/routes/homeRouteHandler.js +12 -0
  26. package/dist/routes/linksToAllModulesRouteHandler.js +10 -0
  27. package/dist/routes/linksToAllPartialsRouteHandler.js +10 -0
  28. package/dist/routes/module.js +26 -0
  29. package/dist/routes/partial.js +26 -0
  30. package/dist/routes/proxyPage.js +205 -0
  31. package/dist/routes/proxyPageResourceRedirect.js +12 -0
  32. package/dist/routes/proxyPageRouteHandler.js +40 -0
  33. package/dist/run.js +7 -0
  34. package/dist/run.mjs +10 -0
  35. package/dist/src/components/ModulesList.js +14 -0
  36. package/dist/src/components/PartialsList.js +13 -0
  37. package/dist/src/createDevServer.js +45 -0
  38. package/dist/src/lib/htmlHelpers.js +10 -0
  39. package/dist/src/lib/moduleGraph.js +9 -0
  40. package/dist/src/lib/proxyHelpers.js +55 -0
  41. package/dist/src/lib/proxyHelpers.test.js +136 -0
  42. package/dist/src/lib/renderComponentWithCSS.js +26 -0
  43. package/dist/src/lib/renderModule.js +84 -0
  44. package/dist/src/lib/renderPartial.js +11 -0
  45. package/dist/src/lib/templates.js +50 -0
  46. package/dist/src/plugins/devMockClientEntryPlugin.js +52 -0
  47. package/dist/src/proxyPage/constants.js +4 -0
  48. package/dist/src/proxyPage/fetchContentMetadata.js +40 -0
  49. package/dist/src/proxyPage/fetchPreviewInfo.js +25 -0
  50. package/dist/src/proxyPage/proxyPage.js +147 -0
  51. package/dist/src/proxyPage/renderLocalError.js +1 -0
  52. package/dist/src/proxyPage/utils.js +36 -0
  53. package/dist/src/routes/createDevServerRoutes.js +19 -0
  54. package/dist/src/routes/homeRouteHandler.js +12 -0
  55. package/dist/src/routes/linksToAllModulesRouteHandler.js +10 -0
  56. package/dist/src/routes/linksToAllPartialsRouteHandler.js +10 -0
  57. package/dist/src/routes/module.js +26 -0
  58. package/dist/src/routes/partial.js +26 -0
  59. package/dist/src/routes/proxyPageRouteHandler.js +28 -0
  60. package/package.json +65 -0
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # cms-dev-server
2
+
3
+ Local dev server for JS rendering
@@ -0,0 +1,14 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ function EmptyModulesList({ webRoot }) {
3
+ return (_jsxs("p", { children: ["No modules in ", _jsxs("code", { children: [webRoot, "components/modules"] })] }));
4
+ }
5
+ function ModuleLinkInLI({ moduleName }) {
6
+ return (_jsx("li", { children: _jsx("a", { href: `/module/${moduleName}`, children: moduleName }) }));
7
+ }
8
+ function ModulesList({ webRoot, moduleNames }) {
9
+ if (moduleNames.length === 0) {
10
+ return _jsx(EmptyModulesList, { webRoot: webRoot });
11
+ }
12
+ return (_jsx("ul", { children: moduleNames.map(moduleName => (_jsx(ModuleLinkInLI, { moduleName: moduleName }, moduleName))) }));
13
+ }
14
+ export default ModulesList;
@@ -0,0 +1,13 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ function EmptyPartialsList({ webRoot }) {
3
+ return (_jsxs("p", { children: ["No partials in ", _jsxs("code", { children: [webRoot, "components/partials"] })] }));
4
+ }
5
+ function PartialLinkInLI({ partialName }) {
6
+ return (_jsx("li", { children: _jsx("a", { href: `/partial/${partialName}`, children: partialName }) }));
7
+ }
8
+ export default function PartialsList({ webRoot, partialNames }) {
9
+ if (partialNames.length === 0) {
10
+ return _jsx(EmptyPartialsList, { webRoot: webRoot });
11
+ }
12
+ return (_jsx("ul", { children: partialNames.map(partialName => (_jsx(PartialLinkInLI, { partialName: partialName }, partialName))) }));
13
+ }
@@ -0,0 +1,25 @@
1
+ import path from 'path';
2
+ import express from 'express';
3
+ import createDevServerRoutes from './routes/createDevServerRoutes.js';
4
+ import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
5
+ import createViteDevServer from './createViteDevServer.js';
6
+ const BASE_PATH = '/';
7
+ const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
8
+ async function createDevServer(webRoot) {
9
+ const expressServer = express();
10
+ const viteServer = await createViteDevServer();
11
+ const absoluteWebRoot = path.resolve(process.cwd(), webRoot);
12
+ const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
13
+ expressServer.locals.devServerHost = 'localhost';
14
+ expressServer.locals.devServerPort = PORT;
15
+ expressServer.locals.webRoot = webRoot;
16
+ expressServer.locals.viteServer = viteServer;
17
+ expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
18
+ expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
19
+ expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer));
20
+ expressServer.listen(PORT);
21
+ console.log(`
22
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at http://localhost:${PORT})
23
+ `);
24
+ }
25
+ export default createDevServer;
@@ -0,0 +1,26 @@
1
+ import { createServer as createViteServer } from 'vite';
2
+ import { default as react } from '@vitejs/plugin-react';
3
+ import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
4
+ const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
5
+ async function createViteDevServer() {
6
+ return createViteServer({
7
+ appType: 'custom',
8
+ server: {
9
+ middlewareMode: true,
10
+ origin: `http://localhost:${PORT}`,
11
+ },
12
+ ssr: {
13
+ // TODO: might need more entries here to get things to resolve through
14
+ // resolveWebRootDepsPlugin
15
+ noExternal: '@hubspot/cms-components',
16
+ },
17
+ resolve: {
18
+ dedupe: ['react', 'react-dom', '@hubspot/cms-components'],
19
+ },
20
+ optimizeDeps: {
21
+ include: ['react', 'react-dom', 'react-dom/client'],
22
+ },
23
+ plugins: [react(), resolveIslandPlugin()],
24
+ });
25
+ }
26
+ export default createViteDevServer;
@@ -0,0 +1,12 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <title><!--title--></title>
6
+ <!--headend-->
7
+ </head>
8
+ <body>
9
+ <div id="root"><!--ssr-outlet--></div>
10
+ <!--bodyend-->
11
+ </body>
12
+ </html>
@@ -0,0 +1,3 @@
1
+ export default function fullOriginalUrlFromRequest(request) {
2
+ return `${request.protocol}://${request.get('host')}${request.originalUrl}`;
3
+ }
@@ -0,0 +1,10 @@
1
+ export const rewriteAbsoluteJsAndCssPaths = (body, host, protocol = 'https://') => {
2
+ // TODO, do we need to worry about any fully relative references? (./whatever/...)
3
+ // Maybe the renderer doesn't typically output those, and when customers do that manually
4
+ // it (probably?) is after the `<base>` element?
5
+ return body.replace(/(src|href)="(\/[^/])/g, `$1="${protocol}${host}$2`);
6
+ };
7
+ export const addBaseTag = (html, urlToProxy) => {
8
+ const baseDomain = new URL(urlToProxy).origin;
9
+ return html.replace('<head>', `<head>\n<base href="${baseDomain}">\n`);
10
+ };
@@ -0,0 +1,11 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable consistent-return */
3
+ import { COMPONENT_EXTENSIONS } from '@hubspot/cms-js-internal';
4
+ export const findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
5
+ for (const extension of COMPONENT_EXTENSIONS) {
6
+ const pathToTry = `${modulePathNoExtension}${extension}`;
7
+ if (moduleGraph.fileToModulesMap.has(pathToTry)) {
8
+ return pathToTry;
9
+ }
10
+ }
11
+ };
@@ -0,0 +1,69 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable consistent-return */
3
+ import fs from 'fs';
4
+ const localJsRenderStartString = '<!-- proxy local render of "';
5
+ // const localJsRenderStartRegex = /<!-- proxy local render of "([^"]+)"/;
6
+ const localJsRenderEndString = 'end proxy local render -->';
7
+ export const findLocalRenderPlaceholders = (body) => {
8
+ let offsetSoFar = 0;
9
+ const result = [];
10
+ while (offsetSoFar < body.length && offsetSoFar !== -1) {
11
+ // Get start of local render block
12
+ const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
13
+ offsetSoFar = startOffset;
14
+ if (startOffset >= 0) {
15
+ const nextNewlineOffset = body.indexOf('\n', startOffset + localJsRenderStartString.length);
16
+ const pathEndOffset = body.indexOf('"', startOffset + localJsRenderStartString.length);
17
+ const nearestNewlineOrQuoteAfterBlockOpen = Math.min(nextNewlineOffset, pathEndOffset);
18
+ // Keep on moving our "where we've scanned so far" pointer
19
+ offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
20
+ if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
21
+ // Pull the path out of double quotes after the block opening
22
+ const path = body.substring(startOffset + localJsRenderStartString.length, pathEndOffset);
23
+ offsetSoFar = pathEndOffset + 1;
24
+ // console.log(`${startOffset}: path = ${path}`);
25
+ // If we're in a valid bloc so far that exists and has a path...
26
+ if (startOffset >= 0 && path) {
27
+ const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);
28
+ const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
29
+ offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
30
+ // Make sure that there is an ending to the block and there is not another
31
+ // HTML end comment string before it
32
+ if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
33
+ // Then pull out the JSON in the middle and try to parse it
34
+ const jsonString = body
35
+ .substring(pathEndOffset + 1, endOffset)
36
+ .trim();
37
+ // console.log(`${endOffset}: jsonString = ${jsonString}`);
38
+ try {
39
+ const json = JSON.parse(jsonString);
40
+ result.push({
41
+ startOffset,
42
+ endOffset: endOffset + localJsRenderEndString.length,
43
+ path,
44
+ json,
45
+ });
46
+ offsetSoFar = endOffset + localJsRenderEndString.length;
47
+ }
48
+ catch (e) {
49
+ console.error(`Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`);
50
+ offsetSoFar = endOffset;
51
+ }
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+ return result;
58
+ };
59
+ const getHSProjectConfig = hsProjectConfigPath => {
60
+ try {
61
+ return JSON.parse(fs.readFileSync(hsProjectConfigPath, 'utf8'));
62
+ }
63
+ catch (e) {
64
+ console.warn('Missing hsproject.json file: ', e.message);
65
+ }
66
+ };
67
+ export const getProjectNameFromHSConfig = hsProjectConfigPath => {
68
+ return getHSProjectConfig(hsProjectConfigPath).name;
69
+ };
@@ -0,0 +1,136 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { findLocalRenderPlaceholders } from './proxyHelpers.js';
3
+ describe('proxyHelpers', () => {
4
+ describe('findLocalRenderPlaceholders', () => {
5
+ it('should do nothing with an empty string', () => {
6
+ const result = findLocalRenderPlaceholders('');
7
+ expect(result).toEqual([]);
8
+ });
9
+ it('should do nothing with a regular HTML comment', () => {
10
+ const result = findLocalRenderPlaceholders('<!-- -->');
11
+ expect(result).toEqual([]);
12
+ });
13
+ it('should do nothing with a regular HTML comment across newlines', () => {
14
+ const result = findLocalRenderPlaceholders(`<!--
15
+ -->`);
16
+ expect(result).toEqual([]);
17
+ });
18
+ it('should do nothing with a never ending HTML comment', () => {
19
+ const result = findLocalRenderPlaceholders(`<!--`);
20
+ expect(result).toEqual([]);
21
+ });
22
+ it('extracts placeholder with nothing before or after it', () => {
23
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
24
+ {
25
+ "the": "props",
26
+ "that": ["need", "to"],
27
+ "be": {
28
+ "passed": "along"
29
+ }
30
+ }
31
+ end proxy local render -->`);
32
+ expect(result.length).toBe(1);
33
+ expect(result[0]).toMatchSnapshot();
34
+ });
35
+ it('extracts placeholder with some HTML around it', () => {
36
+ const result = findLocalRenderPlaceholders(`
37
+ <p>asdf</p>
38
+ <div>
39
+ <!-- proxy local render of "/some/path/to/entry.js"
40
+ {
41
+ "the": "props",
42
+ "that": ["need", "to"],
43
+ "be": {
44
+ "passed": "along"
45
+ }
46
+ }
47
+ end proxy local render -->
48
+ </div>
49
+
50
+ <em>FIN</em>
51
+ `);
52
+ expect(result.length).toBe(1);
53
+ expect(result[0]).toMatchSnapshot();
54
+ });
55
+ it('extacts two placholder blocks immediately after one another', () => {
56
+ const result = findLocalRenderPlaceholders(`<p>asdf</p>
57
+ <div>
58
+ <!-- proxy local render of "/some/path/to/entry.js"
59
+ {
60
+ "the": "props",
61
+ "that": ["need", "to"],
62
+ "be": {
63
+ "passed": "along"
64
+ }
65
+ }
66
+ end proxy local render --><!-- proxy local render of "/some/path/to/entry2.js"
67
+ {
68
+ "the": "props22222",
69
+ "that": ["need", "to"],
70
+ "be": {
71
+ "passed": "along"
72
+ }
73
+ }
74
+ end proxy local render -->
75
+ </div>
76
+
77
+ <em>FIN</em>
78
+ `);
79
+ expect(result.length).toBe(2);
80
+ expect(result[0]).toMatchSnapshot();
81
+ expect(result[1]).toMatchSnapshot();
82
+ });
83
+ it('extacts a placeholder with empty json', () => {
84
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
85
+ {
86
+ }
87
+ end proxy local render -->`);
88
+ expect(result.length).toBe(1);
89
+ expect(result[0]).toMatchSnapshot();
90
+ });
91
+ it('extacts a placeholder with empty json - 2', () => {
92
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
93
+ {}
94
+ end proxy local render -->`);
95
+ expect(result.length).toBe(1);
96
+ expect(result[0]).toMatchSnapshot();
97
+ });
98
+ it('extacts one placholder after a broken incomplete path', () => {
99
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "incomplete path
100
+ -->
101
+ <!-- proxy local render of "/some/path/to/afterMissingPath.js"
102
+ {
103
+ }
104
+ end proxy local render -->`);
105
+ expect(result.length).toBe(1);
106
+ expect(result[0]).toMatchSnapshot();
107
+ });
108
+ it('extacts one placholder after a uncompleted regular HTML comment', () => {
109
+ const result = findLocalRenderPlaceholders(`<!-- WHATEVER
110
+ -->
111
+ <!-- proxy local render of "/some/path/to/afterBustedHtmlComment.js"
112
+ {
113
+ }
114
+ end proxy local render -->`);
115
+ expect(result.length).toBe(1);
116
+ expect(result[0]).toMatchSnapshot();
117
+ });
118
+ it('extacts one placeholder after one with broken missing json', () => {
119
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "path/Before/missingJson"
120
+ -->
121
+ <!-- proxy local render of "/some/path/to/afterMissingJson.js"
122
+ {
123
+ }
124
+ end proxy local render -->`);
125
+ expect(result.length).toBe(1);
126
+ expect(result[0]).toMatchSnapshot();
127
+ });
128
+ it('does not extact broken placeholder with invalid json', () => {
129
+ const result = findLocalRenderPlaceholders(`<!-- proxy local render of "/some/path/to/entry.js"
130
+ Invalid json
131
+ }
132
+ end proxy local render -->`);
133
+ expect(result).toEqual([]);
134
+ });
135
+ });
136
+ });
@@ -0,0 +1,26 @@
1
+ import { hasComponentExtension, removeComponentExtension, } from '@hubspot/cms-js-internal';
2
+ import { findFullPathInModuleGraph } from './moduleGraph.js';
3
+ async function renderComponentWithCSS(viteServer, componentPath, Component, props, pageUrl) {
4
+ // Need to make sure rendering happens in Vite SSR context
5
+ const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
6
+ let componentPathWithExtension;
7
+ let componentPathNoExtension;
8
+ // Support paths with or without an extension (do we need/want both?)
9
+ if (hasComponentExtension(componentPath)) {
10
+ componentPathWithExtension = componentPath;
11
+ componentPathNoExtension = removeComponentExtension(componentPath);
12
+ }
13
+ else {
14
+ componentPathNoExtension = componentPath;
15
+ }
16
+ const { html, renderContext } = await renderComponentOnServer(Component, props, pageUrl);
17
+ if (!componentPathWithExtension) {
18
+ componentPathWithExtension = findFullPathInModuleGraph(componentPathNoExtension, viteServer.moduleGraph);
19
+ if (!componentPathWithExtension) {
20
+ throw new Error(`Couldn't find full path to component: ${componentPathNoExtension}`);
21
+ }
22
+ }
23
+ const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
24
+ return { html, cssNeeded, renderContext };
25
+ }
26
+ export default renderComponentWithCSS;
@@ -0,0 +1,21 @@
1
+ const getPropsInfo = props => {
2
+ const propsSizeInBytes = Buffer.from(JSON.stringify(props)).length;
3
+ if (propsSizeInBytes > 1000000) {
4
+ // If props byte size is > 1mb, show size in red
5
+ return ['\x1b[31m', `${(propsSizeInBytes / 1000000).toFixed(2)}mb`];
6
+ }
7
+ else if (propsSizeInBytes > 10000) {
8
+ // if props byte size is between 10kb and 1mb, show size in yellow
9
+ return ['\x1b[33m', `${(propsSizeInBytes / 1000).toFixed(2)}kb`];
10
+ }
11
+ else {
12
+ // Show size in green
13
+ return ['\x1b[32m', `${(propsSizeInBytes / 1000).toFixed(2)}kb`];
14
+ }
15
+ };
16
+ export const logPartialInfo = (partialPath, props) => {
17
+ console.log('Rendering partial', partialPath);
18
+ console.group();
19
+ console.log('Props size: ', ...getPropsInfo(props));
20
+ console.groupEnd();
21
+ };
@@ -0,0 +1,88 @@
1
+ import { join as joinPath } from 'path';
2
+ import { cloneElement } from 'react';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
4
+ import renderComponentWithCSS from './renderComponentWithCSS.js';
5
+ import { traverseFieldsJSON } from '@hubspot/cms-components/fields';
6
+ import { hasComponentExtension } from '@hubspot/cms-js-internal';
7
+ const lookForModuleInFolder = async (modulePath, viteServer) => {
8
+ let componentModule;
9
+ const insideFolderPath = joinPath(modulePath, 'index');
10
+ try {
11
+ componentModule = await viteServer.ssrLoadModule(insideFolderPath);
12
+ }
13
+ catch (e) {
14
+ if (!e.message.includes('failed to load module')) {
15
+ throw e;
16
+ }
17
+ }
18
+ return [componentModule, insideFolderPath];
19
+ };
20
+ async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}, pageUrl) {
21
+ console.log('Rendering module', requestedModulePath);
22
+ let componentModule;
23
+ let foundPath;
24
+ if (!hasComponentExtension(requestedModulePath)) {
25
+ [componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
26
+ }
27
+ if (!componentModule) {
28
+ // Look for non-folder module
29
+ componentModule = await viteServer.ssrLoadModule(requestedModulePath);
30
+ foundPath = componentModule ? requestedModulePath : undefined;
31
+ }
32
+ if (!componentModule) {
33
+ throw new Error(`Couldn't find module: ${requestedModulePath}`);
34
+ }
35
+ const Component = componentModule.Component;
36
+ const fields = componentModule.fields;
37
+ const meta = componentModule.meta;
38
+ if (!Component) {
39
+ throw new Error(`Module does not have a named Component export: ${foundPath}`);
40
+ }
41
+ else if (!fields) {
42
+ throw new Error(`Module does not have a named fields export: ${foundPath}`);
43
+ }
44
+ else if (!meta) {
45
+ throw new Error(`Module does not have a named meta export: ${foundPath}`);
46
+ }
47
+ const fieldsJSON = renderFieldsToJson(fields);
48
+ const props = getPropsForModule(fieldsJSON, fieldOverrides);
49
+ return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl);
50
+ }
51
+ // TODO, move to cms-js-internal?
52
+ function setInHelper(object, nestedKeysArray, value) {
53
+ let curr = object;
54
+ const finalKey = nestedKeysArray.pop();
55
+ for (let index = 0; index < nestedKeysArray.length; index++) {
56
+ const currentKey = nestedKeysArray[index];
57
+ const nextKey = nestedKeysArray[index + 1];
58
+ if (Number.isInteger(nextKey) || (!nextKey && Number.isInteger(finalKey))) {
59
+ if (curr[currentKey] === undefined) {
60
+ curr[currentKey] = [];
61
+ }
62
+ }
63
+ if (curr[currentKey] === undefined) {
64
+ curr[currentKey] = {};
65
+ }
66
+ curr = curr[currentKey];
67
+ }
68
+ curr[finalKey] = value;
69
+ }
70
+ function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
71
+ const props = {};
72
+ traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
73
+ setInHelper(props, fieldPathArray, value);
74
+ });
75
+ return props;
76
+ }
77
+ // TODO, move to cms-js-internal? (also in resolveModulesPlugin.ts)
78
+ function renderFieldsToJson(fields) {
79
+ let moduleJson;
80
+ const outputCallback = callbackJson => {
81
+ moduleJson = callbackJson;
82
+ };
83
+ renderToStaticMarkup(cloneElement(fields, {
84
+ outputCallback,
85
+ }));
86
+ return moduleJson;
87
+ }
88
+ export default renderModule;
@@ -0,0 +1,12 @@
1
+ import renderComponentWithCSS from './renderComponentWithCSS.js';
2
+ import { logPartialInfo } from './renderHelpers.js';
3
+ async function renderPartial(viteServer, partialPath, props, pageUrl) {
4
+ logPartialInfo(partialPath, props);
5
+ const componentModule = await viteServer.ssrLoadModule(partialPath);
6
+ const Component = componentModule.default;
7
+ if (!componentModule) {
8
+ throw new Error(`Couldn't find partial: ${partialPath}`);
9
+ }
10
+ return renderComponentWithCSS(viteServer, partialPath, Component, props, pageUrl);
11
+ }
12
+ export default renderPartial;
@@ -0,0 +1,49 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable @typescript-eslint/no-shadow */
3
+ import { promises as fsPromises } from 'fs';
4
+ import { sortIslandRootsByPriority, createIslandsGlobalJsForClientInDev, getServerGlobalsToInject, } from '@hubspot/cms-js-internal';
5
+ const { readFile } = fsPromises;
6
+ const ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK = `<script type="module">
7
+ import { setupIslandHydration } from '@hubspot/cms-components/island-runtime';
8
+ setupIslandHydration();
9
+ </script>
10
+ `;
11
+ const createdPlainHtmlTemplate = async (baseTemplatePath, title) => {
12
+ const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');
13
+ return htmlTemplateBase.replace('<!--title-->', title);
14
+ };
15
+ const createIslandHtmlTemplate = async (baseTemplatePath, title) => {
16
+ let htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
17
+ htmlTemplate = htmlTemplate.replace('<!--bodyend-->', `
18
+ ${ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK}
19
+ <!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->
20
+ <!--islandsglobal-->
21
+ `);
22
+ return htmlTemplate;
23
+ };
24
+ export const createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url, title, renderContext, viteServer) => {
25
+ let htmlTemplate;
26
+ if (renderContext.islands.length) {
27
+ htmlTemplate = await createIslandHtmlTemplate(baseTemplatePath, title);
28
+ const sortedIslandRoots = sortIslandRootsByPriority(renderContext.islands);
29
+ htmlTemplate = htmlTemplate.replace('<!--islandsglobal-->', `<script>
30
+ ${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}
31
+ </script>
32
+ ${getServerGlobalsToInject(renderContext.pageUrl)}
33
+ `);
34
+ }
35
+ else {
36
+ htmlTemplate = await createdPlainHtmlTemplate(baseTemplatePath, title);
37
+ }
38
+ return viteServer.transformIndexHtml(url, htmlTemplate);
39
+ };
40
+ export const getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, viteServer, devServerHost, devServerPort) => {
41
+ const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
42
+ // Loading through vite so all of nested `@hubspot/cms-*` imports work
43
+ const { createIslandsGlobalJsForClientInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
44
+ let islandRuntimeScript = await viteServer.transformIndexHtml('/', ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK);
45
+ islandRuntimeScript = islandRuntimeScript.replace('import RefreshRuntime from "/@react-refresh"', `import RefreshRuntime from "http://${serverDomainAndPort}/@react-refresh"`);
46
+ return `${islandRuntimeScript}
47
+ <script>${createIslandsGlobalJsForClientInDev(sortedIslandRoots, viteServer, 4)}</script>
48
+ `;
49
+ };
@@ -0,0 +1,52 @@
1
+ import path from 'path';
2
+ import { readdirSync } from 'fs';
3
+ const PARTIAL_SOURCE_DIR = 'components/partials';
4
+ function getAllComponentFilenamesIn(dirPath) {
5
+ return readdirSync(dirPath).filter(filename => {
6
+ const ext = path.extname(filename);
7
+ return ext === '.jsx' || ext === '.tsx';
8
+ });
9
+ }
10
+ const buildMockPartialModule = entryPointsFileNames => {
11
+ return entryPointsFileNames
12
+ .map(filename => {
13
+ const ext = path.extname(filename);
14
+ const withoutExtension = path.basename(filename, ext);
15
+ return `export const ${withoutExtension} = () => import('/${PARTIAL_SOURCE_DIR}/${filename}');`;
16
+ })
17
+ .join('\n');
18
+ };
19
+ // Not needed in dev unless some code wants to do `import { SomePartial } from 'components/partials'`
20
+ export default function devMockClientEntryPlugin(webRoot) {
21
+ const ENTRY_POINTS_PATH = path.resolve(webRoot, PARTIAL_SOURCE_DIR);
22
+ const MOCK_ENTRY_PATH = `${ENTRY_POINTS_PATH}/index.js`;
23
+ return {
24
+ enforce: 'pre',
25
+ name: 'client-entry',
26
+ options(options) {
27
+ if (!options.input) {
28
+ return {
29
+ ...options,
30
+ input: [MOCK_ENTRY_PATH],
31
+ };
32
+ }
33
+ return options;
34
+ },
35
+ async resolveId(source) {
36
+ if (source === PARTIAL_SOURCE_DIR /*&& options.isEntry*/) {
37
+ return {
38
+ id: source,
39
+ moduleSideEffects: 'no-treeshake',
40
+ };
41
+ }
42
+ return null;
43
+ },
44
+ load(id) {
45
+ if (id === PARTIAL_SOURCE_DIR) {
46
+ const entryPointsFileNames = getAllComponentFilenamesIn(ENTRY_POINTS_PATH);
47
+ return buildMockPartialModule(entryPointsFileNames);
48
+ }
49
+ return null;
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,4 @@
1
+ export const VALID_PROXY_DOMAIN_SUFFIXES = [
2
+ 'localhost',
3
+ // 'hslocal.dev', // TODO not real yet
4
+ ];
@@ -0,0 +1,51 @@
1
+ import http from 'http';
2
+ import https from 'https';
3
+ export default async function getContentMetadata(url, redirects = 0, originalUrl) {
4
+ if (redirects > 5) {
5
+ throw new Error(`Hit too many redirects to HEAD requests for ${originalUrl}`);
6
+ }
7
+ return new Promise((resolve, reject) => {
8
+ const protocolAPI = url.startsWith('https://') ? https : http;
9
+ protocolAPI
10
+ .request(url, {
11
+ method: 'HEAD',
12
+ headers: {
13
+ // Keep this user agent, so we don't get 403s from the request
14
+ ['User-Agent']: 'cms-dev-server',
15
+ },
16
+ }, res => {
17
+ // Use a lib to better follow various redirects?
18
+ if (res.statusCode >= 300 &&
19
+ res.statusCode < 400 &&
20
+ res.headers.location) {
21
+ console.log(`Redirecting to ${res.headers.location} (from ${url})`);
22
+ return resolve(getContentMetadata(res.headers.location, redirects + 1, originalUrl ?? url));
23
+ }
24
+ const portalIdHeader = res.headers['x-hs-hub-id'];
25
+ const contentId = res.headers['x-hs-content-id'];
26
+ if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
27
+ return reject(new Error(`There were multiple hub ID or content ID headers in the HEAD request to ${url}`));
28
+ }
29
+ else {
30
+ const portalId = parseInt(portalIdHeader, 10);
31
+ if (res.statusCode !== 200) {
32
+ return reject(new Error(`${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url}. ${res.statusCode === 429 && res.headers['retry-after']
33
+ ? `Retry after ${res.headers['retry-after']} seconds.`
34
+ : ''}`));
35
+ }
36
+ else if (!portalId || !contentId) {
37
+ return reject(new Error(`Missing hub ID or content ID headers on HEAD request to ${url}`));
38
+ }
39
+ else if (isNaN(portalId)) {
40
+ return reject(new Error(`Hub ID from the HEAD request is not a number: '${portalId}' (${url})`));
41
+ }
42
+ return resolve({ portalId, contentId });
43
+ }
44
+ })
45
+ .on('error', err => {
46
+ console.error(err);
47
+ reject(err);
48
+ })
49
+ .end();
50
+ });
51
+ }