@hubspot/cms-dev-server 0.4.18 → 0.5.0

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 (50) hide show
  1. package/dist/components/ModulesList.js +14 -0
  2. package/dist/components/PartialsList.js +13 -0
  3. package/dist/createDevServer.js +162 -0
  4. package/dist/createViteDevServer.js +51 -0
  5. package/dist/fsevents-72LCIACT.node +0 -0
  6. package/dist/index.js +2 -2
  7. package/dist/internalSsr.js +13 -6
  8. package/dist/lib/cli.js +27 -0
  9. package/dist/lib/debug.js +2 -0
  10. package/dist/lib/errors.js +22 -0
  11. package/dist/lib/fullOriginalUrlFromRequest.js +3 -0
  12. package/dist/lib/httpsRedirectingServer.js +48 -0
  13. package/dist/lib/moduleGraph.js +11 -0
  14. package/dist/lib/proxyHelpers.js +70 -0
  15. package/dist/lib/proxyHelpers.test.js +136 -0
  16. package/dist/lib/renderComponentWithCSS.js +26 -0
  17. package/dist/lib/renderHelpers.js +45 -0
  18. package/dist/lib/renderModule.js +56 -0
  19. package/dist/lib/renderPartial.js +15 -0
  20. package/dist/lib/templates.js +55 -0
  21. package/dist/proxyPage/constants.js +1 -0
  22. package/dist/proxyPage/fetchContentMetadata.js +59 -0
  23. package/dist/proxyPage/fetchDomains.js +29 -0
  24. package/dist/proxyPage/fetchPreviewInfo.js +37 -0
  25. package/dist/proxyPage/proxyPage.js +174 -0
  26. package/dist/proxyPage/renderLocalError.js +27 -0
  27. package/dist/proxyPage/utils.js +38 -0
  28. package/dist/routes/createDevServerRoutes.js +43 -0
  29. package/dist/routes/homeRouteHandler.js +12 -0
  30. package/dist/routes/linksToAllModulesRouteHandler.js +10 -0
  31. package/dist/routes/linksToAllPartialsRouteHandler.js +10 -0
  32. package/dist/routes/module.js +41 -0
  33. package/dist/routes/partial.js +30 -0
  34. package/dist/routes/proxyPageResourceRedirect.js +22 -0
  35. package/dist/routes/proxyPageRouteHandler.js +40 -0
  36. package/dist/routes/proxyPathPageResourceRedirect.js +36 -0
  37. package/dist/routes/proxyPathPageRouteHandler.js +43 -0
  38. package/dist/run.js +95 -35
  39. package/dist/shadowDevServer/createShadowDevServerRoutes.js +63 -0
  40. package/dist/shadowDevServer/startShadowDevServer.js +31 -0
  41. package/dist/storybook/getFieldsArgTypes.js +54 -0
  42. package/dist/storybook/getFieldsArgTypes.test.js +91 -0
  43. package/dist/storybook/getNestedFieldObjectForArgs.js +22 -0
  44. package/dist/storybook/getNestedFieldObjectForArgs.test.js +40 -0
  45. package/dist/storybook/index.js +1 -1
  46. package/dist/storybook/main.js +13 -6
  47. package/dist/storybook/moduleStory.js +61 -0
  48. package/dist/storybook/preview.js +9 -0
  49. package/dist/storybook/types.js +1 -0
  50. package/package.json +3 -3
