@hubspot/cms-dev-server 0.6.0 → 0.6.1

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 (53) hide show
  1. package/dist/index.js +0 -10
  2. package/dist/internalSsr.js +4 -7
  3. package/dist/run.js +43 -9
  4. package/dist/storybook/index.js +61 -46
  5. package/dist/{storybook → storybook-main}/main.js +24 -9
  6. package/dist/storybook-main/preview.js +20 -0
  7. package/package.json +11 -10
  8. package/types/storybook/getFieldsArgTypes.d.ts +1 -7
  9. package/types/storybook/moduleStory.d.ts +5 -2
  10. package/types/storybook/types.d.ts +11 -0
  11. package/dist/components/ModulesList.js +0 -14
  12. package/dist/components/PartialsList.js +0 -13
  13. package/dist/createDevServer.js +0 -162
  14. package/dist/createViteDevServer.js +0 -51
  15. package/dist/lib/cli.js +0 -27
  16. package/dist/lib/debug.js +0 -2
  17. package/dist/lib/errors.js +0 -22
  18. package/dist/lib/fullOriginalUrlFromRequest.js +0 -3
  19. package/dist/lib/httpsRedirectingServer.js +0 -48
  20. package/dist/lib/moduleGraph.js +0 -11
  21. package/dist/lib/proxyHelpers.js +0 -70
  22. package/dist/lib/proxyHelpers.test.js +0 -136
  23. package/dist/lib/renderComponentWithCSS.js +0 -26
  24. package/dist/lib/renderHelpers.js +0 -45
  25. package/dist/lib/renderModule.js +0 -56
  26. package/dist/lib/renderPartial.js +0 -15
  27. package/dist/lib/templates.js +0 -55
  28. package/dist/proxyPage/constants.js +0 -1
  29. package/dist/proxyPage/fetchContentMetadata.js +0 -59
  30. package/dist/proxyPage/fetchDomains.js +0 -29
  31. package/dist/proxyPage/fetchPreviewInfo.js +0 -37
  32. package/dist/proxyPage/proxyPage.js +0 -174
  33. package/dist/proxyPage/renderLocalError.js +0 -27
  34. package/dist/proxyPage/utils.js +0 -38
  35. package/dist/routes/createDevServerRoutes.js +0 -43
  36. package/dist/routes/homeRouteHandler.js +0 -12
  37. package/dist/routes/linksToAllModulesRouteHandler.js +0 -10
  38. package/dist/routes/linksToAllPartialsRouteHandler.js +0 -10
  39. package/dist/routes/module.js +0 -41
  40. package/dist/routes/partial.js +0 -30
  41. package/dist/routes/proxyPageResourceRedirect.js +0 -22
  42. package/dist/routes/proxyPageRouteHandler.js +0 -40
  43. package/dist/routes/proxyPathPageResourceRedirect.js +0 -36
  44. package/dist/routes/proxyPathPageRouteHandler.js +0 -43
  45. package/dist/shadowDevServer/createShadowDevServerRoutes.js +0 -63
  46. package/dist/shadowDevServer/startShadowDevServer.js +0 -31
  47. package/dist/storybook/getFieldsArgTypes.js +0 -54
  48. package/dist/storybook/getFieldsArgTypes.test.js +0 -91
  49. package/dist/storybook/getNestedFieldObjectForArgs.js +0 -22
  50. package/dist/storybook/getNestedFieldObjectForArgs.test.js +0 -40
  51. package/dist/storybook/moduleStory.js +0 -61
  52. package/dist/storybook/preview.js +0 -9
  53. package/dist/storybook/types.js +0 -1
