@hubspot/cms-dev-server 0.4.15 → 0.4.18

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.
@@ -159,6 +159,12 @@ var GATES = [
159
159
  "CMS:JSRenderer:LocalProxySchemaVersion1",
160
160
  "CMS:JSRenderer:GraphQLQueryBuild"
161
161
  ];
162
+ var ENABLED_FEATURES_GATE_MAP = {
163
+ "cms:jsr:sharedDeps": "CMS:JSRenderer:SharedDeps",
164
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
165
+ "cms:jsr:localProxySchemaVersion1": "CMS:JSRenderer:LocalProxySchemaVersion1",
166
+ "cms:jsr:graphqQLQueryBuild": "CMS:JSRenderer:GraphQLQueryBuild"
167
+ };
162
168
  function isUngatedFor(gates, gate) {
163
169
  return gates.includes(gate);
164
170
  }
@@ -478,6 +484,7 @@ function renderFieldsToJson(fields) {
478
484
  export {
479
485
  COMPONENT_EXTENSIONS,
480
486
  CSS_LANGS_RE,
487
+ ENABLED_FEATURES_GATE_MAP,
481
488
  ENTRY_POINTS_PATH,
482
489
  GATES,
483
490
  MODULE_FOLDER_PATH,
package/dist/run.js CHANGED
@@ -148,6 +148,12 @@ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevS
148
148
  )}${writeSharedStateToJsGlobal(islands, perServerRequestData, indent)}`;
149
149
  };
150
150
  var require2 = createRequire(import.meta.url);
151
+ var ENABLED_FEATURES_GATE_MAP = {
152
+ "cms:jsr:sharedDeps": "CMS:JSRenderer:SharedDeps",
153
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
154
+ "cms:jsr:localProxySchemaVersion1": "CMS:JSRenderer:LocalProxySchemaVersion1",
155
+ "cms:jsr:graphqQLQueryBuild": "CMS:JSRenderer:GraphQLQueryBuild"
156
+ };
151
157
  function isUngatedFor(gates, gate) {
152
158
  return gates.includes(gate);
153
159
  }
@@ -532,17 +538,15 @@ var logPartialInfo = (partialPath, props) => {
532
538
  console.groupEnd();
533
539
  };
534
540
 
535
- // src/lib/constants.ts
536
- var Gates = {
537
- GET_SERVER_SIDE_PROPS: "CMS:JSRenderer:GetServerSideProps"
538
- };
539
-
540
541
  // src/lib/renderPartial.ts
541
542
  async function renderPartial(viteServer, partialPath, props, pageUrl, environmentConfig, renderOptions) {
542
543
  logPartialInfo(partialPath, props);
543
544
  let serverSideProps;
544
545
  const componentModule = await viteServer.ssrLoadModule(partialPath);
545
- const ungatedForServerSideProps = environmentConfig.getGates().includes(Gates.GET_SERVER_SIDE_PROPS);
546
+ const ungatedForServerSideProps = isUngatedFor(
547
+ environmentConfig.getGates(),
548
+ "CMS:JSRenderer:GetServerSideProps"
549
+ );
546
550
  if (!componentModule) {
547
551
  throw new Error(`Couldn't find partial: ${partialPath}`);
548
552
  }
