@hubspot/cms-dev-server 0.3.3 → 0.4.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.
@@ -1,19 +1,26 @@
1
1
  import path from 'path';
2
2
  import url from 'url';
3
3
  import express from 'express';
4
+ import http from 'http';
5
+ import bodyParser from 'body-parser';
4
6
  import { spawn } from 'child_process';
5
7
  import { normalizePath } from 'vite';
6
8
  import createDevServerRoutes from './routes/createDevServerRoutes.js';
9
+ import startShadowDevServer from './shadowDevServer/startShadowDevServer.js';
7
10
  import { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';
8
11
  import createViteDevServer from './createViteDevServer.js';
12
+ import { createHttpsRedirectingServer } from './lib/httpsRedirectingServer.js';
9
13
  import { debug } from './lib/debug.js';
10
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';
11
17
  const BASE_PATH = '/';
12
18
  const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
19
+ const SHADOW_PORT = 1442;
13
20
  const STORYBOOK_PORT = process.env.STORYBOOK_PORT
14
21
  ? parseInt(process.env.STORYBOOK_PORT, 10)
15
22
  : 3123;
16
- async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption) {
23
+ async function createDevServer(webRoot, storybook, hubspotCliConfigPathOption, hubspotCliAccountNameOption, sslEnabledOption) {
17
24
  console.log('Warning: this is a prerelease and requires specific HubSpot account configuration to work');
18
25
  let authedPortalId = null;
19
26
  let authedEnv = null;
@@ -43,12 +50,35 @@ If needed you can refer to another config file with --config.
43
50
 
44
51
  Local proxy functionality will not work without setting up authentication.`);
45
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
+ }
46
71
  const authedHublet = 'na1';
47
72
  const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));
48
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 = [];
49
80
  const expressServer = express();
50
- const viteServer = await createViteDevServer(absoluteWebRoot);
51
- expressServer.locals.devServerHost = 'localhost';
81
+ expressServer.locals.devServerHost = 'hslocal.net';
52
82
  expressServer.locals.devServerPort = PORT;
53
83
  expressServer.locals.webRoot = webRoot;
54
84
  expressServer.locals.viteServer = viteServer;
@@ -59,9 +89,30 @@ Local proxy functionality will not work without setting up authentication.`);
59
89
  expressServer.locals.storybookPort = STORYBOOK_PORT;
60
90
  expressServer.locals.projectName = getProjectNameFromHSConfig(path.join(webRoot, '../hsproject.json'));
61
91
  expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
92
+ expressServer.use(bodyParser.json());
62
93
  expressServer.use(BASE_PATH, await createDevServerRoutes(viteServer, storybook ? STORYBOOK_PORT : null));
63
- expressServer.listen(PORT);
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);
64
114
  let extraServerInfo = '';
115
+ const protocol = sslEnabledOption ? 'https' : 'http';
65
116
  if (authedPortalId) {
66
117
  extraServerInfo += `, hubid=${authedPortalId}`;
67
118
  }
@@ -69,7 +120,7 @@ Local proxy functionality will not work without setting up authentication.`);
69
120
  extraServerInfo += `, env=${authedEnv}`;
70
121
  }
71
122
  console.log(`