@@ -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,162 @@
1
+ import path from 'path';
2
+ import url from 'url';
3
+ import express from 'express';
4
+ import http from 'http';
5
+ import bodyParser from 'body-parser';
6
+ import { spawn } from 'child_process';
7
+ import { normalizePath } from 'vite';
8
+ import createDevServerRoutes from './routes/createDevServerRoutes.js';
9
+ import startShadowDevServer from './shadowDevServer/startShadowDevServer.js';
10
+ import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
11
+ import createViteDevServer from './createViteDevServer.js';
12
+ import { createHttpsRedirectingServer } from './lib/httpsRedirectingServer.js';
13
+ import { debug } from './lib/debug.js';
14
+ import { getEnv, getAccountId, loadConfig, validateConfig, } from '@hubspot/cli-lib/lib/config.js';
15
+ import { fetchWebsiteDomainNames } from './proxyPage/fetchDomains.js';
16
+ import { logMissingScopeWarning, MissingScopeError } from './lib/errors.js';
17
+ const BASE_PATH = '/';
18
+ const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
19
+ const SHADOW_PORT = 1442;
20
+ const STORYBOOK_PORT = process.env.STORYBOOK_PORT
21
+ ? parseInt(process.env.STORYBOOK_PORT, 10)
22
+ : 3123;
23
+ async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption) {
24
+ console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
25
+ let authedPortalId = null;
26
+ let authedEnv = null;
27
+ if (hubspotCliConfigPathOption && hubspotCliAccountNameOption) {
28
+ console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration at: ${hubspotCliConfigPathOption}`);
29
+ }
30
+ else if (hubspotCliConfigPathOption) {
31
+ console.log(`Loading HS auth configuration at: ${hubspotCliConfigPathOption}`);
32
+ }
33
+ else if (hubspotCliAccountNameOption) {
34
+ console.log(`Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration.`);
35
+ }
36
+ // If a custom hubspot.config.yaml config path was set, make sure to force load that before
37
+ // any hs config values are read
38
+ loadConfig(hubspotCliConfigPathOption || null, { useEnv: false });
39
+ if (validateConfig()) {
40
+ authedPortalId = getAccountId(hubspotCliAccountNameOption);
41
+ authedEnv = getEnv(hubspotCliAccountNameOption);
42
+ if (!authedPortalId && hubspotCliAccountNameOption) {
43
+ console.error(`Couldn't find ${hubspotCliAccountNameOption} in your hubspot.config.yaml`);
44
+ process.exit(1);
45
+ }
46
+ }
47
+ else {
48
+ console.warn(`Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).
49
+ If needed you can refer to another config file with --config.
50
+
51
+ Local proxy functionality will not work without setting up authentication.`);
52
+ }
53
+ let domainsToProxy = [];
54
+ if (sslEnabledOption && authedPortalId) {
55
+ try {
56
+ const portalDomains = await fetchWebsiteDomainNames(authedPortalId);
57
+ domainsToProxy = (process.env.DOMAINS_TO_PROXY || '')
58
+ .split(',')
59
+ .filter(d => !!d);
60
+ domainsToProxy = [...domainsToProxy, ...portalDomains];
61
+ }
62
+ catch (e) {
63
+ if (e instanceof MissingScopeError) {
64
+ logMissingScopeWarning(e);
65
+ }
66
+ else {
67
+ console.warn(`Failed to fetch domains for ${authedPortalId}, HTTPS proxying won't work with them.`);
68
+ }
69
+ }
70
+ }
71
+ const authedHublet = 'na1';
72
+ const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
73
+ const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, '').split('/').slice(-2);
74
+ const viteServer = await createViteDevServer(absoluteWebRoot, PORT, sslEnabledOption, domainsToProxy);
75
+ // Get https key and cert from the vite config set by vite-plugin-mkcert (if it worked )
76
+ const viteHTTPSConfig = viteServer.config.server.https;
77
+ const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
78
+ const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
79
+ const httpServers = [];
80
+ const expressServer = express();
81
+ expressServer.locals.devServerHost = 'hslocal.net';
82
+ expressServer.locals.devServerPort = PORT;
83
+ expressServer.locals.webRoot = webRoot;
84
+ expressServer.locals.viteServer = viteServer;
85
+ expressServer.locals.authedPortalId = authedPortalId;
86
+ expressServer.locals.authedEnv = authedEnv;
87
+ expressServer.locals.authedHublet = authedHublet;
88
+ expressServer.locals.storybookEnabled = storybook;
89
+ expressServer.locals.storybookPort = STORYBOOK_PORT;
90
+ expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
91
+ expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
92
+ expressServer.use(bodyParser.json());
93
+ expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer, storybook ? STORYBOOK_PORT : null));
94
+ if (sslEnabledOption) {
95
+ if (httpsKey && httpsCert) {
96
+ const { server, innerHTTPServer, innerHTTPSServer } = createHttpsRedirectingServer({ key: httpsKey, cert: httpsCert }, expressServer);
97
+ server.listen(PORT);
98
+ httpServers.push(server);
99
+ // Not sure if we need to worry about closing all of these, but🤷
100
+ httpServers.push(innerHTTPServer);
101
+ httpServers.push(innerHTTPSServer);
102
+ }
103
+ else {
104
+ console.error('Failed to start a HTTPS server, try --no-ssl');
105
+ process.exit(1);
106
+ }
107
+ }
108
+ else {
109
+ const httpServer = http.createServer(expressServer);
110
+ httpServer.listen(PORT);
111
+ httpServers.push(httpServer);
112
+ }
113
+ startShadowDevServer(PORT, SHADOW_PORT);
114
+ let extraServerInfo = '';
115
+ const protocol = sslEnabledOption ? 'https' : 'http';
116
+ if (authedPortalId) {
117
+ extraServerInfo += `, hubid=${authedPortalId}`;
118
+ }
119
+ if (authedEnv && authedEnv !== 'prod') {
120
+ extraServerInfo += `, env=${authedEnv}`;
121
+ }
122
+ console.log(`
123
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
124
+ `);
125
+ if (storybook) {
126
+ const packageRoot = path.dirname(url.fileURLToPath(import.meta.url));
127
+ const configPath = path.resolve(packageRoot, './storybook');
128
+ const storybookProcess = spawn('npx', [
129
+ 'sb',
130
+ 'dev',
131
+ '-p',
132
+ STORYBOOK_PORT.toString(),
133
+ '-c',
134
+ configPath,
135
+ '--quiet',
136
+ '--no-open',
137
+ ], {
138
+ cwd: process.cwd(),
139
+ env: {
140
+ ...process.env,
141
+ WEB_ROOT: path.join(webRoot, 'components'),
142
+ },
143
+ });
144
+ console.log(`Starting storybook server on port ${STORYBOOK_PORT}`);
145
+ if (debug.enabled) {
146
+ storybookProcess.stdout.pipe(process.stdout);
147
+ }
148
+ storybookProcess.stderr.pipe(process.stderr);
149
+ }
150
+ // Return hook to shut down server gracefully
151
+ return {
152
+ close: () => {
153
+ const serverClosePromises = httpServers.map(server => new Promise(resolve => {
154
+ server.close(() => {
155
+ resolve(null);
156
+ });
157
+ }));
158
+ return Promise.allSettled([...serverClosePromises, viteServer.close()]);
159
+ },
160
+ };
161
+ }
162
+ export default createDevServer;
@@ -0,0 +1,51 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
3
+ import { createServer as createViteServer } from 'vite';
4
+ import { default as react } from '@vitejs/plugin-react';
5
+ import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
6
+ import mkcert from 'vite-plugin-mkcert';
7
+ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = []) {
8
+ const additionalMkcertHosts = domainsToProxy
9
+ .map(proxyDomain => [
10
+ `${proxyDomain}.localhost`,
11
+ `${proxyDomain}.hslocal.net`,
12
+ ])
13
+ .flat();
14
+ additionalMkcertHosts.push('*.hslocal.net', 'hslocal.net');
15
+ const origin = sslEnabled
16
+ ? `https://hslocal.net:${port}`
17
+ : `http://hslocal.net:${port}`;
18
+ const viteConfig = {
19
+ appType: 'custom',
20
+ server: {
21
+ middlewareMode: true,
22
+ host: 'hslocal.net',
23
+ origin,
24
+ https: sslEnabled,
25
+ hmr: {
26
+ protocol: sslEnabled ? 'wss' : undefined,
27
+ },
28
+ },
29
+ ssr: {
30
+ // TODO: might need more entries here to get things to resolve through
31
+ // resolveWebRootDepsPlugin
32
+ noExternal: '@hubspot/cms-components',
33
+ },
34
+ resolve: {
35
+ dedupe: ['react', 'react-dom', '@hubspot/cms-components'],
36
+ },
37
+ optimizeDeps: {
38
+ include: ['react', 'react-dom', 'react-dom/client'],
39
+ },
40
+ plugins: [
41
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
42
+ react(),
43
+ resolveIslandPlugin(),
44
+ ],
45
+ css: {
46
+ postcss: webRoot,
47
+ },
48
+ };
49
+ return createViteServer(viteConfig);
50
+ }
51
+ export default createViteDevServer;
Binary file
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { createRequire } from "module";
8
8
  import * as jsxRuntime from "react/jsx-runtime";