@@ -553,7 +557,7 @@ async function renderPartial(viteServer, partialPath, props, pageUrl, environmen
553
557
  if (ungatedForServerSideProps && componentModule.getServerSidePropsUnstable) {
554
558
  try {
555
559
  serverSideProps = await componentModule.getServerSidePropsUnstable(props);
556
- if (serverSideProps.constructor !== Object.constructor) {
560
+ if (serverSideProps.constructor !== {}.constructor) {
557
561
  throw new Error("getServerSidePropsUnstable must return an object");
558
562
  }
559
563
  } catch (e) {
@@ -842,7 +846,10 @@ var lookForModuleInFolder = async (modulePath, viteServer) => {
842
846
  };
843
847
  async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}, pageUrl, environmentConfig, renderOptions) {
844
848
  console.log("Rendering module", requestedModulePath);
845
- const ungatedForServerSideProps = environmentConfig.getGates().includes(Gates.GET_SERVER_SIDE_PROPS);
849
+ const ungatedForServerSideProps = isUngatedFor(
850
+ environmentConfig.getGates(),
851
+ "CMS:JSRenderer:GetServerSideProps"
852
+ );
846
853
  let serverSideProps;
847
854
  let componentModule;
848
855
  let foundPath;
@@ -876,6 +883,9 @@ async function renderModule(viteServer, requestedModulePath, fieldOverrides = {}
876
883
  if (ungatedForServerSideProps && componentModule.getServerSidePropsUnstable) {
877
884
  try {
878
885
  serverSideProps = await componentModule.getServerSidePropsUnstable(props);
886
+ if (serverSideProps.constructor !== {}.constructor) {
887
+ throw new Error("getServerSidePropsUnstable must return an object");
888
+ }
879
889
  } catch (e) {
880
890
  console.log("Error resolving server side props");
881
891
  console.error(e);
@@ -1954,10 +1964,42 @@ function createHttpsRedirectingServer(opts, handler) {
1954
1964
  return { server, innerHTTPServer, innerHTTPSServer };
1955
1965
  }
1956
1966
 
1967
+ // src/lib/getJSRenderingGates.ts
1968
+ import unAuth from "@hubspot/cli-lib/api/localDevAuth/unauthenticated.js";
1969
+
1970
+ // src/lib/gates.ts
1971
+ function getGatesFromEnv() {
1972
+ const gates = process.env.GATES ? process.env.GATES.split(",") : [];
1973
+ return gates;
1974
+ }
1975
+
1976
+ // src/lib/getJSRenderingGates.ts
1977
+ var mapEnabledFeaturesToGates = (enabledFeatures) => {
1978
+ return Object.keys(enabledFeatures).reduce((gates, enabledFeature) => {
1979
+ if (enabledFeatures[enabledFeature]) {
1980
+ gates.push(ENABLED_FEATURES_GATE_MAP[enabledFeature]);
1981
+ }
1982
+ return gates;
1983
+ }, []);
1984
+ };
1985
+ async function getJsRenderingGates(portalId, env, personalAccessKey) {
1986
+ const { enabledFeatures = {} } = await unAuth.fetchAccessToken(
1987
+ personalAccessKey,
1988
+ env,
1989
+ portalId
1990
+ );
1991
+ const envGates = getGatesFromEnv();
1992
+ const gates = mapEnabledFeaturesToGates(enabledFeatures);
1993
+ const mergedGates = [...envGates, ...gates];
1994
+ process.env.GATES = mergedGates.join(",");
1995
+ return mergedGates;
1996
+ }
1997
+
1957
1998
  // src/createDevServer.ts
1958
1999
  import {
1959
2000
  getEnv as getEnv2,
1960
2001
  getAccountId as getAccountId3,
2002
+ getAccountConfig,
1961
2003
  loadConfig,
1962
2004
  validateConfig
1963
2005
  } from "@hubspot/cli-lib/lib/config.js";
@@ -2014,12 +2056,6 @@ async function fetchWebsiteDomainNames(portalId) {
2014
2056
  return domainNames;
2015
2057
  }
2016
2058
 
2017
- // src/lib/gates.ts
2018
- function getGatesFromEnv() {
2019
- const gates = process.env.GATES ? process.env.GATES.split(",") : [];
2020
- return gates;
2021
- }
2022
-
2023
2059
  // src/createDevServer.ts
2024
2060
  var BASE_PATH = "/";
2025
2061
  var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
@@ -2031,6 +2067,7 @@ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2
2031
2067
  );
2032
2068
  let authedPortalId = null;
2033
2069
  let authedEnv = null;
2070
+ let jsRenderingGates = [];
2034
2071
  if (hubspotCliConfigPathOption2 && hubspotCliAccountNameOption2) {
2035
2072
  console.log(
2036
2073
  `Loading HS auth (account = ${hubspotCliAccountNameOption2}) configuration at: ${hubspotCliConfigPathOption2}`
@@ -2062,7 +2099,17 @@ If needed you can refer to another config file with --config.
2062
2099
  Local proxy functionality will not work without setting up authentication.`
2063
2100
  );
2064
2101
  }
2065
- const jsRenderingGates = getGatesFromEnv();
2102
+ try {
2103
+ const { personalAccessKey } = getAccountConfig(authedPortalId);
2104
+ jsRenderingGates = await getJsRenderingGates(
2105
+ authedPortalId,
2106
+ authedEnv,
2107
+ personalAccessKey
2108
+ );
2109
+ } catch (e) {
2110
+ console.error(e);
2111
+ console.warn("Unable to fetch gating information");
2112
+ }
2066
2113
  let domainsToProxy = [];
2067
2114
  if (sslEnabledOption2 && authedPortalId) {
2068
2115
  try {
@@ -0,0 +1,570 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../cms-js-internal/dist/index.js
12
+ var dist_exports = {};
13
+ __export(dist_exports, {
14
+ COMPONENT_EXTENSIONS: () => COMPONENT_EXTENSIONS,
15
+ CSS_LANGS_RE: () => CSS_LANGS_RE,
16
+ ENABLED_FEATURES_GATE_MAP: () => ENABLED_FEATURES_GATE_MAP,
17
+ ENTRY_POINTS_PATH: () => ENTRY_POINTS_PATH,
18
+ GATES: () => GATES,
19
+ MODULE_FOLDER_PATH: () => MODULE_FOLDER_PATH,
20
+ VIRTUAL_CONFIG_SETUP: () => VIRTUAL_CONFIG_SETUP,
21
+ VIRTUAL_ISLAND_RUNTIME: () => VIRTUAL_ISLAND_RUNTIME,
22
+ clientIslandEntryPlugin: () => clientIslandEntryPlugin,
23
+ collectCssInDev: () => collectCssInDev,
24
+ collectCssModules: () => collectCssModules,
25
+ createIslandsGlobalJsForClientInDev: () => createIslandsGlobalJsForClientInDev,
26
+ findAllComponentsIn: () => findAllComponentsIn,
27
+ findAllModulesInRoot: () => findAllModulesInRoot,
28
+ findAllPartialsInRoot: () => findAllPartialsInRoot,
29
+ getCombinedReactUrl: () => getCombinedReactUrl,
30
+ getComponentExtension: () => getComponentExtension,
31
+ getEntryPointHash: () => getEntryPointHash,
32
+ getEntryPointHashWithIndexSuffix: () => getEntryPointHashWithIndexSuffix,
33
+ getIslandRuntimeConfigUrl: () => getIslandRuntimeConfigUrl,
34
+ getIslandUrls: () => getIslandUrls,
35
+ getServerGlobalsToInject: () => getServerGlobalsToInject,
36
+ hasComponentExtension: () => hasComponentExtension,
37
+ isStorybookStory: () => isStorybookStory,
38
+ isUngatedFor: () => isUngatedFor,
39
+ removeComponentExtension: () => removeComponentExtension,
40
+ renderComponentOnServer: () => renderComponentOnServer,
41
+ renderFieldsToJson: () => renderFieldsToJson,
42
+ renderOnServer: () => renderOnServer,
43
+ renderStreamToPromise: () => renderStreamToPromise,
44
+ resolveIslandPlugin: () => resolveIslandPlugin,
45
+ serializeIslandDataToJSON: () => serializeIslandDataToJSON,
46
+ setIn: () => setIn,
47
+ ungatedAtBuildTimeFor: () => ungatedAtBuildTimeFor,
48
+ virtualClientRenderIslandModuleId: () => virtualClientRenderIslandModuleId
49
+ });
50
+ import path, { basename } from "path";
51
+ import { createRequire } from "module";
52
+ import * as jsxRuntime from "react/jsx-runtime";
53
+ import stream from "stream";
54
+ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
55
+ import { createServerRenderContext, ServerRenderContext } from "@hubspot/cms-components";
56
+ import { createHash } from "crypto";
57
+ import { existsSync, readdirSync, lstatSync } from "fs";
58
+ import { join } from "path/posix";
59
+ import { cloneElement } from "react";
60
+ function createPreloadLink(assetPath, basePath = "") {
61
+ if (assetPath && assetPath[0] !== "/") {
62
+ assetPath = `/${assetPath}`;
63
+ }
64
+ if (assetPath.endsWith(".js")) {
65
+ return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
66
+ } else if (CSS_LANGS_RE.test(assetPath)) {
67
+ return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
68
+ } else if (assetPath.endsWith(".woff")) {
69
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
70
+ } else if (assetPath.endsWith(".woff2")) {
71
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
72
+ } else if (assetPath.endsWith(".gif")) {
73
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
74
+ } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
75
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
76
+ } else if (assetPath.endsWith(".png")) {
77
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
78
+ } else {
79
+ throw new Error(`Unknown preload type for ${assetPath}`);
80
+ }
81
+ }
82
+ function getIslandUrls(roots, viteDevServer) {
83
+ return roots.map((island) => {
84
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
85
+ island.moduleId
86
+ );
87
+ if (!islandModule) {
88
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
89
+ }
90
+ const tweakedIsland = {
91
+ ...island,
92
+ url: islandModule.url
93
+ };
94
+ return tweakedIsland;
95
+ });
96
+ }
97
+ function isUngatedFor(gates, gate) {
98
+ return gates.includes(gate);
99
+ }
100
+ function ungatedAtBuildTimeFor(buildDir, gate) {
101
+ try {
102
+ console.log("loading path", path.join(buildDir, BUILD_INFO_PATH));
103
+ const buildInfo = require2(path.join(
104
+ buildDir,
105
+ BUILD_INFO_PATH
106
+ ));
107
+ return isUngatedFor(buildInfo.gates, gate);
108
+ } catch (e) {
109
+ console.error(`error loading build-info.json, path: ${BUILD_INFO_PATH}`);
110
+ return false;
111
+ }
112
+ }
113
+ function resolveIslandPlugin(gates) {
114
+ const sharedDepsEnabled = isUngatedFor(gates, "CMS:JSRenderer:SharedDeps");
115
+ return {
116
+ enforce: "pre",
117
+ name: "resolve-islands",
118
+ configResolved(config) {
119
+ viteRoot = config.root;
120
+ viteCommand = config.command;
121
+ },
122
+ load(id) {
123
+ if (id.endsWith("?island") || id.endsWith("?client")) {
124
+ const [idWithNoParam] = id.split("?");
125
+ const islandModuleImportPath = sharedDepsEnabled ? `${idWithNoParam}?client-entry` : idWithNoParam;
126
+ const componentExtension = path.extname(idWithNoParam);
127
+ const componentFilenameWithNoExtension = path.basename(
128
+ idWithNoParam,
129
+ componentExtension
130
+ );
131
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
132
+ let moduleId = viteCommand === "serve" ? idWithNoParam : modulePath;
133
+ if (sharedDepsEnabled) {
134
+ moduleId = moduleId.concat("?client-entry");
135
+ }
136
+ return `
137
+ const moduleId = '${moduleId}';
138
+
139
+ const lazyComponent = () => import('${islandModuleImportPath}');
140
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
141
+ lazyComponent.moduleId = moduleId;
142
+
143
+ export default lazyComponent;
144
+ `;
145
+ }
146
+ return null;
147
+ }
148
+ };
149
+ }
150
+ function clientIslandEntryPlugin() {
151
+ return {
152
+ enforce: "pre",
153
+ name: "client-island-entry-plugin",
154
+ resolveId(id) {
155
+ if (id === virtualClientRenderIslandModuleId) {
156
+ return virtualClientRenderIslandModuleId;
157
+ }
158
+ return null;
159
+ },
160
+ load(id) {
161
+ if (id.endsWith("?client-entry")) {
162
+ const [idWithNoParam] = id.split("?");
163
+ return `
164
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
165
+ import Component from '${idWithNoParam}';
166
+
167
+ export function render(island) {
168
+ return clientRenderIsland(island, Component)
169
+ }
170
+
171
+ export default Component;
172
+ `;
173
+ }
174
+ if (id === virtualClientRenderIslandModuleId) {
175
+ return clientRenderIsland;
176
+ }
177
+ return null;
178
+ }
179
+ };
180
+ }
181
+ async function renderComponentOnServer(Component, props, pageUrl, environmentConfig, renderOptions) {
182
+ const componentDebugName = Component.displayName || Component.name;
183
+ return renderOnServer(
184
+ /* @__PURE__ */ jsx2(Component, { ...props }),
185
+ pageUrl,
186
+ environmentConfig,
187
+ componentDebugName,
188
+ renderOptions
189
+ );
190
+ }
191
+ async function renderOnServer(elements, pageUrl, environmentConfig, debugName, renderOptions) {
192
+ const renderContext = createServerRenderContext(pageUrl, environmentConfig);
193
+ let html = await renderStreamToPromise(
194
+ /* @__PURE__ */ jsx2(ServerRenderContext.Provider, { value: renderContext, children: elements }),
195
+ renderOptions
196
+ );
197
+ if (renderContext.messagesForBrowser.length > 0) {
198
+ html = `${html}${scriptTagToLogServerMessages(
199
+ renderContext.messagesForBrowser,
200
+ `Server messages rendering: ${debugName}`
201
+ )}`;
202
+ }
203
+ return { html, renderContext };
204
+ }
205
+ function getEntryPointHash(entryPoint) {
206
+ return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
207
+ }
208
+ function getEntryPointHashWithIndexSuffix(entryPoint, index) {
209
+ const renderIndexSuffix = index != null ? `i${index}` : "";
210
+ return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
211
+ }
212
+ function getCombinedReactUrl() {
213
+ const hsEnv = process.env.HS_ENV;
214
+ const fileVersion = hsEnv === "prod" ? `react-combined.mjs` : "react-combined-qa.mjs";
215
+ return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;
216
+ }
217
+ function getIslandRuntimeConfigUrl() {
218
+ const hsEnv = process.env.HS_ENV;
219
+ const fileVersion = hsEnv === "prod" ? `island-runtime.mjs` : "island-runtime-qa.mjs";
220
+ return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;
221
+ }
222
+ function findAllModulesInRoot(webRoot2) {
223
+ const allModuleComponents = findAllComponentsIn(
224
+ webRoot2,
225
+ "./components/modules",
226
+ true
227
+ );
228
+ const moduleNames = Object.keys(allModuleComponents).map(
229
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
230
+ );
231
+ const moduleSubpaths = Object.keys(allModuleComponents);
232
+ return { moduleNames, moduleSubpaths };
233
+ }
234
+ function findAllPartialsInRoot(webRoot2) {
235
+ const allPartialComponents = findAllComponentsIn(
236
+ webRoot2,
237
+ "./components/partials",
238
+ false
239
+ );
240
+ const partialSubpaths = Object.keys(allPartialComponents);
241
+ const partialNames = partialSubpaths.map(
242
+ (partialSubpath) => basename(partialSubpath)
243
+ );
244
+ return { partialNames, partialSubpaths };
245
+ }
246
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl) {
247
+ const globals = [
248
+ `window.__hsEnvConfig = ${JSON.stringify(environmentConfig.toJSON())};`
249
+ ];
250
+ if (hsServerPageUrl) {
251
+ globals.push(`window.__hsServerPageUrl = '${hsServerPageUrl}';`);
252
+ }
253
+ return `
254
+ <script type="text/javascript">
255
+ ${globals.join("\n ")}
256
+ </script>
257
+ `;
258
+ }
259
+ function setIn(object, nestedKeysArray, value) {
260
+ let curr = object;
261
+ const finalKey = nestedKeysArray.pop();
262
+ for (let index = 0; index < nestedKeysArray.length; index++) {
263
+ const currentKey = nestedKeysArray[index];
264
+ const nextKey = nestedKeysArray[index + 1];
265
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
266
+ if (curr[currentKey] === void 0) {
267
+ curr[currentKey] = [];
268
+ }
269
+ }
270
+ if (curr[currentKey] === void 0) {
271
+ curr[currentKey] = {};
272
+ }
273
+ curr = curr[currentKey];
274
+ }
275
+ if (value !== void 0) {
276
+ curr[finalKey] = value;
277
+ }
278
+ }
279
+ function renderFieldsToJson(fields) {
280
+ let moduleJson;
281
+ const outputCallback = (callbackJson) => {
282
+ moduleJson = callbackJson;
283
+ };
284
+ renderToStaticMarkup(
285
+ cloneElement(fields, {
286
+ outputCallback
287
+ })
288
+ );
289
+ return moduleJson;
290
+ }
291
+ var COMPONENT_EXTENSIONS, ENTRY_POINTS_PATH, MODULE_FOLDER_PATH, VIRTUAL_ISLAND_RUNTIME, VIRTUAL_CONFIG_SETUP, CSS_LANGS_RE, collectCssModules, collectCssInDev, serializeIslandDataToJSON, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, require2, GATES, ENABLED_FEATURES_GATE_MAP, BUILD_INFO_PATH, viteRoot, viteCommand, clientRenderIsland, virtualClientRenderIslandModuleId, jsx2, promiseForNewWritableStream, renderStreamToPromise, scriptTagToLogServerMessages, getComponentExtension, hasComponentExtension, isStorybookStory, removeComponentExtension, COMBINED_REACT_BASE_PATH, ISLAND_RUNTIME_CONFIG_BASE_PATH, findAllComponentsIn;
292
+ var init_dist = __esm({
293
+ "../cms-js-internal/dist/index.js"() {
294
+ COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
295
+ ENTRY_POINTS_PATH = "components/partials/";
296
+ MODULE_FOLDER_PATH = "components/modules/";
297
+ VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
298
+ VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
299
+ CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
300
+ collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
301
+ const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
302
+ modulePathToStartWith
303
+ );
304
+ if (!appModulesForPath || appModulesForPath.size === 0) {
305
+ throw new Error(`No modules at: ${modulePathToStartWith}`);
306
+ } else if (appModulesForPath.size > 1) {
307
+ throw new Error(`More than one module at: ${modulePathToStartWith}`);
308
+ }
309
+ const appModule = Array.from(appModulesForPath.values())[0];
310
+ const allServerSideModulesImported = /* @__PURE__ */ new Set();
311
+ const newCssModules = [];
312
+ const moduleQueue = Array.from(appModule.importedModules);
313
+ for (const importedModule of moduleQueue) {
314
+ if (allServerSideModulesImported.has(importedModule.id)) {
315
+ continue;
316
+ }
317
+ allServerSideModulesImported.add(importedModule.id);
318
+ const isCss = CSS_LANGS_RE.test(importedModule.file);
319
+ const moduleModulesToQueue = Array.from(importedModule.importedModules);
320
+ if (isCss && !cssModulesImported.has(importedModule)) {
321
+ cssModulesImported.add(importedModule);
322
+ newCssModules.push(importedModule);
323
+ }
324
+ moduleQueue.push(...moduleModulesToQueue);
325
+ }
326
+ return newCssModules;
327
+ };
328
+ collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
329
+ return `${collectCssModules(
330
+ modulePathToStartWith,
331
+ viteServer,
332
+ cssModulesImported
333
+ ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
334
+ `;
335
+ };
336
+ serializeIslandDataToJSON = (tweakedIslandsArray, indent = 0) => {
337
+ const indentString = new Array(indent).fill(" ").join("");
338
+ return `${JSON.stringify(
339
+ tweakedIslandsArray.map(
340
+ ({
341
+ id,
342
+ moduleName,
343
+ moduleId,
344
+ props,
345
+ hydrateOn,
346
+ clientOnly,
347
+ priority,
348
+ url,
349
+ sharedStateID
350
+ }) => {
351
+ const output = {
352
+ id,
353
+ moduleName,
354
+ moduleId,
355
+ hydrateOn,
356
+ clientOnly,
357
+ priority,
358
+ props,
359
+ url
360
+ };
361
+ if (sharedStateID) {
362
+ output.sharedStateID = sharedStateID;
363
+ }
364
+ return output;
365
+ }
366
+ ),
367
+ null,
368
+ 2
369
+ ).replace(/\n/gm, `
370
+ ${indentString}`)}`;
371
+ };
372
+ writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0) => {
373
+ const indentString = new Array(indent).fill(" ").join("");
374
+ const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x) => !!x);
375
+ if (sharedStateIDs.length > 0) {
376
+ const stateByID = {};
377
+ sharedStateIDs.forEach(
378
+ (id) => stateByID[id] = perServerRequestData.get(id)
379
+ );
380
+ const stringifiedState = JSON.stringify(stateByID, null, 2);
381
+ return `
382
+
383
+ var newState = ${stringifiedState};
384
+ if(window.__hsSSInit) {
385
+ window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
386
+ } else {
387
+ window.__hsSSInit = newState;
388
+ }`.replace(/\n/gm, `
389
+ ${indentString}`);
390
+ }
391
+ return "";
392
+ };
393
+ createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent) => {
394
+ const islands = getIslandUrls(roots, viteDevServer);
395
+ return `window.__islands = ${serializeIslandDataToJSON(
396
+ islands,
397
+ indent
398
+ )}${writeSharedStateToJsGlobal(islands, perServerRequestData, indent)}`;
399
+ };
400
+ require2 = createRequire(import.meta.url);
401
+ GATES = [
402
+ "CMS:JSRenderer:SharedDeps",
403
+ "CMS:JSRenderer:GetServerSideProps",
404
+ "CMS:JSRenderer:LocalProxySchemaVersion1",
405
+ "CMS:JSRenderer:GraphQLQueryBuild"
406
+ ];
407
+ ENABLED_FEATURES_GATE_MAP = {
408
+ "cms:jsr:sharedDeps": "CMS:JSRenderer:SharedDeps",
409
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
410
+ "cms:jsr:localProxySchemaVersion1": "CMS:JSRenderer:LocalProxySchemaVersion1",
411
+ "cms:jsr:graphqQLQueryBuild": "CMS:JSRenderer:GraphQLQueryBuild"
412
+ };
413
+ BUILD_INFO_PATH = "/build-info.json";
414
+ 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";
415
+ virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
416
+ jsx2 = jsxRuntime.jsx;
417
+ promiseForNewWritableStream = () => {
418
+ const chunks = [];
419
+ const writableStream = new stream.Writable();
420
+ writableStream._write = (chunk, encoding, done) => {
421
+ chunks.push(Buffer.from(chunk));
422
+ done();
423
+ };
424
+ const streamDonePromise = new Promise((resolve, reject) => {
425
+ writableStream.on("error", (error) => {
426
+ reject(error);
427
+ });
428
+ writableStream._final = (done) => {
429
+ resolve(Buffer.concat(chunks).toString("utf8"));
430
+ done();
431
+ };
432
+ });
433
+ return { streamDonePromise, writableStream };
434
+ };
435
+ renderStreamToPromise = async (reactElements, renderOptions = {}) => {
436
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
437
+ const {
438
+ pipe
439
+ /* abort */
440
+ } = renderToPipeableStream(reactElements, {
441
+ ...renderOptions,
442
+ onShellReady() {
443
+ },
444
+ onAllReady() {
445
+ pipe(writableStream);
446
+ }
447
+ // We will log the error sent to the writable, any need to do something in these callbacks?
448
+ // onShellError(error) {},
449
+ // onError(error) {},
450
+ });
451
+ return streamDonePromise;
452
+ };
453
+ scriptTagToLogServerMessages = (messagesForBrowser, groupLabel) => {
454
+ if (!messagesForBrowser) {
455
+ return "";
456
+ }
457
+ const consoleLines = [];
458
+ for (const message of messagesForBrowser) {
459
+ const funcString = message.level === "error" ? "console.error" : "console.warn";
460
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
461
+ consoleLines.push(` ${funcString}(${argString});`);
462
+ }
463
+ let groupStart = "";
464
+ let groupEnd = "";
465
+ if (groupLabel !== null) {
466
+ groupStart = `
467
+ console.group(${JSON.stringify(groupLabel)});`;
468
+ groupEnd = ` console.groupEnd()
469
+ `;
470
+ }
471
+ return `<script>${groupStart}
472
+ ${consoleLines.join("\n")}
473
+ ${groupEnd}</script>
474
+ `;
475
+ };
476
+ getComponentExtension = (componentPath) => {
477
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
478
+ (ext) => componentPath.endsWith(ext)
479
+ );
480
+ if (filteredExtensions.length === 1) {
481
+ return filteredExtensions[0];
482
+ }
483
+ return void 0;
484
+ };
485
+ hasComponentExtension = (componentPath) => {
486
+ return !!getComponentExtension(componentPath);
487
+ };
488
+ isStorybookStory = (componentPath) => {
489
+ return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
490
+ };
491
+ removeComponentExtension = (componentPath) => {
492
+ const ext = getComponentExtension(componentPath);
493
+ if (ext == null) {
494
+ return componentPath;
495
+ }
496
+ return componentPath.slice(0, -1 * ext.length);
497
+ };
498
+ COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
499
+ ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
500
+ findAllComponentsIn = (webRoot2, componentsFolder, includeSubdirIndexJS) => {
501
+ const fullComponentsFolderPath = join(webRoot2, componentsFolder);
502
+ const componentsByName = {};
503
+ if (!existsSync(fullComponentsFolderPath)) {
504
+ return componentsByName;
505
+ }
506
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
507
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
508
+ const subdirPath = join(componentsFolder, fileOrFolderName);
509
+ const isDirectory = lstatSync(fullPath).isDirectory();
510
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
511
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
512
+ componentsByName[subdirPathNoExtension] = subdirPath;
513
+ } else if (isDirectory && includeSubdirIndexJS) {
514
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
515
+ const potentialIndexModule = join(
516
+ subdirPath,
517
+ `index${potentialExtension}`
518
+ );
519
+ const fullPotentialPath = join(
520
+ fullPath,
521
+ `index${potentialExtension}`
522
+ );
523
+ if (existsSync(fullPotentialPath)) {
524
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
525
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
526
+ break;
527
+ }
528
+ }
529
+ }
530
+ });
531
+ return componentsByName;
532
+ };
533
+ }
534
+ });
535
+
536
+ // src/storybook/main.ts
537
+ import path2 from "path";
538
+ import { mergeConfig } from "vite";
539
+ var webRoot = process.env.WEB_ROOT;
540
+ var storyPath = path2.resolve(process.cwd(), webRoot, "**/*.stories.*");
541
+ var jsRenderingGates = process.env.GATES ? process.env.GATES.split(",") : [];
542
+ var main_default = {
543
+ addons: ["@storybook/addon-essentials"],
544
+ framework: "@storybook/react-vite",
545
+ stories: [storyPath],
546
+ viteFinal: async (config) => {
547
+ const { resolveIslandPlugin: resolveIslandPlugin2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
548
+ const viteConfig = {
549
+ resolve: {
550
+ dedupe: [
551
+ "react",
552
+ "react-dom",
553
+ "@hubspot/cms-components",
554
+ "@hubspot/cms-dev-server"
555
+ ]
556
+ },
557
+ optimizeDeps: {
558
+ include: ["react", "react-dom", "react-dom/client"]
559
+ },
560
+ css: {
561
+ postcss: webRoot
562
+ },
563
+ plugins: [resolveIslandPlugin2(jsRenderingGates)]
564
+ };
565
+ return mergeConfig(config, viteConfig);
566
+ }
567
+ };
568
+ export {
569
+ main_default as default
570
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "0.4.15",
3
+ "version": "0.4.18",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@hubspot/cli-lib": "^3.0.12",
27
- "@hubspot/cms-components": "^0.4.15",
27
+ "@hubspot/cms-components": "^0.4.18",
28
28
  "@storybook/addon-actions": "^7.0.0-beta.19",
29
29
  "@storybook/addon-essentials": "^7.0.0-beta.19",
30
30
  "@storybook/addon-interactions": "^7.0.0-beta.19",
@@ -95,5 +95,5 @@
95
95
  "publishConfig": {
96
96
  "access": "public"
97
97
  },
98
- "gitHead": "8fe879bdaa60e23de6af81291693d2241f23e673"
98
+ "gitHead": "82893df718a2aae330cce8df35e00f27cb49adf1"
99
99
  }