@@ -1,162 +0,0 @@
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;
@@ -1,51 +0,0 @@
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;
package/dist/lib/cli.js DELETED
@@ -1,27 +0,0 @@
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
- }
package/dist/lib/debug.js DELETED
@@ -1,2 +0,0 @@
1
- import { default as debugFactory } from 'debug';
2
- export const debug = debugFactory('cms-dev-server');
@@ -1,22 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
1
- export default function fullOriginalUrlFromRequest(request) {
2
- return `${request.protocol}://${request.get('host')}${request.originalUrl}`;
3
- }
@@ -1,48 +0,0 @@
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
- }
@@ -1,11 +0,0 @@
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
- };
@@ -1,70 +0,0 @@
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
- };
@@ -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, environmentConfig) {
4
- // Need to make sure rendering happens in Vite SSR context
5
- const { renderComponentOnServer, collectCssInDev } = await viteServer.ssrLoadModule('@hubspot/cms-js-internal');
6
- let componentPathWithExtension;
7
- let componentPathNoExtension;
8
- // Support paths with or without an extension (do we need/want both?)
9
- if (hasComponentExtension(componentPath)) {
10
- componentPathWithExtension = componentPath;
11
- componentPathNoExtension = removeComponentExtension(componentPath);
12
- }
13
- else {
14
- componentPathNoExtension = componentPath;
15
- }
16
- const { html, renderContext } = await renderComponentOnServer(Component, props, pageUrl, environmentConfig);
17
- if (!componentPathWithExtension) {
18
- componentPathWithExtension = findFullPathInModuleGraph(componentPathNoExtension, viteServer.moduleGraph);
19
- if (!componentPathWithExtension) {
20
- throw new Error(`Couldn't find full path to component: ${componentPathNoExtension}`);
21
- }
22
- }
23
- const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);
24
- return { html, cssNeeded, renderContext };
25
- }
26
- export default renderComponentWithCSS;
@@ -1,45 +0,0 @@
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`, `\x1b[0m`];
8
- }
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`, `\x1b[0m`];
12
- }
13
- else {
14
- // Show size in green
15
- return ['\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`, `\x1b[0m`];
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();
39
- };
40
- export const logPartialInfo = (partialPath, props) => {
41
- console.log('Rendering partial', partialPath);
42
- console.group();
43
- console.log('Props size: ', ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 }));
44
- console.groupEnd();
45
- };
@@ -1,56 +0,0 @@
1
- import { join as joinPosix } from 'path/posix';
2
- import renderComponentWithCSS from './renderComponentWithCSS.js';
3
- import { traverseFieldsJSON } from '@hubspot/cms-components/fields';
4
- import { hasComponentExtension, setIn, renderFieldsToJson, } from '@hubspot/cms-js-internal';
5
- const lookForModuleInFolder = async (modulePath, viteServer) => {
6
- let componentModule;
7
- const insideFolderPath = joinPosix(modulePath, 'index');
8
- try {
9
- componentModule = await viteServer.ssrLoadModule(insideFolderPath);
10
- }
11
- catch (e) {
12
- if (!e.message.includes('Failed to load url')) {
13
- throw e;
14
- }
15
- }
16
- return [componentModule, insideFolderPath];
17
- };
18
- async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}, pageUrl, environmentConfig) {
19
- console.log('Rendering module', requestedModulePath);
20
- let componentModule;
21
- let foundPath;
22
- if (!hasComponentExtension(requestedModulePath)) {
23
- [componentModule, foundPath] = await lookForModuleInFolder(requestedModulePath, viteServer);
24
- }
25
- if (!componentModule) {
26
- // Look for non-folder module
27
- componentModule = await viteServer.ssrLoadModule(requestedModulePath);
28
- foundPath = componentModule ? requestedModulePath : undefined;
29
- }
30
- if (!componentModule) {
31
- throw new Error(`Couldn't find module: ${requestedModulePath}`);
32
- }
33
- const Component = componentModule.Component;
34
- const fields = componentModule.fields;
35
- const meta = componentModule.meta;
36
- if (!Component) {
37
- throw new Error(`Module does not have a named Component export: ${foundPath}`);
38
- }
39
- else if (!fields) {
40
- throw new Error(`Module does not have a named fields export: ${foundPath}`);
41
- }
42
- else if (!meta) {
43
- throw new Error(`Module does not have a named meta export: ${foundPath}`);
44
- }
45
- const fieldsJSON = renderFieldsToJson(fields);
46
- const props = getPropsForModule(fieldsJSON, fieldOverrides);
47
- return renderComponentWithCSS(viteServer, foundPath, Component, props, pageUrl, environmentConfig);
48
- }
49
- function getPropsForModule(fieldsJSON, fieldOverrides = {}) {
50
- const props = {};
51
- traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
52
- setIn(props, fieldPathArray, value);
53
- });
54
- return props;
55
- }
56
- export default renderModule;