72
- HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at http://localhost:${PORT}${extraServerInfo})
123
+ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
73
124
  `);
74
125
  if (storybook) {
75
126
  const packageRoot = path.dirname(url.fileURLToPath(import.meta.url));
@@ -96,5 +147,16 @@ HubSpot CMS dev server hosting: ${expressServer.locals.projectName}/${expressSer
96
147
  }
97
148
  storybookProcess.stderr.pipe(process.stderr);
98
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
+ };
99
161
  }
100
162
  export default createDevServer;
@@ -1,13 +1,30 @@
1
+ /* hs-eslint ignored failing-rules */
2
+ /* eslint-disable require-await */
1
3
  import { createServer as createViteServer } from 'vite';
2
4
  import { default as react } from '@vitejs/plugin-react';
3
5
  import { resolveIslandPlugin } from '@hubspot/cms-js-internal';
4
- const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
5
- async function createViteDevServer(webRoot) {
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}`;
6
18
  const viteConfig = {
7
19
  appType: 'custom',
8
20
  server: {
9
21
  middlewareMode: true,
10
- origin: `http://localhost:${PORT}`,
22
+ host: 'hslocal.net',
23
+ origin,
24
+ https: sslEnabled,
25
+ hmr: {
26
+ protocol: sslEnabled ? 'wss' : undefined,
27
+ },
11
28
  },
12
29
  ssr: {
13
30
  // TODO: might need more entries here to get things to resolve through
@@ -20,10 +37,14 @@ async function createViteDevServer(webRoot) {
20
37
  optimizeDeps: {
21
38
  include: ['react', 'react-dom', 'react-dom/client'],
22
39
  },
40
+ plugins: [
41
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
42
+ react(),
43
+ resolveIslandPlugin(),
44
+ ],
23
45
  css: {
24
46
  postcss: webRoot,
25
47
  },
26
- plugins: [react(), resolveIslandPlugin()],
27
48
  };
28
49
  return createViteServer(viteConfig);
29
50
  }
Binary file
package/dist/index.js CHANGED
@@ -1 +1,84 @@
1
- export { default as createViteDevServer } from './createViteDevServer.js';
1
+ // src/createViteDevServer.ts
2
+ import { createServer as createViteServer } from "vite";
3
+ import { default as react } from "@vitejs/plugin-react";
4
+
5
+ // ../cms-js-internal/dist/index.js
6
+ import path from "path";
7
+ import stream from "stream";
8
+ import { renderToPipeableStream } from "react-dom/server";
9
+ import {
10
+ ServerRenderContext,
11
+ createServerRenderContext
12
+ } from "@hubspot/cms-components";
13
+ import { jsx } from "react/jsx-runtime";
14
+ import path2 from "path";
15
+ import { existsSync, readdirSync, lstatSync } from "fs";
16
+ import { join as joinPosix } from "path/posix";
17
+ import { basename } from "path";
18
+ import { cloneElement } from "react";
19
+ import { renderToStaticMarkup } from "react-dom/server";
20
+ var viteRoot;
21
+ var viteCommand;
22
+ function resolveIslandPlugin() {
23
+ return {
24
+ enforce: "pre",
25
+ name: "resolve-islands",
26
+ configResolved(config) {
27
+ viteRoot = config.root;
28
+ viteCommand = config.command;
29
+ },
30
+ load(id) {
31
+ if (id.endsWith("?island")) {
32
+ const [idWithNoParam] = id.split("?");
33
+ const componentExtension = path.extname(idWithNoParam);
34
+ const componentFilenameWithNoExtension = path.basename(
35
+ idWithNoParam,
36
+ componentExtension
37
+ );
38
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
39
+ return `
40
+ const moduleId = '${viteCommand === "serve" ? idWithNoParam : modulePath}';
41
+
42
+ const lazyComponent = () => import('${idWithNoParam}');
43
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
44
+ lazyComponent.moduleId = moduleId;
45
+
46
+ export default lazyComponent;
47
+ `;
48
+ }
49
+ return null;
50
+ }
51
+ };
52
+ }
53
+
54
+ // src/createViteDevServer.ts
55
+ var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
56
+ async function createViteDevServer(webRoot) {
57
+ const viteConfig = {
58
+ appType: "custom",
59
+ server: {
60
+ middlewareMode: true,
61
+ origin: `http://localhost:${PORT}`
62
+ },
63
+ ssr: {
64
+ // TODO: might need more entries here to get things to resolve through
65
+ // resolveWebRootDepsPlugin
66
+ noExternal: "@hubspot/cms-components"
67
+ },
68
+ resolve: {
69
+ dedupe: ["react", "react-dom", "@hubspot/cms-components"]
70
+ },
71
+ optimizeDeps: {
72
+ include: ["react", "react-dom", "react-dom/client"]
73
+ },
74
+ css: {
75
+ postcss: webRoot
76
+ },
77
+ plugins: [react(), resolveIslandPlugin()]
78
+ };
79
+ return createViteServer(viteConfig);
80
+ }
81
+ var createViteDevServer_default = createViteDevServer;
82
+ export {
83
+ createViteDevServer_default as createViteDevServer
84
+ };
@@ -0,0 +1,390 @@
1
+ // ../cms-js-internal/dist/index.js
2
+ import path from "path";
3
+ import stream from "stream";
4
+ import { renderToPipeableStream } from "react-dom/server";
5
+ import {
6
+ ServerRenderContext,
7
+ createServerRenderContext
8
+ } from "@hubspot/cms-components";
9
+ import { jsx } from "react/jsx-runtime";
10
+ import path2 from "path";
11
+ import { existsSync, readdirSync, lstatSync } from "fs";
12
+ import { join as joinPosix } from "path/posix";
13
+ import { basename } from "path";
14
+ import { cloneElement } from "react";
15
+ import { renderToStaticMarkup } from "react-dom/server";
16
+ var collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
17
+ const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
18
+ modulePathToStartWith
19
+ );
20
+ if (!appModulesForPath || appModulesForPath.size === 0) {
21
+ throw new Error(`No modules at: ${modulePathToStartWith}`);
22
+ } else if (appModulesForPath.size > 1) {
23
+ throw new Error(`More than one module at: ${modulePathToStartWith}`);
24
+ }
25
+ const appModule = Array.from(appModulesForPath.values())[0];
26
+ const allServerSideModulesImported = /* @__PURE__ */ new Set();
27
+ const newCssModules = [];
28
+ const moduleQueue = Array.from(appModule.importedModules);
29
+ for (const importedModule of moduleQueue) {
30
+ if (allServerSideModulesImported.has(importedModule.id)) {
31
+ continue;
32
+ }
33
+ allServerSideModulesImported.add(importedModule.id);
34
+ const isCss = importedModule.file.endsWith(".css");
35
+ const moduleModulesToQueue = Array.from(importedModule.importedModules);
36
+ if (isCss && !cssModulesImported.has(importedModule)) {
37
+ cssModulesImported.add(importedModule);
38
+ newCssModules.push(importedModule);
39
+ }
40
+ moduleQueue.push(...moduleModulesToQueue);
41
+ }
42
+ return newCssModules;
43
+ };
44
+ function createPreloadLink(assetPath, basePath = "") {
45
+ if (assetPath && assetPath[0] !== "/") {
46
+ assetPath = `/${assetPath}`;
47
+ }
48
+ if (assetPath.endsWith(".js")) {
49
+ return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
50
+ } else if (assetPath.endsWith(".css")) {
51
+ return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
52
+ } else if (assetPath.endsWith(".woff")) {
53
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
54
+ } else if (assetPath.endsWith(".woff2")) {
55
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
56
+ } else if (assetPath.endsWith(".gif")) {
57
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
58
+ } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
59
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
60
+ } else if (assetPath.endsWith(".png")) {
61
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
62
+ } else {
63
+ throw new Error(`Unknown preload type for ${assetPath}`);
64
+ }
65
+ }
66
+ var collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
67
+ return `${collectCssModules(
68
+ modulePathToStartWith,
69
+ viteServer,
70
+ cssModulesImported
71
+ ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
72
+ `;
73
+ };
74
+ var writeIslandDataToJsGlobal = (tweakedIslandsArray, indent = 0) => {
75
+ const indentString = new Array(indent).fill(" ").join("");
76
+ return `window.__islands = ${JSON.stringify(
77
+ tweakedIslandsArray.map(
78
+ ({
79
+ id,
80
+ moduleName,
81
+ moduleId,
82
+ props,
83
+ hydrateOn,
84
+ clientOnly,
85
+ priority,
86
+ url
87
+ }) => {
88
+ return {
89
+ id,
90
+ moduleName,
91
+ moduleId,
92
+ props,
93
+ hydrateOn,
94
+ clientOnly,
95
+ priority,
96
+ url
97
+ };
98
+ }
99
+ ),
100
+ null,
101
+ 2
102
+ ).replace(/\n/gm, `
103
+ ${indentString}`)};`;
104
+ };
105
+ function getIslandUrls(roots, viteDevServer) {
106
+ return roots.map((island) => {
107
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
108
+ island.moduleId
109
+ );
110
+ if (!islandModule) {
111
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
112
+ }
113
+ const tweakedIsland = {
114
+ ...island,
115
+ url: islandModule.url
116
+ };
117
+ return tweakedIsland;
118
+ });
119
+ }
120
+ var createIslandsGlobalJsForClientInDev = (roots, viteDevServer, indent) => {
121
+ return writeIslandDataToJsGlobal(getIslandUrls(roots, viteDevServer), indent);
122
+ };
123
+ var viteRoot;
124
+ var viteCommand;
125
+ function resolveIslandPlugin() {
126
+ return {
127
+ enforce: "pre",
128
+ name: "resolve-islands",
129
+ configResolved(config) {
130
+ viteRoot = config.root;
131
+ viteCommand = config.command;
132
+ },
133
+ load(id) {
134
+ if (id.endsWith("?island")) {
135
+ const [idWithNoParam] = id.split("?");
136
+ const componentExtension = path.extname(idWithNoParam);
137
+ const componentFilenameWithNoExtension = path.basename(
138
+ idWithNoParam,
139
+ componentExtension
140
+ );
141
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
142
+ return `
143
+ const moduleId = '${viteCommand === "serve" ? idWithNoParam : modulePath}';
144
+
145
+ const lazyComponent = () => import('${idWithNoParam}');
146
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
147
+ lazyComponent.moduleId = moduleId;
148
+
149
+ export default lazyComponent;
150
+ `;
151
+ }
152
+ return null;
153
+ }
154
+ };
155
+ }
156
+ var promiseForNewWritableStream = () => {
157
+ const chunks = [];
158
+ const writableStream = new stream.Writable();
159
+ writableStream._write = (chunk, encoding, done) => {
160
+ chunks.push(Buffer.from(chunk));
161
+ done();
162
+ };
163
+ const streamDonePromise = new Promise((resolve, reject) => {
164
+ writableStream.on("error", (error) => {
165
+ reject(error);
166
+ });
167
+ writableStream._final = (done) => {
168
+ resolve(Buffer.concat(chunks).toString("utf8"));
169
+ done();
170
+ };
171
+ });
172
+ return { streamDonePromise, writableStream };
173
+ };
174
+ var renderStreamToPromise = async (reactElements) => {
175
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
176
+ const {
177
+ pipe
178
+ /* abort */
179
+ } = renderToPipeableStream(reactElements, {
180
+ onShellReady() {
181
+ },
182
+ onAllReady() {
183
+ pipe(writableStream);
184
+ }
185
+ // We will log the error sent to the writable, any need to do something in these callbacks?
186
+ // onShellError(error) {},
187
+ // onError(error) {},
188
+ });
189
+ return streamDonePromise;
190
+ };
191
+ var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
192
+ if (!messagesForBrowser) {
193
+ return "";
194
+ }
195
+ const consoleLines = [];
196
+ for (const message of messagesForBrowser) {
197
+ const funcString = message.level === "error" ? "console.error" : "console.warn";
198
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
199
+ consoleLines.push(` ${funcString}(${argString});`);
200
+ }
201
+ let groupStart = "";
202
+ let groupEnd = "";
203
+ if (groupLabel !== null) {
204
+ groupStart = `
205
+ console.group(${JSON.stringify(groupLabel)});`;
206
+ groupEnd = ` console.groupEnd()
207
+ `;
208
+ }
209
+ return `<script>${groupStart}
210
+ ${consoleLines.join("\n")}
211
+ ${groupEnd}</script>
212
+ `;
213
+ };
214
+ async function renderComponentOnServer(Component, props, pageUrl, environmentConfig) {
215
+ const componentDebugName = Component.displayName || Component.name;
216
+ return renderOnServer(
217
+ /* @__PURE__ */ jsx(Component, { ...props }),
218
+ pageUrl,
219
+ environmentConfig,
220
+ componentDebugName
221
+ );
222
+ }
223
+ async function renderOnServer(elements, pageUrl, environmentConfig, debugName) {
224
+ const renderContext = createServerRenderContext(pageUrl, environmentConfig);
225
+ let html = await renderStreamToPromise(
226
+ /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements })
227
+ );
228
+ if (renderContext.messagesForBrowser.length > 0) {
229
+ html = `${html}${scriptTagToLogServerMessages(
230
+ renderContext.messagesForBrowser,
231
+ `Server messages rendering: ${debugName}`
232
+ )}`;
233
+ }
234
+ return { html, renderContext };
235
+ }
236
+ var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
237
+ var ENTRY_POINTS_PATH = "components/partials/";
238
+ var MODULE_FOLDER_PATH = "components/modules/";
239
+ var VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
240
+ var VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
241
+ var getComponentExtension = (componentPath) => {
242
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
243
+ (ext) => componentPath.endsWith(ext)
244
+ );
245
+ if (filteredExtensions.length === 1) {
246
+ return filteredExtensions[0];
247
+ }
248
+ return void 0;
249
+ };
250
+ var hasComponentExtension = (componentPath) => {
251
+ return !!getComponentExtension(componentPath);
252
+ };
253
+ var isStorybookStory = (componentPath) => {
254
+ return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
255
+ };
256
+ var removeComponentExtension = (componentPath) => {
257
+ const ext = getComponentExtension(componentPath);
258
+ if (ext == null) {
259
+ return componentPath;
260
+ }
261
+ return componentPath.slice(0, -1 * ext.length);
262
+ };
263
+ var findAllComponentsIn = (webRoot, componentsFolder, includeSubdirIndexJS) => {
264
+ const fullComponentsFolderPath = joinPosix(webRoot, componentsFolder);
265
+ const componentsByName = {};
266
+ if (!existsSync(fullComponentsFolderPath)) {
267
+ return componentsByName;
268
+ }
269
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
270
+ const fullPath = joinPosix(fullComponentsFolderPath, fileOrFolderName);
271
+ const subdirPath = joinPosix(componentsFolder, fileOrFolderName);
272
+ const isDirectory = lstatSync(fullPath).isDirectory();
273
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
274
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
275
+ componentsByName[subdirPathNoExtension] = subdirPath;
276
+ } else if (isDirectory && includeSubdirIndexJS) {
277
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
278
+ const potentialIndexModule = joinPosix(
279
+ subdirPath,
280
+ `index${potentialExtension}`
281
+ );
282
+ const fullPotentialPath = joinPosix(
283
+ fullPath,
284
+ `index${potentialExtension}`
285
+ );
286
+ if (existsSync(fullPotentialPath)) {
287
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
288
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ });
294
+ return componentsByName;
295
+ };
296
+ var findAllComponentsIn_default = findAllComponentsIn;
297
+ function findAllModulesInRoot(webRoot) {
298
+ const allModuleComponents = findAllComponentsIn_default(
299
+ webRoot,
300
+ "./components/modules",
301
+ true
302
+ );
303
+ const moduleNames = Object.keys(allModuleComponents).map(
304
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
305
+ );
306
+ const moduleSubpaths = Object.keys(allModuleComponents);
307
+ return { moduleNames, moduleSubpaths };
308
+ }
309
+ function findAllPartialsInRoot(webRoot) {
310
+ const allPartialComponents = findAllComponentsIn_default(
311
+ webRoot,
312
+ "./components/partials",
313
+ false
314
+ );
315
+ const partialSubpaths = Object.keys(allPartialComponents);
316
+ const partialNames = partialSubpaths.map(
317
+ (partialSubpath) => basename(partialSubpath)
318
+ );
319
+ return { partialNames, partialSubpaths };
320
+ }
321
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl) {
322
+ const globals = [
323
+ `window.__hsEnvConfig = ${JSON.stringify(environmentConfig.toJSON())};`
324
+ ];
325
+ if (hsServerPageUrl) {
326
+ globals.push(`window.__hsServerPageUrl = '${hsServerPageUrl}';`);
327
+ }
328
+ return `
329
+ <script type="text/javascript">
330
+ ${globals.join("\n ")}
331
+ </script>
332
+ `;
333
+ }
334
+ function setIn(object, nestedKeysArray, value) {
335
+ let curr = object;
336
+ const finalKey = nestedKeysArray.pop();
337
+ for (let index = 0; index < nestedKeysArray.length; index++) {
338
+ const currentKey = nestedKeysArray[index];
339
+ const nextKey = nestedKeysArray[index + 1];
340
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
341
+ if (curr[currentKey] === void 0) {
342
+ curr[currentKey] = [];
343
+ }
344
+ }
345
+ if (curr[currentKey] === void 0) {
346
+ curr[currentKey] = {};
347
+ }
348
+ curr = curr[currentKey];
349
+ }
350
+ if (value !== void 0) {
351
+ curr[finalKey] = value;
352
+ }
353
+ }
354
+ function renderFieldsToJson(fields) {
355
+ let moduleJson;
356
+ const outputCallback = (callbackJson) => {
357
+ moduleJson = callbackJson;
358
+ };
359
+ renderToStaticMarkup(
360
+ cloneElement(fields, {
361
+ outputCallback
362
+ })
363
+ );
364
+ return moduleJson;
365
+ }
366
+ export {
367
+ COMPONENT_EXTENSIONS,
368
+ ENTRY_POINTS_PATH,
369
+ MODULE_FOLDER_PATH,
370
+ VIRTUAL_CONFIG_SETUP,
371
+ VIRTUAL_ISLAND_RUNTIME,
372
+ collectCssInDev,
373
+ collectCssModules,
374
+ createIslandsGlobalJsForClientInDev,
375
+ findAllComponentsIn_default as findAllComponentsIn,
376
+ findAllModulesInRoot,
377
+ findAllPartialsInRoot,
378
+ getComponentExtension,
379
+ getIslandUrls,
380
+ getServerGlobalsToInject,
381
+ hasComponentExtension,
382
+ isStorybookStory,
383
+ removeComponentExtension,
384
+ renderComponentOnServer,
385
+ renderFieldsToJson,
386
+ renderOnServer,
387
+ renderStreamToPromise,
388
+ resolveIslandPlugin,
389
+ setIn
390
+ };
package/dist/lib/cli.js CHANGED
@@ -15,11 +15,13 @@ export function getDevServerCommandLineOptions(argv) {
15
15
  hubspotCliAccountNameOption = args[accountOptionIndex + 1];
16
16
  args.splice(accountOptionIndex, 2);
17
17
  }
18
+ const sslEnabledOption = args.includes('--ssl') && !args.includes('--no-ssl');
18
19
  const storybook = args.findIndex(arg => arg === '--storybook') > 0;
19
20
  return {
20
- webRoot,
21
21
  hubspotCliConfigPathOption,
22
22
  hubspotCliAccountNameOption,
23
+ sslEnabledOption,
23
24
  storybook,
25
+ webRoot,
24
26
  };
25
27
  }
@@ -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
+ }