@hubspot/cms-dev-server 1.1.0-prerelease.7 → 1.1.0-prerelease.8

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 (34) hide show
  1. package/dist/lib/argHelpers.js +6 -0
  2. package/dist/lib/cli.js +23 -0
  3. package/dist/lib/renderHelpers.js +34 -10
  4. package/dist/plugins/devMockClientEntryPlugin.js +1 -1
  5. package/dist/routes/module.js +2 -1
  6. package/dist/routes/partial.js +2 -1
  7. package/package.json +4 -4
  8. package/dist/routes/proxyPage.js +0 -205
  9. package/dist/run.mjs +0 -10
  10. package/dist/src/components/ModulesList.js +0 -14
  11. package/dist/src/components/PartialsList.js +0 -13
  12. package/dist/src/createDevServer.js +0 -45
  13. package/dist/src/lib/htmlHelpers.js +0 -10
  14. package/dist/src/lib/moduleGraph.js +0 -9
  15. package/dist/src/lib/proxyHelpers.js +0 -55
  16. package/dist/src/lib/proxyHelpers.test.js +0 -136
  17. package/dist/src/lib/renderComponentWithCSS.js +0 -26
  18. package/dist/src/lib/renderModule.js +0 -84
  19. package/dist/src/lib/renderPartial.js +0 -11
  20. package/dist/src/lib/templates.js +0 -50
  21. package/dist/src/plugins/devMockClientEntryPlugin.js +0 -52
  22. package/dist/src/proxyPage/constants.js +0 -4
  23. package/dist/src/proxyPage/fetchContentMetadata.js +0 -40
  24. package/dist/src/proxyPage/fetchPreviewInfo.js +0 -25
  25. package/dist/src/proxyPage/proxyPage.js +0 -147
  26. package/dist/src/proxyPage/renderLocalError.js +0 -1
  27. package/dist/src/proxyPage/utils.js +0 -36
  28. package/dist/src/routes/createDevServerRoutes.js +0 -19
  29. package/dist/src/routes/homeRouteHandler.js +0 -12
  30. package/dist/src/routes/linksToAllModulesRouteHandler.js +0 -10
  31. package/dist/src/routes/linksToAllPartialsRouteHandler.js +0 -10
  32. package/dist/src/routes/module.js +0 -26
  33. package/dist/src/routes/partial.js +0 -26
  34. package/dist/src/routes/proxyPageRouteHandler.js +0 -28
@@ -0,0 +1,6 @@
1
+ export const getLongArgumentFrom = (args, argToLookFor) => {
2
+ const argIndex = process.argv.indexOf(argToLookFor);
3
+ if (argIndex > 0 && argIndex <= args.length) {
4
+ return args[argIndex + 1];
5
+ }
6
+ };
@@ -0,0 +1,23 @@
1
+ import { resolve } from 'path';
2
+ export function getDevServerCommandLineOptions(argv) {
3
+ const args = [...argv];
4
+ const webRoot = args[2];
5
+ let hubspotCliConfigPathOption;
6
+ let hubspotCliAccountNameOption;
7
+ // Very basic CLI option parsing
8
+ const configOptionIndex = args.findIndex(arg => arg === '-c' || arg === '--config');
9
+ if (configOptionIndex > 0 && args.length > configOptionIndex) {
10
+ hubspotCliConfigPathOption = resolve(args[configOptionIndex + 1]);
11
+ args.splice(configOptionIndex, 2);
12
+ }
13
+ const accountOptionIndex = args.findIndex(arg => arg === '-a' || arg === '--account');
14
+ if (accountOptionIndex > 0 && args.length > accountOptionIndex) {
15
+ hubspotCliAccountNameOption = args[accountOptionIndex + 1];
16
+ args.splice(accountOptionIndex, 2);
17
+ }
18
+ return {
19
+ webRoot,
20
+ hubspotCliConfigPathOption,
21
+ hubspotCliAccountNameOption,
22
+ };
23
+ }
@@ -1,21 +1,45 @@
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`];
1
+ function getByteSizeOf(props) {
2
+ return Buffer.from(JSON.stringify(props)).length;
3
+ }
4
+ function formatBytesToString(bytes) {
5
+ if (bytes > 1000000) {
6
+ // If byte size is > 1mb, show size in red
7
+ return ['\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`];
6
8
  }
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`];
9
+ else if (bytes > 10000) {
10
+ // if byte size is between 10kb and 1mb, show size in yellow
11
+ return ['\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`];
10
12
  }