9
9
  import stream from "stream";
10
10
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
11
- import { createServerRenderContext, ServerRenderContext } from "@hubspot/cms-components";
11
+ import { createServerRenderContextV2, ServerRenderContext } from "@hubspot/cms-components";
12
12
  import { createHash } from "crypto";
13
13
  import { existsSync, readdirSync, lstatSync } from "fs";
14
14
  import { join } from "path/posix";
@@ -56,7 +56,7 @@ function resolveIslandPlugin(gates) {
56
56
  }
57
57
  };
58
58
  }
59
- var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: any\n) {\n const { island, rootElement, postHydration, pageUrl, islands } =\n renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: `island-${renderableIsland.index}-`,\n };\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n >\n <Component islandId={island.id} {...island.props} />\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
59
+ var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: any\n) {\n const { island, rootElement, postHydration, pageUrl, islands, basePath } =\n renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: `island-${renderableIsland.index}-`,\n };\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n basePath={basePath}\n >\n <Component islandId={island.id} {...island.props} />\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
60
60
  var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
61
61
  function clientIslandEntryPlugin() {
62
62
  return {
@@ -4,7 +4,7 @@ import { createRequire } from "module";
4
4
  import * as jsxRuntime from "react/jsx-runtime";
5
5
  import stream from "stream";
6
6
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
7
- import { createServerRenderContext, ServerRenderContext } from "@hubspot/cms-components";
7
+ import { createServerRenderContextV2, ServerRenderContext } from "@hubspot/cms-components";
8
8
  import { createHash } from "crypto";
9
9
  import { existsSync, readdirSync, lstatSync } from "fs";
10
10
  import { join } from "path/posix";
@@ -221,7 +221,7 @@ function resolveIslandPlugin(gates) {
221
221
  }
222
222
  };
223
223
  }
