@hubspot/cms-dev-server 0.18.10 → 0.18.12

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.
package/dist/run.js CHANGED
@@ -36,7 +36,7 @@ import { escapeRegExp } from "@hubspot/local-dev-lib/escapeRegExp";
36
36
  import inquirer from "inquirer";
37
37
  import { getThemeJSONPath } from "@hubspot/local-dev-lib/cms/themes";
38
38
  import findup from "findup-sync";
39
- import { getCwd, getAbsoluteFilePath } from "@hubspot/local-dev-lib/path";
39
+ import { getAbsoluteFilePath } from "@hubspot/local-dev-lib/path";
40
40
  import { logger } from "@hubspot/local-dev-lib/logger";
41
41
  import {
42
42
  isHubSpotHttpError,
@@ -85,22 +85,24 @@ function previewProjectPrompt(themeComponents) {
85
85
  }
86
86
  ]);
87
87
  }
88
- var getProjectConfig = async (_dir) => {
88
+ var getProjectConfig = async (_dir, isUsingLocalWorkspace = false) => {
89
89
  const getProjectConfigPath = (__dir) => {
90
- const projectDir = _dir ? getAbsoluteFilePath(_dir) : getCwd();
90
+ const dir = isUsingLocalWorkspace ? __dir : getAbsoluteFilePath(__dir);
91
+ if (!dir) {
92
+ return null;
93
+ }
91
94
  const PROJECT_CONFIG_FILE = "hsproject.json";
92
- const configPath2 = findup(PROJECT_CONFIG_FILE, {
93
- cwd: projectDir,
95
+ return findup(PROJECT_CONFIG_FILE, {
96
+ cwd: path.resolve(__dir),
94
97
  nocase: true
95
98
  });
96
- return configPath2;
97
99
  };
98
100
  const configPath = await getProjectConfigPath(_dir);
99
101
  if (!configPath) {
100
102
  return { projectConfig: null, projectDir: null };
101
103
  }
102
104
  try {
103
- const config = fs.readFileSync(configPath);
105
+ const config = fs.readFileSync(configPath, "utf8");
104
106
  const projectConfig = JSON.parse(config);
105
107
  return {
106
108
  projectDir: path.dirname(configPath),
@@ -189,12 +191,15 @@ function getIsLegacyApp(appConfig, appPath) {
189
191
  });
190
192
  return !hasAnyReactExtensions;
191
193
  }
192
- async function determineSrcAndDest() {
194
+ async function determineSrcAndDest(webRoot2, isUsingLocalWorkspace = false) {
193
195
  let absoluteSrc;
194
196
  let dest;
195
- const { projectDir, projectConfig } = await getProjectConfig(void 0);
197
+ const { projectDir, projectConfig } = await getProjectConfig(
198
+ webRoot2,
199
+ isUsingLocalWorkspace
200
+ );
196
201
  if (projectDir && projectConfig) {
197
- let themeJsonPath = getThemeJSONPath(void 0);
202
+ let themeJsonPath = getThemeJSONPath(webRoot2);
198
203
  if (!themeJsonPath) {
199
204
  const projectComponents = await findProjectComponents(projectDir);
200
205
  const themeComponents = projectComponents.filter(
@@ -658,7 +663,7 @@ function getDevServerCommandLineOptions(argv) {
658
663
  const storybook2 = args.findIndex((arg) => arg === "--storybook") > 0;
659
664
  const fieldGenEnabledOption2 = args.includes("--generateFieldsTypes");
660
665
  const resetSession2 = args.includes("--resetSession");
661
- const showUI = args.includes("--showUI");
666
+ const showUI2 = args.includes("--showUI");
662
667
  return {
663
668
  hubspotCliConfigPathOption: hubspotCliConfigPathOption2,
664
669
  hubspotCliAccountNameOption: hubspotCliAccountNameOption2,
@@ -666,17 +671,17 @@ function getDevServerCommandLineOptions(argv) {
666
671
  storybook: storybook2,
667
672
  fieldGenEnabledOption: fieldGenEnabledOption2,
668
673
  webRoot: webRoot2,
669
- showUI,
674
+ showUI: showUI2,
670
675
  resetSession: resetSession2
671
676
  };
672
677
  }
673
- async function buildThemePreviewOptions(webRoot2) {
678
+ async function buildThemePreviewOptions(webRoot2, isUsingLocalWorkspace = false) {
674
679
  const themeJsonPath = join(webRoot2, "theme.json");
675
680
  if (!existsSync(themeJsonPath)) {
676
681
  return void 0;
677
682
  }
678
683
  const filePaths = await getUploadableFileList(webRoot2, false);
679
- const { dest } = await determineSrcAndDest();
684
+ const { dest } = await determineSrcAndDest(webRoot2, isUsingLocalWorkspace);
680
685
  const startProgressBar = (numFiles) => {
681
686
  const initialUploadProgressBar = new cliProgress.SingleBar(
682
687
  {
@@ -741,17 +746,17 @@ async function buildThemePreviewOptions(webRoot2) {
741
746
  }
742
747
 
743
748
  // src/createDevServer.ts
744
- import path13 from "path";
749
+ import path15 from "path";
745
750
  import url2 from "url";
746
751
  import express3 from "express";
747
752
  import http3 from "http";
748
753
  import bodyParser from "body-parser";
749
754
  import { spawn } from "child_process";
750
- import { normalizePath as normalizePath7 } from "vite";
755
+ import { normalizePath as normalizePath9 } from "vite";
751
756
  import { Transform } from "stream";
752
757
 
753
758
  // src/routes/createDevServerRoutes.ts
754
- import { Router } from "express";
759
+ import { Router, urlencoded } from "express";
755
760
  import { createProxyMiddleware } from "http-proxy-middleware";
756
761
 
757
762
  // src/routes/partial.ts
@@ -790,7 +795,7 @@ function packagePath(metaUrl, projectPath) {
790
795
  );
791
796
  }
792
797
 
793
- // ../cms-js-internal/dist/types-BXr0V0Zd.js
798
+ // ../cms-js-internal/dist/types-CGxfMR-y.js
794
799
  import path3 from "path";
795
800
  import { createHash } from "crypto";
796
801
  import fs2, { readFileSync, existsSync as existsSync2, readdirSync, lstatSync } from "fs";
@@ -1011,7 +1016,13 @@ function findAllModulesInRoot(webRoot2) {
1011
1016
  (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
1012
1017
  );
1013
1018
  const moduleSubpaths = Object.keys(allModuleComponents);
1014
- return { moduleNames, moduleSubpaths };
1019
+ const moduleNamesWithExtension = Object.values(allModuleComponents).map(
1020
+ (path22) => {
1021
+ const file = path22.replace("components/modules/", "");
1022
+ return file.includes("/index.") ? file.split("/index.")[0] : file;
1023
+ }
1024
+ );
1025
+ return { moduleNames, moduleSubpaths, moduleNamesWithExtension };
1015
1026
  }
1016
1027
  function findAllPartialsInRoot(webRoot2) {
1017
1028
  const allPartialComponents = findAllComponentsIn(
@@ -1366,8 +1377,8 @@ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap)
1366
1377
  );
1367
1378
  return Object.fromEntries(relativeEntries);
1368
1379
  }
1369
- function toRelativePath(config, path14) {
1370
- return path14.replace(config.root, "");
1380
+ function toRelativePath(config, path16) {
1381
+ return path16.replace(`${config.root}/`, "");
1371
1382
  }
1372
1383
  function shouldSkipModule(config, moduleInfo, code) {
1373
1384
  const isExternal = config.command !== "serve" && moduleInfo.isExternal;
@@ -1405,11 +1416,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1405
1416
  let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
1406
1417
  let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
1407
1418
  traverse(sourceAst, {
1408
- ImportDeclaration(path14) {
1409
- if (t.isStringLiteral(path14.node.source, {
1419
+ ImportDeclaration(path16) {
1420
+ if (t.isStringLiteral(path16.node.source, {
1410
1421
  value: "@hubspot/cms-components"
1411
1422
  })) {
1412
- for (const specifier of path14.node.specifiers) {
1423
+ for (const specifier of path16.node.specifiers) {
1413
1424
  if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
1414
1425
  name: CMS_MODULE_COMPONENT_NAME
1415
1426
  })) {
@@ -1423,14 +1434,14 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1423
1434
  }
1424
1435
  }
1425
1436
  },
1426
- JSXOpeningElement(path14) {
1427
- if (t.isJSXIdentifier(path14.node.name, {
1437
+ JSXOpeningElement(path16) {
1438
+ if (t.isJSXIdentifier(path16.node.name, {
1428
1439
  name: moduleComponentLocalImportName
1429
1440
  })) {
1430
1441
  let cmsModuleName;
1431
1442
  let cmsModulePath;
1432
1443
  let cmsModuleLabel;
1433
- for (const prop of path14.node.attributes) {
1444
+ for (const prop of path16.node.attributes) {
1434
1445
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
1435
1446
  cmsModuleName = prop.value.value;
1436
1447
  continue;
@@ -1465,11 +1476,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1465
1476
  }
1466
1477
  contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
1467
1478
  }
1468
- if (t.isJSXIdentifier(path14.node.name, {
1479
+ if (t.isJSXIdentifier(path16.node.name, {
1469
1480
  name: dndAreaComponentLocalImportName
1470
1481
  })) {
1471
1482
  let dndAreaName;
1472
- for (const prop of path14.node.attributes) {
1483
+ for (const prop of path16.node.attributes) {
1473
1484
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
1474
1485
  dndAreaName = prop.value.value;
1475
1486
  continue;
@@ -1583,7 +1594,7 @@ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__
1583
1594
  function filterEntryPointsToModules(entryPointCmsModuleMap) {
1584
1595
  return Object.fromEntries(
1585
1596
  Object.entries(entryPointCmsModuleMap).filter(
1586
- ([entryPoint]) => entryPoint.startsWith("/components/modules/")
1597
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
1587
1598
  )
1588
1599
  );
1589
1600
  }
@@ -2053,7 +2064,7 @@ function trackUsage(action) {
2053
2064
  eventName: EVENT_NAME,
2054
2065
  action,
2055
2066
  nodeVersion: getNodeVersionData(),
2056
- version: "0.18.10",
2067
+ version: "0.18.12",
2057
2068
  os: getPlatform()
2058
2069
  };
2059
2070
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -2126,12 +2137,12 @@ var findLocalRenderPlaceholders = (body) => {
2126
2137
  );
2127
2138
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
2128
2139
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
2129
- const path14 = body.substring(
2140
+ const path16 = body.substring(
2130
2141
  startOffset + localJsRenderStartString.length,
2131
2142
  pathEndOffset
2132
2143
  );
2133
2144
  offsetSoFar = pathEndOffset + 1;
2134
- if (startOffset >= 0 && path14) {
2145
+ if (startOffset >= 0 && path16) {
2135
2146
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
2136
2147
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
2137
2148
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -2156,7 +2167,7 @@ var findLocalRenderPlaceholders = (body) => {
2156
2167
  result.push({
2157
2168
  startOffset,
2158
2169
  endOffset: endOffset + localJsRenderEndString.length,
2159
- path: path14,
2170
+ path: path16,
2160
2171
  json
2161
2172
  });
2162
2173
  }
@@ -2201,7 +2212,6 @@ import { http as hsCliHttp6 } from "@hubspot/local-dev-lib/http";
2201
2212
 
2202
2213
  // src/lib/renderModule.ts
2203
2214
  import { join as joinPosix2 } from "path/posix";
2204
- import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
2205
2215
  import * as cmsComponents2 from "@hubspot/cms-components";
2206
2216
  import { http as hsCliHttp3 } from "@hubspot/local-dev-lib/http";
2207
2217
 
@@ -2231,6 +2241,16 @@ async function fetchModuleGraphQLData(accountId, query, requestedModulePath, pag
2231
2241
  return dataQueryResult;
2232
2242
  }
2233
2243
 
2244
+ // src/lib/getFieldValuesForModule.ts
2245
+ import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
2246
+ function getFieldValuesForModule(fieldsJSON, fieldOverrides = {}) {
2247
+ const props = {};
2248
+ traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
2249
+ setIn(props, fieldPathArray, value);
2250
+ });
2251
+ return props;
2252
+ }
2253
+
2234
2254
  // src/lib/renderModule.ts
2235
2255
  var VALIDATE_FIELDS_ENDPOINT = "/designmanager/v1/modules/validate-fields";
2236
2256
  var VALIDATE_META_ENDPOINT = "/designmanager/v1/modules/validate-meta";
@@ -2447,13 +2467,6 @@ async function renderModule(viteServer, requestedModulePath, moduleProps, pageUr
2447
2467
  componentModule.unstable_modifyHtml
2448
2468
  ).then(applyFieldsValidationToRenderContext);
2449
2469
  }
2450
- function getFieldValuesForModule(fieldsJSON, fieldOverrides = {}) {
2451
- const props = {};
2452
- traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
2453
- setIn(props, fieldPathArray, value);
2454
- });
2455
- return props;
2456
- }
2457
2470
  var renderModule_default = renderModule;
2458
2471
 
2459
2472
  // src/proxyPage/utils.ts
@@ -2533,9 +2546,9 @@ var customColors = [
2533
2546
  ];
2534
2547
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
2535
2548
  var darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;
2536
- var renderLocalError_default = (path14, error) => {
2549
+ var renderLocalError_default = (path16, error) => {
2537
2550
  const stackWithColorClasses = Converter.toHtml(error.stack);
2538
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path14}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2551
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path16}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2539
2552
  };
2540
2553
 
2541
2554
  // src/proxyPage/fetchPreviewInfo.ts
@@ -3356,7 +3369,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
3356
3369
  const cssNeeded = Array.from(dom.window.document.querySelectorAll("style")).map((element) => element.outerHTML).join("");
3357
3370
  return { html: modulePreviewContent, cssNeeded };
3358
3371
  }
3359
- async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot2, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue) {
3372
+ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot2, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue, fieldOverrides = {}) {
3360
3373
  const modulePath = normalizePath3(
3361
3374
  path7.resolve(webRoot2, "components/modules/", moduleName)
3362
3375
  );
@@ -3399,6 +3412,10 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3399
3412
  const internalSsrPath = packagePath(import.meta.url, "internalSsr");
3400
3413
  const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
3401
3414
  const localFieldsJson = renderFieldsToJson(fields, modulePath);
3415
+ const localFieldValues = getFieldValuesForModule(
3416
+ localFieldsJson,
3417
+ fieldOverrides
3418
+ );
3402
3419
  const localModule = {
3403
3420
  isJsModule: true,
3404
3421
  schemaVersion: 2,
@@ -3439,6 +3456,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3439
3456
  `
3440
3457
  );
3441
3458
  }
3459
+ localRenderPlaceholders[0].json.props.fieldValues = localFieldValues;
3442
3460
  return await renderComponentForPlaceholder(
3443
3461
  0,
3444
3462
  localRenderPlaceholders[0],
@@ -3796,6 +3814,74 @@ ${e.stack}`);
3796
3814
  };
3797
3815
  var module_default = moduleRouteHandler;
3798
3816
 
3817
+ // src/routes/moduleFieldsJson.ts
3818
+ import path10 from "path";
3819
+ import { normalizePath as normalizePath6 } from "vite";
3820
+
3821
+ // src/lib/renderModuleFieldsJson.ts
3822
+ import { join as joinPosix4 } from "path/posix";
3823
+ var lookForModuleInFolder3 = async (modulePath, viteServer) => {
3824
+ let componentModule;
3825
+ const insideFolderPath = joinPosix4(modulePath, "index");
3826
+ try {
3827
+ componentModule = await viteServer.ssrLoadModule(insideFolderPath);
3828
+ } catch (e) {
3829
+ if (!e.message.includes("Failed to load url")) {
3830
+ throw e;
3831
+ }
3832
+ }
3833
+ return [componentModule, insideFolderPath];
3834
+ };
3835
+ async function renderModuleFieldsJson(viteServer, requestedModulePath) {
3836
+ let componentModule;
3837
+ try {
3838
+ if (!hasComponentExtension(requestedModulePath)) {
3839
+ [componentModule] = await lookForModuleInFolder3(
3840
+ requestedModulePath,
3841
+ viteServer
3842
+ );
3843
+ }
3844
+ if (!componentModule) {
3845
+ componentModule = await viteServer.ssrLoadModule(requestedModulePath);
3846
+ }
3847
+ } catch (error) {
3848
+ throw new Error(
3849
+ `Failed to load module ${requestedModulePath}: ${error.message}`
3850
+ );
3851
+ }
3852
+ if (!componentModule) {
3853
+ throw new Error(`Couldn't find module: ${requestedModulePath}`);
3854
+ }
3855
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
3856
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
3857
+ const fieldsJson = renderFieldsToJson(
3858
+ componentModule.fields,
3859
+ requestedModulePath
3860
+ );
3861
+ return fieldsJson;
3862
+ }
3863
+ var renderModuleFieldsJson_default = renderModuleFieldsJson;
3864
+
3865
+ // src/routes/moduleFieldsJson.ts
3866
+ var moduleFieldsJsonRouteHandler = async (request2, response) => {
3867
+ try {
3868
+ sendTrackingRequest("fields-json-route");
3869
+ const { webRoot: webRoot2, viteServer } = request2.app.locals;
3870
+ const { moduleName } = request2.params;
3871
+ const modulePath = normalizePath6(
3872
+ path10.resolve(webRoot2, "components/modules/", moduleName)
3873
+ );
3874
+ const fieldsJson = await renderModuleFieldsJson_default(viteServer, modulePath);
3875
+ return response.status(200).set({ "Content-Type": "application/json" }).json(fieldsJson);
3876
+ } catch (error) {
3877
+ console.error("Error processing module fields.json:", error);
3878
+ return response.status(500).json({
3879
+ error: "Failed to process module fields"
3880
+ });
3881
+ }
3882
+ };
3883
+ var moduleFieldsJson_default = moduleFieldsJsonRouteHandler;
3884
+
3799
3885
  // src/proxyPage/fetchContentMetadata.ts
3800
3886
  import http from "http";
3801
3887
  import https from "https";
@@ -4009,16 +4095,20 @@ async function fetchPreviewTemplates(accountId, previewToken) {
4009
4095
  url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}`
4010
4096
  })).data;
4011
4097
  }
4012
- async function fetchModuleByPath(accountId, path14) {
4098
+ async function fetchModuleByPath(accountId, path16) {
4013
4099
  return (await hsCliHttp8.get(accountId, {
4014
- url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path14}?portalId=${accountId}`
4100
+ url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path16}?portalId=${accountId}`
4015
4101
  })).data;
4016
4102
  }
4017
- async function fetchTemplateByPath(accountId, path14) {
4103
+ async function fetchTemplateByPath(accountId, path16) {
4018
4104
  return (await hsCliHttp8.get(accountId, {
4019
- url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path14}?portalId=${accountId}`
4105
+ url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path16}?portalId=${accountId}`
4020
4106
  })).data;
4021
4107
  }
4108
+ async function fetchModulePageDependencies(accountId, path16) {
4109
+ const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path16}`;
4110
+ return (await hsCliHttp8.get(accountId, { url: url3 })).data;
4111
+ }
4022
4112
 
4023
4113
  // src/components/HubLTemplatesList.tsx
4024
4114
  import { jsx as jsx7, jsxs as jsxs3 } from "react/jsx-runtime";
@@ -4258,8 +4348,8 @@ function proxyServerlessRequest(req, res, next) {
4258
4348
  }
4259
4349
 
4260
4350
  // src/routes/modulePreviewRouteHandler.ts
4261
- import path10 from "path";
4262
- import { normalizePath as normalizePath6 } from "vite";
4351
+ import path11 from "path";
4352
+ import { normalizePath as normalizePath7 } from "vite";
4263
4353
  async function modulePreviewRouteHandler(request2, response) {
4264
4354
  sendTrackingRequest("view-module-preview-route");
4265
4355
  const {
@@ -4273,9 +4363,46 @@ async function modulePreviewRouteHandler(request2, response) {
4273
4363
  projectComponentPath
4274
4364
  } = request2.app.locals;
4275
4365
  const moduleName = request2.params.moduleName;
4276
- const modulePath = normalizePath6(
4277
- path10.resolve(webRoot2, "components/modules/", moduleName)
4366
+ const modulePath = normalizePath7(
4367
+ path11.resolve(webRoot2, "components/modules/", moduleName)
4278
4368
  );
4369
+ const PREVIEWER_APP_PARAM = "hsPreviewerApp";
4370
+ let fieldOverrides = {};
4371
+ if (request2.method === "POST" && request2.body) {
4372
+ if (request2.query[PREVIEWER_APP_PARAM] === "module" && request2.body.module_data) {
4373
+ fieldOverrides = request2.body.module_data;
4374
+ } else {
4375
+ fieldOverrides = request2.body;
4376
+ }
4377
+ try {
4378
+ if (typeof fieldOverrides === "string") {
4379
+ const parsedFieldOverrides = JSON.parse(fieldOverrides);
4380
+ if (parsedFieldOverrides && typeof parsedFieldOverrides === "object" && !Array.isArray(parsedFieldOverrides)) {
4381
+ fieldOverrides = parsedFieldOverrides;
4382
+ } else {
4383
+ throw new Error("Parsed field overrides must be an object");
4384
+ }
4385
+ }
4386
+ } catch (e) {
4387
+ console.error(
4388
+ `Error parsing field for module "${moduleName}": ${e.message}`,
4389
+ "\nReceived value:",
4390
+ fieldOverrides
4391
+ );
4392
+ }
4393
+ } else if (request2.query.fields) {
4394
+ try {
4395
+ if (typeof request2.query.fields === "string") {
4396
+ fieldOverrides = JSON.parse(
4397
+ decodeURIComponent(request2.query.fields.replace(/\+/g, "%20"))
4398
+ );
4399
+ }
4400
+ } catch (e) {
4401
+ console.error(
4402
+ `Error parsing field param for module ${moduleName}: ${request2.query.fields}`
4403
+ );
4404
+ }
4405
+ }
4279
4406
  try {
4280
4407
  const {
4281
4408
  html: renderedHtml,
@@ -4293,7 +4420,8 @@ async function modulePreviewRouteHandler(request2, response) {
4293
4420
  projectName,
4294
4421
  projectComponentPath,
4295
4422
  fullOriginalUrlFromRequest(request2),
4296
- request2.get("COOKIE")
4423
+ request2.get("COOKIE"),
4424
+ fieldOverrides
4297
4425
  );
4298
4426
  const baseTemplatePath = packagePath(
4299
4427
  import.meta.url,
@@ -4489,6 +4617,7 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
4489
4617
  );
4490
4618
  }
4491
4619
  devServerApp.use(viteServer.middlewares);
4620
+ devServerApp.use(urlencoded());
4492
4621
  devServerApp.get("/proxy", proxyPathPageRouteHandler);
4493
4622
  devServerApp.get("/partials/", linksToAllPartialsRouteHandler_default);
4494
4623
  devServerApp.get("/partial/:partial", partial_default);
@@ -4497,7 +4626,12 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
4497
4626
  devServerApp.get("/preview/module/:moduleName", modulePreviewRouteHandler_default);
4498
4627
  devServerApp.get("/modules/", linksToAllModulesRouteHandler_default);
4499
4628
  devServerApp.get("/module/:moduleName", module_default);
4629
+ devServerApp.get(
4630
+ "/preview/module/:moduleName/fields.json",
4631
+ moduleFieldsJson_default
4632
+ );
4500
4633
  devServerApp.get("/module/:moduleName/*", module_default);
4634
+ devServerApp.post("/preview/module/:moduleName", modulePreviewRouteHandler_default);
4501
4635
  devServerApp.get("/hublmodule/:modulePath(*)", hublModuleRouteHandler);
4502
4636
  devServerApp.get("/template/:templatePath(*)", templateRouteHandler);
4503
4637
  devServerApp.all("/hs/serverless/*", proxyServerlessRequest);
@@ -4577,7 +4711,9 @@ function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
4577
4711
  environmentConfig,
4578
4712
  gates
4579
4713
  );
4580
- const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
4714
+ const localRenderPlaceholders = findLocalRenderPlaceholders(
4715
+ pageHtml.data
4716
+ );
4581
4717
  if (localRenderPlaceholders.length) {
4582
4718
  hasJSBuildingBlocks = true;
4583
4719
  localProxyUrl = `http://${hostName}.hslocal.net:${devServerPort}${pathName}`;
@@ -4772,25 +4908,67 @@ import { createServer as createViteServer2 } from "vite";
4772
4908
  import { default as react2 } from "@vitejs/plugin-react";
4773
4909
 
4774
4910
  // src/lib/getDevServerUIData.ts
4775
- async function getDevServerUIData(reqLocals) {
4776
- const { themeWebRoot, authedPortalId, projectName, localPreviewToken } = reqLocals;
4777
- const { moduleNames } = findAllModulesInRoot(themeWebRoot);
4778
- const { partialNames } = findAllPartialsInRoot(themeWebRoot);
4779
- const hubLModuleData = await fetchHubLModules(
4780
- authedPortalId,
4781
- localPreviewToken
4911
+ import path12 from "path";
4912
+ import { normalizePath as normalizePath8 } from "vite";
4913
+ function mapModulesData(modules, themeWebRoot, viteServer) {
4914
+ return Promise.all(
4915
+ modules.moduleNames.map(async (name, index) => {
4916
+ const modulePath = normalizePath8(
4917
+ path12.resolve(themeWebRoot, "components/modules/", name)
4918
+ );
4919
+ const fieldsJson = await renderModuleFieldsJson_default(viteServer, modulePath);
4920
+ return {
4921
+ name,
4922
+ subPath: modules.moduleSubpaths[index],
4923
+ nameWithExtension: modules.moduleNamesWithExtension[index],
4924
+ fieldsJson
4925
+ };
4926
+ })
4782
4927
  );
4783
- const hubLTemplateData = await fetchPreviewTemplates(
4928
+ }
4929
+ function mapPartialsData(modules) {
4930
+ return modules.partialNames.map((name, index) => ({
4931
+ name,
4932
+ subPath: modules.partialSubpaths[index]
4933
+ }));
4934
+ }
4935
+ async function getDevServerUIData(reqLocals) {
4936
+ const {
4937
+ themeWebRoot,
4784
4938
  authedPortalId,
4785
- localPreviewToken
4939
+ projectName,
4940
+ localPreviewToken,
4941
+ webRootProjectComponentFolder,
4942
+ viteServer
4943
+ } = reqLocals;
4944
+ const modulesData = findAllModulesInRoot(themeWebRoot);
4945
+ const partialsData = findAllPartialsInRoot(themeWebRoot);
4946
+ const mappedModulesData = await mapModulesData(
4947
+ modulesData,
4948
+ themeWebRoot,
4949
+ viteServer
4786
4950
  );
4951
+ let hubLModuleData = { objects: [] };
4952
+ let hubLTemplateData = { objects: [] };
4953
+ if (authedPortalId) {
4954
+ hubLModuleData = await fetchHubLModules(authedPortalId, localPreviewToken);
4955
+ hubLTemplateData = await fetchPreviewTemplates(
4956
+ authedPortalId,
4957
+ localPreviewToken
4958
+ );
4959
+ }
4960
+ const hubLTemplates = (hubLTemplateData == null ? void 0 : hubLTemplateData.objects.filter(
4961
+ (template) => isCodedFile(template.filename)
4962
+ )) || [];
4787
4963
  return {
4788
4964
  authedPortalId,
4789
4965
  projectName,
4790
- moduleNames,
4791
- partialNames,
4966
+ modulesData: mappedModulesData,
4967
+ partialsData: mapPartialsData(partialsData),
4792
4968
  hubLModules: (hubLModuleData == null ? void 0 : hubLModuleData.objects) || [],
4793
- hubLTemplates: (hubLTemplateData == null ? void 0 : hubLTemplateData.objects) || []
4969
+ hubLTemplates,
4970
+ themeWebRoot,
4971
+ webRootProjectComponentFolder
4794
4972
  };
4795
4973
  }
4796
4974
  var getDevServerUIData_default = getDevServerUIData;
@@ -4803,7 +4981,11 @@ async function createAppServer(webRoot2, reqLocals, port) {
4803
4981
  server: {
4804
4982
  middlewareMode: true,
4805
4983
  host: "hslocal.net",
4806
- origin
4984
+ origin,
4985
+ hmr: {
4986
+ port: port + 1,
4987
+ host: "hslocal.net"
4988
+ }
4807
4989
  },
4808
4990
  appType: "custom",
4809
4991
  root: webRoot2,
@@ -4841,20 +5023,38 @@ async function createAppServer(webRoot2, reqLocals, port) {
4841
5023
  };
4842
5024
  const viteServer = await createViteServer2(viteConfig);
4843
5025
  app.use(viteServer.middlewares);
5026
+ app.get("/api/module-pages", async (req, res, next) => {
5027
+ const { path: path16, portalId } = req.query;
5028
+ if (!path16 || !portalId) {
5029
+ return res.status(400).json({ error: "Missing required parameters" });
5030
+ }
5031
+ try {
5032
+ const data = await fetchModulePageDependencies(
5033
+ Number(portalId),
5034
+ path16
5035
+ );
5036
+ res.json(data);
5037
+ } catch (err) {
5038
+ next(err);
5039
+ }
5040
+ });
4844
5041
  app.use("*", async (req, res) => {
4845
5042
  try {
4846
- const inititialProps = await getDevServerUIData_default(reqLocals);
5043
+ const initialProps = await getDevServerUIData_default({
5044
+ ...reqLocals,
5045
+ viteServer
5046
+ });
4847
5047
  const url3 = req.originalUrl.replace("/", "");
4848
- let template = await fs4.readFile("./app/index.html", "utf-8");
5048
+ let template = await fs4.readFile(`${webRoot2}/index.html`, "utf-8");
4849
5049
  template = await viteServer.transformIndexHtml(url3, template);
4850
5050
  const { render } = await viteServer.ssrLoadModule(
4851
- "./app/serverEntry.tsx"
5051
+ `${webRoot2}/serverEntry.tsx`
4852
5052
  );
4853
- const rendered = await render(inititialProps);
5053
+ const rendered = await render(initialProps);
4854
5054
  const html = template.replace(`<!--app-head-->`, rendered.head ?? "").replace(`<!--app-html-->`, rendered.html ?? "").replace(
4855
5055
  `<!--app-script-->`,
4856
5056
  `<script>window.__hsInitialProps = ${JSON.stringify(
4857
- inititialProps
5057
+ initialProps
4858
5058
  )}</script>` ?? ""
4859
5059
  );
4860
5060
  res.status(200).set({ "Content-Type": "text/html" }).send(html);
@@ -4864,6 +5064,10 @@ async function createAppServer(webRoot2, reqLocals, port) {
4864
5064
  res.status(500).end(e.stack);
4865
5065
  }
4866
5066
  });
5067
+ app.use((err, req, res, next) => {
5068
+ console.error("API Error:", err);
5069
+ res.status(500).json({ error: "Internal server error" });
5070
+ });
4867
5071
  app.listen(port, () => {
4868
5072
  console.log(`Server started at http://localhost:${port}`);
4869
5073
  });
@@ -5030,7 +5234,7 @@ async function fetchWebsiteDomainNames(portalId) {
5030
5234
  }
5031
5235
 
5032
5236
  // src/lib/validateHSPlatform.ts
5033
- import path11 from "path";
5237
+ import path13 from "path";
5034
5238
  import fs5 from "fs";
5035
5239
  import select from "@inquirer/select";
5036
5240
  import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
@@ -5042,12 +5246,12 @@ function findHSProjectJson(startPath) {
5042
5246
  let currentDir = startPath;
5043
5247
  let dirLevel = 0;
5044
5248
  const maxDirLevel = 4;
5045
- while (path11.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
5046
- const filePath = path11.join(currentDir, HSPROJECT_JSON);
5249
+ while (path13.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
5250
+ const filePath = path13.join(currentDir, HSPROJECT_JSON);
5047
5251
  if (checkFileExists(filePath)) {
5048
5252
  return filePath;
5049
5253
  }
5050
- currentDir = path11.dirname(currentDir);
5254
+ currentDir = path13.dirname(currentDir);
5051
5255
  dirLevel++;
5052
5256
  }
5053
5257
  console.log(
@@ -5353,7 +5557,7 @@ function writeFieldsType(fields, fileName, typeName) {
5353
5557
 
5354
5558
  // src/lib/watchFieldsUpdates.ts
5355
5559
  import fs6 from "fs";
5356
- import path12 from "path";
5560
+ import path14 from "path";
5357
5561
  import readline from "readline";
5358
5562
  var lastSerializedFieldsCache = {};
5359
5563
  var formatAsTypeName = (str) => {
@@ -5365,9 +5569,9 @@ var isInModulesFolder = (filePath, projectRoot) => {
5365
5569
  const getEntryPathFromId = (id) => {
5366
5570
  return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
5367
5571
  };
5368
- const currentModuleId = path12.normalize(filePath);
5572
+ const currentModuleId = path14.normalize(filePath);
5369
5573
  const moduleEntryPath = getEntryPathFromId(currentModuleId);
5370
- const subFolderTokens = moduleEntryPath.split(path12.sep);
5574
+ const subFolderTokens = moduleEntryPath.split(path14.sep);
5371
5575
  return {
5372
5576
  inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
5373
5577
  isRootModuleFile: subFolderTokens.length === 3
@@ -5394,10 +5598,10 @@ var getIndexFile = (filePath, projectRoot) => {
5394
5598
  return void 0;
5395
5599
  if (isRootModuleFile)
5396
5600
  return { indexFilePath: filePath, isRootModuleFile };
5397
- const dir = path12.dirname(filePath);
5601
+ const dir = path14.dirname(filePath);
5398
5602
  const files = fs6.readdirSync(dir);
5399
5603
  const indexFileName = files.find((file) => file.startsWith("index."));
5400
- return indexFileName ? { indexFilePath: path12.join(dir, indexFileName), isRootModuleFile } : void 0;
5604
+ return indexFileName ? { indexFilePath: path14.join(dir, indexFileName), isRootModuleFile } : void 0;
5401
5605
  };
5402
5606
  var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
5403
5607
  let indexFile;
@@ -5421,7 +5625,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5421
5625
  if (!indexInfo)
5422
5626
  return;
5423
5627
  const { indexFilePath, isRootModuleFile } = indexInfo;
5424
- const indexFileName = path12.parse(indexFilePath).name;
5628
+ const indexFileName = path14.parse(indexFilePath).name;
5425
5629
  const isTypeFile = filePath.endsWith(".types.ts");
5426
5630
  if (isTypeFile)
5427
5631
  return;
@@ -5432,7 +5636,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5432
5636
  );
5433
5637
  if (fields) {
5434
5638
  const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
5435
- const typeFilePath = path12.join(path12.dirname(filePath), typeFileName);
5639
+ const typeFilePath = path14.join(path14.dirname(filePath), typeFileName);
5436
5640
  const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
5437
5641
  const serializedFields = JSON.stringify(fields);
5438
5642
  if (lastSerializedFields === serializedFields)
@@ -5440,7 +5644,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5440
5644
  const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
5441
5645
  if (!hasAutoGenComment)
5442
5646
  return;
5443
- const moduleFolderName = path12.basename(path12.dirname(filePath));
5647
+ const moduleFolderName = path14.basename(path14.dirname(filePath));
5444
5648
  const outputTypeName = formatAsTypeName(moduleFolderName);
5445
5649
  const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
5446
5650
  if (didSucceed) {
@@ -5456,7 +5660,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
5456
5660
  var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
5457
5661
  const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
5458
5662
  moduleSubpaths.forEach((modulePath) => {
5459
- const resolvedPath = path12.resolve(projectRoot, modulePath);
5663
+ const resolvedPath = path14.resolve(projectRoot, modulePath);
5460
5664
  maybeUpdateFields(resolvedPath, viteServer, projectRoot);
5461
5665
  });
5462
5666
  const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
@@ -5480,7 +5684,7 @@ var BASE_PATH = "/";
5480
5684
  var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
5481
5685
  var SHADOW_PORT = 1442;
5482
5686
  var STORYBOOK_PORT = process.env.STORYBOOK_PORT ? parseInt(process.env.STORYBOOK_PORT, 10) : 3123;
5483
- async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2, themePreviewOptions2, showUI) {
5687
+ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2, themePreviewOptions2, showUI2) {
5484
5688
  let authedPortalId = null;
5485
5689
  let authedEnv = null;
5486
5690
  let jsRenderingGates = [];
@@ -5594,7 +5798,7 @@ Local proxy functionality and module preview routes will not work without settin
5594
5798
  } catch (e) {
5595
5799
  authedHublet = "na1";
5596
5800
  }
5597
- const absoluteWebRoot = normalizePath7(path13.resolve(process.cwd(), webRoot2));
5801
+ const absoluteWebRoot = normalizePath9(path15.resolve(process.cwd(), webRoot2));
5598
5802
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
5599
5803
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
5600
5804
  if (authedPortalId) {
@@ -5685,9 +5889,9 @@ Local proxy functionality and module preview routes will not work without settin
5685
5889
  HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
5686
5890
  `
5687
5891
  );
5688
- if (showUI) {
5689
- const appWebRoot = path13.join(
5690
- path13.dirname(url2.fileURLToPath(import.meta.url)),
5892
+ if (showUI2) {
5893
+ const appWebRoot = path15.join(
5894
+ path15.dirname(url2.fileURLToPath(import.meta.url)),
5691
5895
  "../app"
5692
5896
  );
5693
5897
  const reqLocals = {
@@ -5703,8 +5907,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
5703
5907
  httpServers.push(appServer);
5704
5908
  }
5705
5909
  if (storybook2) {
5706
- const packageRoot = path13.dirname(url2.fileURLToPath(import.meta.url));
5707
- const configPath = path13.resolve(packageRoot, "./storybook-main");
5910
+ const packageRoot = path15.dirname(url2.fileURLToPath(import.meta.url));
5911
+ const configPath = path15.resolve(packageRoot, "./storybook-main");
5708
5912
  sendTrackingRequest("start-storybook");
5709
5913
  const storybookProcess = spawn(
5710
5914
  "sb",
@@ -5724,7 +5928,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
5724
5928
  portalId: authedPortalId.toString(),
5725
5929
  hsEnv: authedEnv,
5726
5930
  hublet: authedHublet,
5727
- WEB_ROOT: path13.join(webRoot2, "components")
5931
+ WEB_ROOT: path15.join(webRoot2, "components")
5728
5932
  }
5729
5933
  }
5730
5934
  );
@@ -5772,7 +5976,8 @@ var {
5772
5976
  sslEnabledOption,
5773
5977
  storybook,
5774
5978
  fieldGenEnabledOption,
5775
- resetSession
5979
+ resetSession,
5980
+ showUI
5776
5981
  } = getDevServerCommandLineOptions(process.argv);
5777
5982
  if (!webRoot) {
5778
5983
  throw new Error(`No web root path argument specified`);
@@ -5792,5 +5997,6 @@ createDevServer_default(
5792
5997
  hubspotCliAccountNameOption,
5793
5998
  sslEnabledOption,
5794
5999
  fieldGenEnabledOption,
5795
- themePreviewOptions
6000
+ themePreviewOptions,
6001
+ showUI
5796
6002
  );