@hubspot/cms-dev-server 1.1.0-prerelease.2 → 1.1.0-prerelease.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.
@@ -18,6 +18,7 @@ async function createDevServer(webRoot) {
18
18
  expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
19
19
  expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer));
20
20
  expressServer.listen(PORT);
21
+ console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
21
22
  console.log(`
22
23
  HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at http://localhost:${PORT})
23
24
  `);
@@ -32,7 +32,7 @@ export default function devMockClientEntryPlugin(webRoot) {
32
32
  }
33
33
  return options;
34
34
  },
35
- async resolveId(source) {
35
+ async resolveId(source, importer, options) {
36
36
  if (source === PARTIAL_SOURCE_DIR /*&& options.isEntry*/) {
37
37
  return {
38
38
  id: source,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "1.1.0-prerelease.2",
3
+ "version": "1.1.0-prerelease.4",
4
4
  "type": "module",
5
5
  "main": "./dist/createViteDevServer.js",
6
6
  "scripts": {
@@ -17,8 +17,8 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "@hubspot/cli-lib": "^3.0.12",
20
- "@hubspot/cms-components": "^1.1.0-prerelease.2",
21
- "@hubspot/cms-js-internal": "^1.1.0-prerelease.2",
20
+ "@hubspot/cms-components": "^1.1.0-prerelease.4",
21
+ "@hubspot/cms-js-internal": "^1.1.0-prerelease.4",
22
22
  "@vitejs/plugin-react": "^2.0.0",
23
23
  "ansi-to-html": "0.7.x",
24
24
  "express": "^4.17.3",
@@ -61,5 +61,5 @@
61
61
  "publishConfig": {
62
62
  "access": "public"
63
63
  },
64
- "gitHead": "330e82ed2299c04e65795ea2149f721ce4b314e1"
64
+ "gitHead": "48f05583415f59bcfd6e191a0031660fd4f316c0"
65
65
  }
@@ -1,205 +0,0 @@
1
- import path from 'path';
2
- import { getAccountId } from '@hubspot/cli-lib/lib/config.js';
3
- import { get as hsGet } from '@hubspot/cli-lib/http.js';
4
- import { createRenderInfoContext } from '@hubspot/cms-components';
5
- import { findLocalRenderPlaceholders, } from '../lib/proxyHelpers.js';
6
- import renderPartial from '../lib/renderPartial.js';
7
- import { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';
8
- import { rewriteAbsoluteJsAndCssPaths } from '../lib/htmlHelpers.js';
9
- const fetchPreviewInfo = async (accountId, portalId, contentId) => {
10
- try {
11
- // Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]
12
- const content = await hsGet(accountId, {
13
- uri: `/content/api/v4/contents/${contentId}`,
14
- query: { portalId },
15
- json: true,
16
- });
17
- return {
18
- previewDomain: content.previewDomain ?? content.resolvedDomain,
19
- previewKey: content.previewKey,
20
- };
21
- }
22
- catch (error) {
23
- console.log(`error`, error);
24
- if (error.options) {
25
- console.log(`error.options`, error.options);
26
- }
27
- if (error.response && error.response.headers) {
28
- console.log(`error.response.headers`, error.response.headers);
29
- }
30
- throw error;
31
- }
32
- };
33
- const createPreviewQueryParams = (previewInfo) => {
34
- const { previewKey } = previewInfo;
35
- return {
36
- _preview: true,
37
- preview_key: previewKey,
38
- };
39
- };
40
- const createPreviewPath = (contentId) => {
41
- return `/_hcms/preview/content/${contentId}`;
42
- };
43
- const makeProxyPreviewRequest = (accountId, host, path, queryParams) => {
44
- console.log(`Proxying request to https://${host}${path}`);
45
- const result = hsGet(accountId, {
46
- baseUrl: `https://${host}`,
47
- uri: `${path}`,
48
- query: {
49
- ...queryParams,
50
- // Makes render_js_partial return comments instead of actually rendering
51
- hsLocalProxy: true,
52
- },
53
- json: false,
54
- });
55
- console.log('hsGet', `https://${host}${path}`, queryParams);
56
- return result.catch((error) => {
57
- if (error.statusCode >= 400 &&
58
- error.statusCode < 500 &&
59
- !!error.response.body) {
60
- return error.response.body;
61
- }
62
- else {
63
- throw error;
64
- }
65
- });
66
- };
67
- const createLocalJsRenderErrorOutput = (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
68
- const randomStringWithLotsOf = (char, maxLength) => {
69
- return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');
70
- };
71
- const fakeRenderJsComponent = (indexForThisRender) => {
72
- return new Promise((resolve, reject) => {
73
- const randomTimeout = Math.floor(Math.random() * 200) + indexForThisRender * 1000;
74
- setTimeout(() => {
75
- try {
76
- const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${indexForThisRender + 1} (${randomTimeout}ms delay) ${randomStringWithLotsOf('?', 100)}</div>\n`;
77
- resolve({
78
- html: fakeJsRenderedOutput,
79
- cssNeeded: '',
80
- renderInfoContext: createRenderInfoContext(),
81
- });
82
- }
83
- catch (e) {
84
- console.log('Error with JS render...');
85
- console.error(e);
86
- reject();
87
- }
88
- }, randomTimeout);
89
- });
90
- };
91
- const renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder, webRoot, viteServer) => {
92
- if (localRenderPlaceholder.path.startsWith('/fake/path/to/')) {
93
- return fakeRenderJsComponent(indexForThisRender);
94
- }
95
- else if (localRenderPlaceholder.path.startsWith('components/partials/')) {
96
- const partialPath = path.resolve(webRoot, localRenderPlaceholder.path);
97
- return renderPartial(viteServer, partialPath, localRenderPlaceholder.json);
98
- }
99
- else {
100
- throw new Error(`Unimplemented render of ${localRenderPlaceholder.path}`);
101
- }
102
- };
103
- async function proxySpecificPage(response, portalId, contentId, currentUrl, webRoot, viteServer, devServerHost, devServerPort) {
104
- let accountId;
105
- try {
106
- accountId = getAccountId(portalId);
107
- }
108
- catch (e) {
109
- response
110
- .status(500)
111
- .end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
112
- return;
113
- }
114
- if (!accountId) {
115
- response
116
- .status(500)
117
- .end(`Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`);
118
- return;
119
- }
120
- try {
121
- const serverDomainAndPort = `${devServerHost}:${devServerPort}`;
122
- const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);
123
- const { previewDomain } = previewInfo;
124
- const previewPath = createPreviewPath(contentId);
125
- const previewQueryParams = createPreviewQueryParams(previewInfo);
126
- let pageHtml = await makeProxyPreviewRequest(accountId, previewDomain, previewPath, previewQueryParams);
127
- // TODO, this is only needed for asset references that happen _before_ the `<base href="...">` element
128
- // Is that only a preview URL thing? Or is it in all (most?) rendered CMS pages
129
- pageHtml = rewriteAbsoluteJsAndCssPaths(pageHtml, previewDomain, 'https://');
130
- // Loading through vite so all of nested `@hubspot/cms-*` imports work
131
- const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
132
- const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
133
- const numPlaceholders = localRenderPlaceholders.length;
134
- const totalNumHtmlChunks = numPlaceholders * 2 + 1;
135
- let numJsRenderFailures = 0;
136
- let islands = [];
137
- const renderPromisesByChunkIndex = new Array(numPlaceholders);
138
- if (localRenderPlaceholders.length > 0) {
139
- let offsetSoFar = 0;
140
- const pageChunks = new Array(numPlaceholders + 1);
141
- for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
142
- const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
143
- pageChunks[indexForThisRender] = pageHtml.slice(offsetSoFar, localRenderPlaceholder.startOffset);
144
- const renderPromise = renderComponentForPlaceholder(indexForThisRender, localRenderPlaceholder, webRoot, viteServer);
145
- renderPromisesByChunkIndex[indexForThisRender] = renderPromise
146
- .then((promiseResult) => {
147
- // eslint-disable-next-line prefer-const
148
- let { html, cssNeeded, renderInfoContext } = promiseResult;
149
- console.log(`Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`);
150
- if (renderInfoContext.islands.length > 0) {
151
- islands = islands.concat(renderInfoContext.islands);
152
- }
153
- if (cssNeeded) {
154
- // Note, this is needed for cases where `<base href="...">` is output by the renderer, so
155
- // that local asset URLs go to the local dev server
156
- cssNeeded = rewriteAbsoluteJsAndCssPaths(cssNeeded, serverDomainAndPort, 'http://');
157
- return `${cssNeeded}\n${html}`;
158
- }
159
- return html;
160
- })
161
- .catch((e) => {
162
- numJsRenderFailures += 1;
163
- console.error(e);
164
- return createLocalJsRenderErrorOutput(localRenderPlaceholder.path, e);
165
- });
166
- offsetSoFar = localRenderPlaceholder.endOffset;
167
- }
168
- // Last chunk from end of last placeholder to end of HTML
169
- pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
170
- response.writeHead(200);
171
- for (let i = 0; i < localRenderPlaceholders.length; i++) {
172
- const chunk = pageChunks[i];
173
- response.write(chunk);
174
- const foobar = await renderPromisesByChunkIndex[i];
175
- // console.log("JS rendered chunk", i, foobar);
176
- response.write(foobar);
177
- }
178
- if (islands.length > 0) {
179
- const sortedIslandRoots = sortIslandRootsByPriority(islands);
180
- const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(sortedIslandRoots, viteServer, devServerHost, devServerPort);
181
- response.write(islandRuntimeAndGlobalScriptHtml);
182
- }
183
- // Write last string chunk located after last placeholder
184
- response.write(pageChunks[pageChunks.length - 1]);
185
- response.end();
186
- }
187
- else {
188
- response.writeHead(200);
189
- response.write(pageHtml);
190
- response.end();
191
- }
192
- }
193
- catch (error) {
194
- // TODO change error.stack to error.message before we publish
195
- response
196
- .status(500)
197
- .end(`Failed proxy render of page id = ${contentId} hub id = ${portalId}\n\n${error.stack}`);
198
- return;
199
- }
200
- }
201
- async function proxyPageHandler(request, response) {
202
- const { packageRoot, viteServer, webRoot, devServerHost, devServerPort } = request.app.locals;
203
- await proxySpecificPage(response, parseInt(request.params.portalId, 10), request.params.contentId, request.originalUrl, webRoot, viteServer, devServerHost, devServerPort);
204
- }
205
- export default proxyPageHandler;
package/dist/run.mjs DELETED
@@ -1,10 +0,0 @@
1
- #!/usr/bin/env node
2
- import createDevServer from './src/createDevServer.js';
3
- import { dirname } from 'path';
4
- import { fileURLToPath } from 'url';
5
- const packageRoot = dirname(fileURLToPath(import.meta.url));
6
- const webRoot = process.argv[2];
7
- if (!webRoot) {
8
- throw new Error(`No web root path argument specified`);
9
- }
10
- createDevServer(packageRoot, webRoot);
@@ -1,14 +0,0 @@
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;
@@ -1,13 +0,0 @@
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
- }
@@ -1,45 +0,0 @@
1
- import express from 'express';
2
- import { createServer as createViteServer } from 'vite';
3
- import { default as react } from '@vitejs/plugin-react';
4
- import createDevServerRoutes from './routes/createDevServerRoutes.js';
5
- import devMockClientEntryPlugin from './plugins/devMockClientEntryPlugin.js';
6
- import { resolveIslandPlugin, resolveWebRootDepsPlugin, } from '@hubspot/cms-js-internal';
7
- const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD;
8
- const BASE_PATH = '/';
9
- const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
10
- async function createDevServer(packageRoot, webRoot) {
11
- const expressServer = express();
12
- const viteServer = await createViteServer({
13
- appType: 'custom',
14
- server: {
15
- middlewareMode: true,
16
- origin: `http://localhost:${PORT}`,
17
- },
18
- ssr: {
19
- // TODO: might need more entries here to get things to resolve through
20
- // resolveWebRootDepsPlugin
21
- noExternal: '@hubspot/cms-components',
22
- },
23
- optimizeDeps: {
24
- include: ['react', 'react-dom', 'react-dom/client'],
25
- },
26
- build: {},
27
- plugins: [
28
- react({ jsxRuntime: 'automatic' }),
29
- // @ts-ignore
30
- devMockClientEntryPlugin(webRoot),
31
- // @ts-ignore
32
- resolveIslandPlugin(),
33
- resolveWebRootDepsPlugin(webRoot, packageRoot),
34
- ],
35
- });
36
- expressServer.locals.devServerHost = 'localhost';
37
- expressServer.locals.devServerPort = PORT;
38
- expressServer.locals.packageRoot = packageRoot;
39
- expressServer.locals.webRoot = webRoot;
40
- expressServer.locals.viteServer = viteServer;
41
- expressServer.use(BASE_PATH, await createDevServerRoutes(packageRoot, webRoot, viteServer));
42
- expressServer.listen(PORT);
43
- console.log(`HubSpot CMS dev server listening at http://localhost:${PORT}`);
44
- }
45
- export default createDevServer;
@@ -1,10 +0,0 @@
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
- };
@@ -1,9 +0,0 @@
1
- import { COMPONENT_EXTENSIONS } from '@hubspot/cms-js-internal';
2
- export const findFullPathInModuleGraph = (modulePathNoExtension, moduleGraph) => {
3
- for (let extension of COMPONENT_EXTENSIONS) {
4
- const pathToTry = `${modulePathNoExtension}${extension}`;
5
- if (moduleGraph.fileToModulesMap.has(pathToTry)) {
6
- return pathToTry;
7
- }
8
- }
9
- };
@@ -1,55 +0,0 @@
1
- const localJsRenderStartString = '<!-- proxy local render of "';
2
- // const localJsRenderStartRegex = /<!-- proxy local render of "([^"]+)"/;
3
- const localJsRenderEndString = 'end proxy local render -->';
4
- export const findLocalRenderPlaceholders = (body) => {
5
- let offsetSoFar = 0;
6
- const result = [];
7
- while (offsetSoFar < body.length && offsetSoFar !== -1) {
8
- // Get start of local render block
9
- const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
10
- offsetSoFar = startOffset;
11
- if (startOffset >= 0) {
12
- const nextNewlineOffset = body.indexOf('\n', startOffset + localJsRenderStartString.length);
13
- const pathEndOffset = body.indexOf('"', startOffset + localJsRenderStartString.length);
14
- const nearestNewlineOrQuoteAfterBlockOpen = Math.min(nextNewlineOffset, pathEndOffset);
15
- // Keep on moving our "where we've scanned so far" pointer
16
- offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
17
- if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
18
- // Pull the path out of double quotes after the block opening
19
- const path = body.substring(startOffset + localJsRenderStartString.length, pathEndOffset);
20
- offsetSoFar = pathEndOffset + 1;
21
- // console.log(`${startOffset}: path = ${path}`);
22
- // If we're in a valid bloc so far that exists and has a path...
23
- if (startOffset >= 0 && path) {
24
- const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);
25
- const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
26
- offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
27
- // Make sure that there is an ending to the block and there is not another
28
- // HTML end comment string before it
29
- if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
30
- // Then pull out the JSON in the middle and try to parse it
31
- const jsonString = body
32
- .substring(pathEndOffset + 1, endOffset)
33
- .trim();
34
- // console.log(`${endOffset}: jsonString = ${jsonString}`);
35
- try {
36
- const json = JSON.parse(jsonString);
37
- result.push({
38
- startOffset,
39
- endOffset: endOffset + localJsRenderEndString.length,
40
- path,
41
- json,
42
- });
43
- offsetSoFar = endOffset + localJsRenderEndString.length;
44
- }
45
- catch (e) {
46
- console.error(`Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`);
47
- offsetSoFar = endOffset;
48
- }
49
- }
50
- }
51
- }
52
- }
53
- }
54
- return result;
55
- };
@@ -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) {
4
- // Need to make sure rendering happens in Vite SSR context
5
- const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
6
- let componentPathWithExtension;
7
- let componentPathNoExtension;
8
- // Support paths with or without an extension (do we need/want both?)
9
- if (hasComponentExtension(componentPath)) {
10
- componentPathWithExtension = componentPath;
11
- componentPathNoExtension = removeComponentExtension(componentPath);
12
- }
13
- else {
14
- componentPathNoExtension = componentPath;
15
- }
16
- const { html, renderInfoContext } = await renderComponentOnServer(Component, props, pageUrl);
17
- if (!componentPathWithExtension) {
18
- componentPathWithExtension = findFullPathInModuleGraph(componentPathNoExtension, viteServer.moduleGraph);
19
- if (!componentPathWithExtension) {
20
- throw new Error(`Couldn't find full path to component: ${componentPathNoExtension}`);
21
- }
22
- }
23
- const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
24
- return { html, cssNeeded, renderInfoContext };
25
- }
26
- export default renderComponentWithCSS;
@@ -1,84 +0,0 @@
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, pageUrl, fieldOverrides = {}) {
21
- console.log('Rendering module', requestedModulePath);
22
- let componentModule, foundPath;
23
- if (!hasComponentExtension(requestedModulePath)) {
24
- [componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
25
- }
26
- if (!componentModule) {
27
- // Look for non-folder module
28
- componentModule = await viteServer.ssrLoadModule(requestedModulePath);
29
- foundPath = componentModule ? requestedModulePath : undefined;
30
- }
31
- if (!componentModule) {
32
- throw new Error(`Couldn't find module: ${requestedModulePath}`);
33
- }
34
- const Component = componentModule.Component;
35
- const fields = componentModule.fields;
36
- const meta = componentModule.meta;
37
- if (!Component) {
38
- throw new Error(`Module does not have a named Component export: ${foundPath}`);
39
- }
40
- else if (!fields) {
41
- throw new Error(`Module does not have a named fields export: ${foundPath}`);
42
- }
43
- else if (!meta) {
44
- throw new Error(`Module does not have a named meta export: ${foundPath}`);
45
- }
46
- const fieldsJSON = renderFieldsToJson(fields);
47
- const props = getPropsForModule(fieldsJSON, fieldOverrides);
48
- return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl);
49
- }
50
- // TODO, move to cms-js-internal?
51
- function setInHelper(object, nestedKeysArray, value) {
52
- let curr = object;
53
- const finalKey = nestedKeysArray.pop();
54
- for (let nestedKey of nestedKeysArray) {
55
- if (Number.isInteger(nestedKey)) {
56
- // TODO support occurences/groups with numeric path keys
57
- throw new Error('TODO, support traversal of fields with occurances');
58
- }
59
- if (curr[nestedKey] === undefined) {
60
- curr[nestedKey] = {};
61
- }
62
- curr = curr[nestedKey];
63
- }
64
- curr[finalKey] = value;
65
- }
66
- function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
67
- const props = {};
68
- traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value, field) => {
69
- setInHelper(props, fieldPathArray, value);
70
- });
71
- return props;
72
- }
73
- // TODO, move to cms-js-internal? (also in resolveModulesPlugin.ts)
74
- function renderFieldsToJson(fields) {
75
- let moduleJson;
76
- const outputCallback = (callbackJson) => {
77
- moduleJson = callbackJson;
78
- };
79
- renderToStaticMarkup(cloneElement(fields, {
80
- outputCallback,
81
- }));
82
- return moduleJson;
83
- }
84
- export default renderModule;
@@ -1,11 +0,0 @@
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;
@@ -1,50 +0,0 @@
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
- };
@@ -1,52 +0,0 @@
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
- }
@@ -1,4 +0,0 @@
1
- export const VALID_PROXY_DOMAIN_SUFFIXES = [
2
- 'localhost',
3
- // 'hslocal.dev', // TODO not real yet
4
- ];
@@ -1,40 +0,0 @@
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
- }
@@ -1,25 +0,0 @@
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
- };
@@ -1,147 +0,0 @@
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
- }
@@ -1 +0,0 @@
1
- export default (path, error) => `<div data-js-rendered="error">Error rendering ${path}<br/><br/><code><pre>${error.stack}</pre></code></div>`;
@@ -1,36 +0,0 @@
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
- };
@@ -1,19 +0,0 @@
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;
@@ -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 } = 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;
@@ -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);
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);
8
- response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);
9
- };
10
- export default linksToAllPartialRouteHandler;
@@ -1,26 +0,0 @@
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;
@@ -1,26 +0,0 @@
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;
@@ -1,28 +0,0 @@
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
- }