224
- var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: any\n) {\n const { island, rootElement, postHydration, pageUrl, islands } =\n renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: `island-${renderableIsland.index}-`,\n };\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n >\n <Component islandId={island.id} {...island.props} />\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
224
+ var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: any\n) {\n const { island, rootElement, postHydration, pageUrl, islands, basePath } =\n renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: `island-${renderableIsland.index}-`,\n };\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n basePath={basePath}\n >\n <Component islandId={island.id} {...island.props} />\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
225
225
  var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
226
226
  function clientIslandEntryPlugin() {
227
227
  return {
@@ -314,18 +314,22 @@ ${consoleLines.join("\n")}
314
314
  ${groupEnd}</script>
315
315
  `;
316
316
  };
317
- async function renderComponentOnServer(Component, props, pageUrl, environmentConfig, renderOptions) {
317
+ async function renderComponentOnServer(Component, props, pageUrl, environmentConfig, entryPointBasePath, renderOptions) {
318
318
  const componentDebugName = Component.displayName || Component.name;
319
319
  return renderOnServer(
320
320
  /* @__PURE__ */ jsx2(Component, { ...props }),
321
321
  pageUrl,
322
322
  environmentConfig,
323
+ entryPointBasePath,
323
324
  componentDebugName,
324
325
  renderOptions
325
326
  );
326
327
  }
327
- async function renderOnServer(elements, pageUrl, environmentConfig, debugName, renderOptions) {
328
- const renderContext = createServerRenderContext(pageUrl, environmentConfig);
328
+ async function renderOnServer(elements, pageUrl, environmentConfig, entryPointBasePath, debugName, renderOptions) {
329
+ const renderContext = createServerRenderContextV2(pageUrl, {
330
+ environmentConfig,
331
+ entryPointBasePath
332
+ });
329
333
  let html = await renderStreamToPromise(
330
334
  /* @__PURE__ */ jsx2(ServerRenderContext.Provider, { value: renderContext, children: elements }),
331
335
  renderOptions
@@ -436,13 +440,16 @@ function findAllPartialsInRoot(webRoot) {
436
440
  );
437
441
  return { partialNames, partialSubpaths };
438
442
  }
439
- function getServerGlobalsToInject(environmentConfig, hsServerPageUrl) {
443
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath) {
440
444
  const globals = [
441
445
  `window.__hsEnvConfig = ${JSON.stringify(environmentConfig.toJSON())};`
442
446
  ];
443
447
  if (hsServerPageUrl) {
444
448
  globals.push(`window.__hsServerPageUrl = '${hsServerPageUrl}';`);
445
449
  }
450
+ if (hsBasePath) {
451
+ globals.push(`window.__hsBasePath = '${hsBasePath}';`);
452
+ }
446
453
  return `
447
454
  <script type="text/javascript">
448
455
  ${globals.join("\n ")}
@@ -0,0 +1,27 @@
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
+ const sslEnabledOption = args.includes('--ssl') && !args.includes('--no-ssl');
19
+ const storybook = args.findIndex(arg => arg === '--storybook') > 0;
20
+ return {
21
+ hubspotCliConfigPathOption,
22
+ hubspotCliAccountNameOption,
23
+ sslEnabledOption,
24
+ storybook,
25
+ webRoot,
26
+ };
27
+ }
@@ -0,0 +1,2 @@
1
+ import { default as debugFactory } from 'debug';
2
+ export const debug = debugFactory('cms-dev-server');
@@ -0,0 +1,22 @@
1
+ const MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.\nYou may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account\n`;
2
+ const OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
3
+ const NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
4
+ export class MissingScopeError extends Error {
5
+ constructor(error) {
6
+ let messageEnd = '';
7
+ if (error.error.message.match(OAUTH_ERROR_REGEX)) {
8
+ messageEnd = error.error.message;
9
+ }
10
+ super(`${MISSING_SCOPE_ERROR_PREFIX}\n${messageEnd}`);
11
+ // Set the prototype explicitly.
12
+ Object.setPrototypeOf(this, MissingScopeError.prototype);
13
+ }
14
+ }
15
+ export function logMissingScopeWarning(error) {
16
+ console.warn(error.message);
17
+ }
18
+ export function isMissingScopeError(error) {
19
+ return (error.statusCode === 403 &&
20
+ (error.error.message.match(OAUTH_ERROR_REGEX) ||
21
+ error.error.message.startsWith(NOT_PUBLIC_USE_ERROR)));
22
+ }
@@ -0,0 +1,3 @@
1
+ export default function fullOriginalUrlFromRequest(request) {
2
+ return `${request.protocol}://${request.get('host')}${request.originalUrl}`;
3
+ }
@@ -0,0 +1,48 @@
1
+ import net from 'net';
2
+ import http from 'http';
3
+ import https from 'https';
4
+ function requireHTTPS(message, response) {
5
+ const newLocation = `https://${message.headers.host}${message.url}`;
6
+ response
7
+ .writeHead(302, {
8
+ Location: newLocation,
9
+ })
10
+ .end();
11
+ }
12
+ // Running http and https servers on the same port pulled from https://stackoverflow.com/a/42019773
13
+ export function createHttpsRedirectingServer(opts, handler) {
14
+ const innerHTTPServer = http.createServer(requireHTTPS);
15
+ const innerHTTPSServer = https.createServer(opts, handler);
16
+ const server = net.createServer(socket => {
17
+ socket.once('data', buffer => {
18
+ // Pause the socket
19
+ socket.pause();
20
+ // Determine if this is an HTTP(s) request
21
+ const byte = buffer[0];
22
+ let protocol;
23
+ if (byte === 22) {
24
+ protocol = 'https';
25
+ }
26
+ else if (32 < byte && byte < 127) {
27
+ protocol = 'http';
28
+ }
29
+ else {
30
+ throw new Error('Unknown issue with incoming data, unknown if http or https');
31
+ }
32
+ const proxy = protocol === 'http' ? innerHTTPServer : innerHTTPSServer;
33
+ if (proxy) {
34
+ // Push the buffer back onto the front of the data stream
35
+ socket.unshift(buffer);
36
+ // Emit the socket to the HTTP(s) server
37
+ proxy.emit('connection', socket);
38
+ }
39
+ // As of NodeJS 10.x the socket must be
40
+ // resumed asynchronously or the socket
41
+ // connection hangs, potentially crashing
42
+ // the process. Prior to NodeJS 10.x
43
+ // the socket may be resumed synchronously.
44
+ process.nextTick(() => socket.resume());
45
+ });
46
+ });
47
+ return { server, innerHTTPServer, innerHTTPSServer };
48
+ }
@@ -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,70 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable consistent-return */
3
+ import fs from 'fs';
4
+ import { resolve } from 'path';
5
+ const localJsRenderStartString = '<!-- proxy local render of "';
6
+ // const localJsRenderStartRegex = /<!-- proxy local render of "([^"]+)"/;
7
+ const localJsRenderEndString = 'end proxy local render -->';
8
+ export const findLocalRenderPlaceholders = (body) => {
9
+ let offsetSoFar = 0;
10
+ const result = [];
11
+ while (offsetSoFar < body.length && offsetSoFar !== -1) {
12
+ // Get start of local render block
13
+ const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);
14
+ offsetSoFar = startOffset;
15
+ if (startOffset >= 0) {
16
+ const nextNewlineOffset = body.indexOf('\n', startOffset + localJsRenderStartString.length);
17
+ const pathEndOffset = body.indexOf('"', startOffset + localJsRenderStartString.length);
18
+ const nearestNewlineOrQuoteAfterBlockOpen = Math.min(nextNewlineOffset, pathEndOffset);
19
+ // Keep on moving our "where we've scanned so far" pointer
20
+ offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
21
+ if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
22
+ // Pull the path out of double quotes after the block opening
23
+ const path = body.substring(startOffset + localJsRenderStartString.length, pathEndOffset);
24
+ offsetSoFar = pathEndOffset + 1;
25
+ // console.log(`${startOffset}: path = ${path}`);
26
+ // If we're in a valid bloc so far that exists and has a path...
27
+ if (startOffset >= 0 && path) {
28
+ const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);
29
+ const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
30
+ offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
31
+ // Make sure that there is an ending to the block and there is not another
32
+ // HTML end comment string before it
33
+ if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {
34
+ // Then pull out the JSON in the middle and try to parse it
35
+ const jsonString = body
36
+ .substring(pathEndOffset + 1, endOffset)
37
+ .trim();
38
+ // console.log(`${endOffset}: jsonString = ${jsonString}`);
39
+ try {
40
+ const json = JSON.parse(jsonString);
41
+ result.push({
42
+ startOffset,
43
+ endOffset: endOffset + localJsRenderEndString.length,
44
+ path,
45
+ json,
46
+ });
47
+ offsetSoFar = endOffset + localJsRenderEndString.length;
48
+ }
49
+ catch (e) {
50
+ console.error(`Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`);
51
+ offsetSoFar = endOffset;
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+ }
58
+ return result;
59
+ };
60
+ const getHSProjectConfig = hsProjectConfigPath => {
61
+ try {
62
+ return JSON.parse(fs.readFileSync(hsProjectConfigPath, 'utf8'));
63
+ }
64
+ catch (e) {
65
+ console.warn(`Missing hsproject.json file (${resolve(hsProjectConfigPath)}): `, e.message);
66
+ }
67
+ };
68
+ export const getProjectNameFromHSConfig = hsProjectConfigPath => {
69
+ return getHSProjectConfig(hsProjectConfigPath).name;
70
+ };
@@ -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
+ });