11
13
  else {
12
14
  // Show size in green
13
- return ['\x1b[32m', `${(propsSizeInBytes / 1000).toFixed(2)}kb`];
15
+ return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`];
14
16
  }
17
+ }
18
+ const getPropsInfo = (props, reportOptions = { showNestedKeySizeIfGreater: null }, recursionDepth = 0) => {
19
+ if (recursionDepth > 8) {
20
+ return [];
21
+ }
22
+ const propsSizeInBytes = getByteSizeOf(props);
23
+ const result = formatBytesToString(propsSizeInBytes);
24
+ if (!Array.isArray(props) &&
25
+ Object.keys(props).length > 0 &&
26
+ reportOptions.showNestedKeySizeIfGreater != null &&
27
+ propsSizeInBytes > reportOptions.showNestedKeySizeIfGreater) {
28
+ for (const [key, value] of Object.entries(props)) {
29
+ const size = getPropsInfo(value, reportOptions, recursionDepth + 1);
30
+ if (Array.isArray(value)) {
31
+ result.push('\n', `${key}[${value.length}]`, ...size);
32
+ }
33
+ else {
34
+ result.push('\n', key, ...size);
35
+ }
36
+ }
37
+ }
38
+ return result.flat();
15
39
  };
16
40
  export const logPartialInfo = (partialPath, props) => {
17
41
  console.log('Rendering partial', partialPath);
18
42
  console.group();
19
- console.log('Props size: ', ...getPropsInfo(props));
43
+ console.log('Props size: ', ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 }));
20
44
  console.groupEnd();
21
45
  };
@@ -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,
@@ -1,11 +1,12 @@
1
1
  import path from 'path';
2
+ import url from 'url';
2
3
  import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
3
4
  import renderModule from '../lib/renderModule.js';
4
5
  import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
5
6
  const moduleRouteHandler = async (request, response) => {
6
7
  const { webRoot, viteServer } = request.app.locals;
7
8
  const moduleName = request.params.moduleName;
8
- const baseTemplatePath = path.join(import.meta.url.replace('file://', ''), '../../html/baseTemplate.html');
9
+ const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../../html/baseTemplate.html');
9
10
  const modulePath = path.resolve(webRoot, 'components/modules/', moduleName);
10
11
  try {
11
12
  const { html: renderedHtml, cssNeeded, renderContext, } = await renderModule(viteServer, modulePath, null, fullOriginalUrlFromRequest(request));
@@ -1,11 +1,12 @@
1
1
  import path from 'path';
2
+ import url from 'url';
2
3
  import fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';
3
4
  import renderPartial from '../lib/renderPartial.js';
4
5
  import { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';
5
6
  const partialRouteHandler = async (request, response) => {
6
7
  const { webRoot, viteServer } = request.app.locals;
7
8
  const partialName = request.params.partial;
8
- const baseTemplatePath = path.join(import.meta.url.replace('file://', ''), '../../html/baseTemplate.html');
9
+ const baseTemplatePath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), '../../html/baseTemplate.html');
9
10
  const partialPath = path.resolve(webRoot, 'components/partials/', partialName);
10
11
  try {
11
12
  const { html: renderedHtml, cssNeeded, renderContext, } = await renderPartial(viteServer, partialPath, {}, fullOriginalUrlFromRequest(request));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "1.1.0-prerelease.7",
3
+ "version": "1.1.0-prerelease.8",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/createViteDevServer.js",
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@hubspot/cli-lib": "^3.0.12",
24
- "@hubspot/cms-components": "^1.1.0-prerelease.7",
25
- "@hubspot/cms-js-internal": "^1.1.0-prerelease.7",
24
+ "@hubspot/cms-components": "^1.1.0-prerelease.8",
25
+ "@hubspot/cms-js-internal": "^1.1.0-prerelease.8",
26
26
  "@vitejs/plugin-react": "^2.0.0",
27
27
  "ansi-to-html": "0.7.x",
28
28
  "express": "^4.17.3",
@@ -64,5 +64,5 @@
64
64
  "publishConfig": {
65
65
  "access": "public"
66
66
  },
67
- "gitHead": "254eaaa461326ec5fecb911c3e7954527aa1741b"
67
+ "gitHead": "6f94d6cfa5034605913264f991337056b3ac53fc"
68
68
  }
@@ -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
- });