@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/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createServer as createViteServer } from "vite";
3
3
  import { default as react } from "@vitejs/plugin-react";
4
4
 
5
- // ../cms-js-internal/dist/types-BXr0V0Zd.js
5
+ // ../cms-js-internal/dist/types-CGxfMR-y.js
6
6
  import path from "path";
7
7
  import { createHash } from "crypto";
8
8
  import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
@@ -223,7 +223,13 @@ function findAllModulesInRoot(webRoot) {
223
223
  (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
224
224
  );
225
225
  const moduleSubpaths = Object.keys(allModuleComponents);
226
- return { moduleNames, moduleSubpaths };
226
+ const moduleNamesWithExtension = Object.values(allModuleComponents).map(
227
+ (path22) => {
228
+ const file = path22.replace("components/modules/", "");
229
+ return file.includes("/index.") ? file.split("/index.")[0] : file;
230
+ }
231
+ );
232
+ return { moduleNames, moduleSubpaths, moduleNamesWithExtension };
227
233
  }
228
234
  function findAllPartialsInRoot(webRoot) {
229
235
  const allPartialComponents = findAllComponentsIn(
@@ -578,8 +584,8 @@ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap)
578
584
  );
579
585
  return Object.fromEntries(relativeEntries);
580
586
  }
581
- function toRelativePath(config, path13) {
582
- return path13.replace(config.root, "");
587
+ function toRelativePath(config, path15) {
588
+ return path15.replace(`${config.root}/`, "");
583
589
  }
584
590
  function shouldSkipModule(config, moduleInfo, code) {
585
591
  const isExternal = config.command !== "serve" && moduleInfo.isExternal;
@@ -617,11 +623,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
617
623
  let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
618
624
  let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
619
625
  traverse(sourceAst, {
620
- ImportDeclaration(path13) {
621
- if (t.isStringLiteral(path13.node.source, {
626
+ ImportDeclaration(path15) {
627
+ if (t.isStringLiteral(path15.node.source, {
622
628
  value: "@hubspot/cms-components"
623
629
  })) {
624
- for (const specifier of path13.node.specifiers) {
630
+ for (const specifier of path15.node.specifiers) {
625
631
  if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
626
632
  name: CMS_MODULE_COMPONENT_NAME
627
633
  })) {
@@ -635,14 +641,14 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
635
641
  }
636
642
  }
637
643
  },
638
- JSXOpeningElement(path13) {
639
- if (t.isJSXIdentifier(path13.node.name, {
644
+ JSXOpeningElement(path15) {
645
+ if (t.isJSXIdentifier(path15.node.name, {
640
646
  name: moduleComponentLocalImportName
641
647
  })) {
642
648
  let cmsModuleName;
643
649
  let cmsModulePath;
644
650
  let cmsModuleLabel;
645
- for (const prop of path13.node.attributes) {
651
+ for (const prop of path15.node.attributes) {
646
652
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
647
653
  cmsModuleName = prop.value.value;
648
654
  continue;
@@ -677,11 +683,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
677
683
  }
678
684
  contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
679
685
  }
680
- if (t.isJSXIdentifier(path13.node.name, {
686
+ if (t.isJSXIdentifier(path15.node.name, {
681
687
  name: dndAreaComponentLocalImportName
682
688
  })) {
683
689
  let dndAreaName;
684
- for (const prop of path13.node.attributes) {
690
+ for (const prop of path15.node.attributes) {
685
691
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
686
692
  dndAreaName = prop.value.value;
687
693
  continue;
@@ -795,7 +801,7 @@ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__
795
801
  function filterEntryPointsToModules(entryPointCmsModuleMap) {
796
802
  return Object.fromEntries(
797
803
  Object.entries(entryPointCmsModuleMap).filter(
798
- ([entryPoint]) => entryPoint.startsWith("/components/modules/")
804
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
799
805
  )
800
806
  );
801
807
  }
@@ -1023,17 +1029,17 @@ Custom origin: ${process.env.VITE_ORIGIN}
1023
1029
  var createViteDevServer_default = createViteDevServer;
1024
1030
 
1025
1031
  // src/createDevServer.ts
1026
- import path12 from "path";
1032
+ import path14 from "path";
1027
1033
  import url2 from "url";
1028
1034
  import express3 from "express";
1029
1035
  import http3 from "http";
1030
1036
  import bodyParser from "body-parser";
1031
1037
  import { spawn } from "child_process";
1032
- import { normalizePath as normalizePath7 } from "vite";
1038
+ import { normalizePath as normalizePath9 } from "vite";
1033
1039
  import { Transform } from "stream";
1034
1040
 
1035
1041
  // src/routes/createDevServerRoutes.ts
1036
- import { Router } from "express";
1042
+ import { Router, urlencoded } from "express";
1037
1043
  import { createProxyMiddleware } from "http-proxy-middleware";
1038
1044
 
1039
1045
  // src/routes/partial.ts
@@ -1449,7 +1455,7 @@ function trackUsage(action) {
1449
1455
  eventName: EVENT_NAME,
1450
1456
  action,
1451
1457
  nodeVersion: getNodeVersionData(),
1452
- version: "0.18.10",
1458
+ version: "0.18.12",
1453
1459
  os: getPlatform()
1454
1460
  };
1455
1461
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -1522,12 +1528,12 @@ var findLocalRenderPlaceholders = (body) => {
1522
1528
  );
1523
1529
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1524
1530
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1525
- const path13 = body.substring(
1531
+ const path15 = body.substring(
1526
1532
  startOffset + localJsRenderStartString.length,
1527
1533
  pathEndOffset
1528
1534
  );
1529
1535
  offsetSoFar = pathEndOffset + 1;
1530
- if (startOffset >= 0 && path13) {
1536
+ if (startOffset >= 0 && path15) {
1531
1537
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1532
1538
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1533
1539
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1552,7 +1558,7 @@ var findLocalRenderPlaceholders = (body) => {
1552
1558
  result.push({
1553
1559
  startOffset,
1554
1560
  endOffset: endOffset + localJsRenderEndString.length,
1555
- path: path13,
1561
+ path: path15,
1556
1562
  json
1557
1563
  });
1558
1564
  }
@@ -1597,7 +1603,6 @@ import { http as hsCliHttp6 } from "@hubspot/local-dev-lib/http";
1597
1603
 
1598
1604
  // src/lib/renderModule.ts
1599
1605
  import { join as joinPosix2 } from "path/posix";
1600
- import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
1601
1606
  import * as cmsComponents2 from "@hubspot/cms-components";
1602
1607
  import { http as hsCliHttp3 } from "@hubspot/local-dev-lib/http";
1603
1608
 
@@ -1627,6 +1632,16 @@ async function fetchModuleGraphQLData(accountId, query, requestedModulePath, pag
1627
1632
  return dataQueryResult;
1628
1633
  }
1629
1634
 
1635
+ // src/lib/getFieldValuesForModule.ts
1636
+ import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
1637
+ function getFieldValuesForModule(fieldsJSON, fieldOverrides = {}) {
1638
+ const props = {};
1639
+ traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
1640
+ setIn(props, fieldPathArray, value);
1641
+ });
1642
+ return props;
1643
+ }
1644
+
1630
1645
  // src/lib/renderModule.ts
1631
1646
  var VALIDATE_FIELDS_ENDPOINT = "/designmanager/v1/modules/validate-fields";
1632
1647
  var VALIDATE_META_ENDPOINT = "/designmanager/v1/modules/validate-meta";
@@ -1843,13 +1858,6 @@ async function renderModule(viteServer, requestedModulePath, moduleProps, pageUr
1843
1858
  componentModule.unstable_modifyHtml
1844
1859
  ).then(applyFieldsValidationToRenderContext);
1845
1860
  }
1846
- function getFieldValuesForModule(fieldsJSON, fieldOverrides = {}) {
1847
- const props = {};
1848
- traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {
1849
- setIn(props, fieldPathArray, value);
1850
- });
1851
- return props;
1852
- }
1853
1861
  var renderModule_default = renderModule;
1854
1862
 
1855
1863
  // src/proxyPage/utils.ts
@@ -1929,9 +1937,9 @@ var customColors = [
1929
1937
  ];
1930
1938
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
1931
1939
  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;`;
1932
- var renderLocalError_default = (path13, error) => {
1940
+ var renderLocalError_default = (path15, error) => {
1933
1941
  const stackWithColorClasses = Converter.toHtml(error.stack);
1934
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path13}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1942
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path15}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1935
1943
  };
1936
1944
 
1937
1945
  // src/proxyPage/fetchPreviewInfo.ts
@@ -2752,7 +2760,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2752
2760
  const cssNeeded = Array.from(dom.window.document.querySelectorAll("style")).map((element) => element.outerHTML).join("");
2753
2761
  return { html: modulePreviewContent, cssNeeded };
2754
2762
  }
2755
- async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue) {
2763
+ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue, fieldOverrides = {}) {
2756
2764
  const modulePath = normalizePath3(
2757
2765
  path6.resolve(webRoot, "components/modules/", moduleName)
2758
2766
  );
@@ -2795,6 +2803,10 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
2795
2803
  const internalSsrPath = packagePath(import.meta.url, "internalSsr");
2796
2804
  const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
2797
2805
  const localFieldsJson = renderFieldsToJson(fields, modulePath);
2806
+ const localFieldValues = getFieldValuesForModule(
2807
+ localFieldsJson,
2808
+ fieldOverrides
2809
+ );
2798
2810
  const localModule = {
2799
2811
  isJsModule: true,
2800
2812
  schemaVersion: 2,
@@ -2835,6 +2847,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
2835
2847
  `
2836
2848
  );
2837
2849
  }
2850
+ localRenderPlaceholders[0].json.props.fieldValues = localFieldValues;
2838
2851
  return await renderComponentForPlaceholder(
2839
2852
  0,
2840
2853
  localRenderPlaceholders[0],
@@ -3192,6 +3205,74 @@ ${e.stack}`);
3192
3205
  };
3193
3206
  var module_default = moduleRouteHandler;
3194
3207
 
3208
+ // src/routes/moduleFieldsJson.ts
3209
+ import path9 from "path";
3210
+ import { normalizePath as normalizePath6 } from "vite";
3211
+
3212
+ // src/lib/renderModuleFieldsJson.ts
3213
+ import { join as joinPosix4 } from "path/posix";
3214
+ var lookForModuleInFolder3 = async (modulePath, viteServer) => {
3215
+ let componentModule;
3216
+ const insideFolderPath = joinPosix4(modulePath, "index");
3217
+ try {
3218
+ componentModule = await viteServer.ssrLoadModule(insideFolderPath);
3219
+ } catch (e) {
3220
+ if (!e.message.includes("Failed to load url")) {
3221
+ throw e;
3222
+ }
3223
+ }
3224
+ return [componentModule, insideFolderPath];
3225
+ };
3226
+ async function renderModuleFieldsJson(viteServer, requestedModulePath) {
3227
+ let componentModule;
3228
+ try {
3229
+ if (!hasComponentExtension(requestedModulePath)) {
3230
+ [componentModule] = await lookForModuleInFolder3(
3231
+ requestedModulePath,
3232
+ viteServer
3233
+ );
3234
+ }
3235
+ if (!componentModule) {
3236
+ componentModule = await viteServer.ssrLoadModule(requestedModulePath);
3237
+ }
3238
+ } catch (error) {
3239
+ throw new Error(
3240
+ `Failed to load module ${requestedModulePath}: ${error.message}`
3241
+ );
3242
+ }
3243
+ if (!componentModule) {
3244
+ throw new Error(`Couldn't find module: ${requestedModulePath}`);
3245
+ }
3246
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
3247
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
3248
+ const fieldsJson = renderFieldsToJson(
3249
+ componentModule.fields,
3250
+ requestedModulePath
3251
+ );
3252
+ return fieldsJson;
3253
+ }
3254
+ var renderModuleFieldsJson_default = renderModuleFieldsJson;
3255
+
3256
+ // src/routes/moduleFieldsJson.ts
3257
+ var moduleFieldsJsonRouteHandler = async (request2, response) => {
3258
+ try {
3259
+ sendTrackingRequest("fields-json-route");
3260
+ const { webRoot, viteServer } = request2.app.locals;
3261
+ const { moduleName } = request2.params;
3262
+ const modulePath = normalizePath6(
3263
+ path9.resolve(webRoot, "components/modules/", moduleName)
3264
+ );
3265
+ const fieldsJson = await renderModuleFieldsJson_default(viteServer, modulePath);
3266
+ return response.status(200).set({ "Content-Type": "application/json" }).json(fieldsJson);
3267
+ } catch (error) {
3268
+ console.error("Error processing module fields.json:", error);
3269
+ return response.status(500).json({
3270
+ error: "Failed to process module fields"
3271
+ });
3272
+ }
3273
+ };
3274
+ var moduleFieldsJson_default = moduleFieldsJsonRouteHandler;
3275
+
3195
3276
  // src/proxyPage/fetchContentMetadata.ts
3196
3277
  import http from "http";
3197
3278
  import https from "https";
@@ -3405,16 +3486,20 @@ async function fetchPreviewTemplates(accountId, previewToken) {
3405
3486
  url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}`
3406
3487
  })).data;
3407
3488
  }
3408
- async function fetchModuleByPath(accountId, path13) {
3489
+ async function fetchModuleByPath(accountId, path15) {
3409
3490
  return (await hsCliHttp8.get(accountId, {
3410
- url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path13}?portalId=${accountId}`
3491
+ url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path15}?portalId=${accountId}`
3411
3492
  })).data;
3412
3493
  }
3413
- async function fetchTemplateByPath(accountId, path13) {
3494
+ async function fetchTemplateByPath(accountId, path15) {
3414
3495
  return (await hsCliHttp8.get(accountId, {
3415
- url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path13}?portalId=${accountId}`
3496
+ url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path15}?portalId=${accountId}`
3416
3497
  })).data;
3417
3498
  }
3499
+ async function fetchModulePageDependencies(accountId, path15) {
3500
+ const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path15}`;
3501
+ return (await hsCliHttp8.get(accountId, { url: url3 })).data;
3502
+ }
3418
3503
 
3419
3504
  // src/components/HubLTemplatesList.tsx
3420
3505
  import { jsx as jsx7, jsxs as jsxs3 } from "react/jsx-runtime";
@@ -3654,8 +3739,8 @@ function proxyServerlessRequest(req, res, next) {
3654
3739
  }
3655
3740
 
3656
3741
  // src/routes/modulePreviewRouteHandler.ts
3657
- import path9 from "path";
3658
- import { normalizePath as normalizePath6 } from "vite";
3742
+ import path10 from "path";
3743
+ import { normalizePath as normalizePath7 } from "vite";
3659
3744
  async function modulePreviewRouteHandler(request2, response) {
3660
3745
  sendTrackingRequest("view-module-preview-route");
3661
3746
  const {
@@ -3669,9 +3754,46 @@ async function modulePreviewRouteHandler(request2, response) {
3669
3754
  projectComponentPath
3670
3755
  } = request2.app.locals;
3671
3756
  const moduleName = request2.params.moduleName;
3672
- const modulePath = normalizePath6(
3673
- path9.resolve(webRoot, "components/modules/", moduleName)
3757
+ const modulePath = normalizePath7(
3758
+ path10.resolve(webRoot, "components/modules/", moduleName)
3674
3759
  );
3760
+ const PREVIEWER_APP_PARAM = "hsPreviewerApp";
3761
+ let fieldOverrides = {};
3762
+ if (request2.method === "POST" && request2.body) {
3763
+ if (request2.query[PREVIEWER_APP_PARAM] === "module" && request2.body.module_data) {
3764
+ fieldOverrides = request2.body.module_data;
3765
+ } else {
3766
+ fieldOverrides = request2.body;
3767
+ }
3768
+ try {
3769
+ if (typeof fieldOverrides === "string") {
3770
+ const parsedFieldOverrides = JSON.parse(fieldOverrides);
3771
+ if (parsedFieldOverrides && typeof parsedFieldOverrides === "object" && !Array.isArray(parsedFieldOverrides)) {
3772
+ fieldOverrides = parsedFieldOverrides;
3773
+ } else {
3774
+ throw new Error("Parsed field overrides must be an object");
3775
+ }
3776
+ }
3777
+ } catch (e) {
3778
+ console.error(
3779
+ `Error parsing field for module "${moduleName}": ${e.message}`,
3780
+ "\nReceived value:",
3781
+ fieldOverrides
3782
+ );
3783
+ }
3784
+ } else if (request2.query.fields) {
3785
+ try {
3786
+ if (typeof request2.query.fields === "string") {
3787
+ fieldOverrides = JSON.parse(
3788
+ decodeURIComponent(request2.query.fields.replace(/\+/g, "%20"))
3789
+ );
3790
+ }
3791
+ } catch (e) {
3792
+ console.error(
3793
+ `Error parsing field param for module ${moduleName}: ${request2.query.fields}`
3794
+ );
3795
+ }
3796
+ }
3675
3797
  try {
3676
3798
  const {
3677
3799
  html: renderedHtml,
@@ -3689,7 +3811,8 @@ async function modulePreviewRouteHandler(request2, response) {
3689
3811
  projectName,
3690
3812
  projectComponentPath,
3691
3813
  fullOriginalUrlFromRequest(request2),
3692
- request2.get("COOKIE")
3814
+ request2.get("COOKIE"),
3815
+ fieldOverrides
3693
3816
  );
3694
3817
  const baseTemplatePath = packagePath(
3695
3818
  import.meta.url,
@@ -3885,6 +4008,7 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
3885
4008
  );
3886
4009
  }
3887
4010
  devServerApp.use(viteServer.middlewares);
4011
+ devServerApp.use(urlencoded());
3888
4012
  devServerApp.get("/proxy", proxyPathPageRouteHandler);
3889
4013
  devServerApp.get("/partials/", linksToAllPartialsRouteHandler_default);
3890
4014
  devServerApp.get("/partial/:partial", partial_default);
@@ -3893,7 +4017,12 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
3893
4017
  devServerApp.get("/preview/module/:moduleName", modulePreviewRouteHandler_default);
3894
4018
  devServerApp.get("/modules/", linksToAllModulesRouteHandler_default);
3895
4019
  devServerApp.get("/module/:moduleName", module_default);
4020
+ devServerApp.get(
4021
+ "/preview/module/:moduleName/fields.json",
4022
+ moduleFieldsJson_default
4023
+ );
3896
4024
  devServerApp.get("/module/:moduleName/*", module_default);
4025
+ devServerApp.post("/preview/module/:moduleName", modulePreviewRouteHandler_default);
3897
4026
  devServerApp.get("/hublmodule/:modulePath(*)", hublModuleRouteHandler);
3898
4027
  devServerApp.get("/template/:templatePath(*)", templateRouteHandler);
3899
4028
  devServerApp.all("/hs/serverless/*", proxyServerlessRequest);
@@ -3973,7 +4102,9 @@ function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
3973
4102
  environmentConfig,
3974
4103
  gates
3975
4104
  );
3976
- const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
4105
+ const localRenderPlaceholders = findLocalRenderPlaceholders(
4106
+ pageHtml.data
4107
+ );
3977
4108
  if (localRenderPlaceholders.length) {
3978
4109
  hasJSBuildingBlocks = true;
3979
4110
  localProxyUrl = `http://${hostName}.hslocal.net:${devServerPort}${pathName}`;
@@ -4049,25 +4180,67 @@ import { createServer as createViteServer2 } from "vite";
4049
4180
  import { default as react2 } from "@vitejs/plugin-react";
4050
4181
 
4051
4182
  // src/lib/getDevServerUIData.ts
4052
- async function getDevServerUIData(reqLocals) {
4053
- const { themeWebRoot, authedPortalId, projectName, localPreviewToken } = reqLocals;
4054
- const { moduleNames } = findAllModulesInRoot(themeWebRoot);
4055
- const { partialNames } = findAllPartialsInRoot(themeWebRoot);
4056
- const hubLModuleData = await fetchHubLModules(
4057
- authedPortalId,
4058
- localPreviewToken
4183
+ import path11 from "path";
4184
+ import { normalizePath as normalizePath8 } from "vite";
4185
+ function mapModulesData(modules, themeWebRoot, viteServer) {
4186
+ return Promise.all(
4187
+ modules.moduleNames.map(async (name, index) => {
4188
+ const modulePath = normalizePath8(
4189
+ path11.resolve(themeWebRoot, "components/modules/", name)
4190
+ );
4191
+ const fieldsJson = await renderModuleFieldsJson_default(viteServer, modulePath);
4192
+ return {
4193
+ name,
4194
+ subPath: modules.moduleSubpaths[index],
4195
+ nameWithExtension: modules.moduleNamesWithExtension[index],
4196
+ fieldsJson
4197
+ };
4198
+ })
4059
4199
  );
4060
- const hubLTemplateData = await fetchPreviewTemplates(
4200
+ }
4201
+ function mapPartialsData(modules) {
4202
+ return modules.partialNames.map((name, index) => ({
4203
+ name,
4204
+ subPath: modules.partialSubpaths[index]
4205
+ }));
4206
+ }
4207
+ async function getDevServerUIData(reqLocals) {
4208
+ const {
4209
+ themeWebRoot,
4061
4210
  authedPortalId,
4062
- localPreviewToken
4211
+ projectName,
4212
+ localPreviewToken,
4213
+ webRootProjectComponentFolder,
4214
+ viteServer
4215
+ } = reqLocals;
4216
+ const modulesData = findAllModulesInRoot(themeWebRoot);
4217
+ const partialsData = findAllPartialsInRoot(themeWebRoot);
4218
+ const mappedModulesData = await mapModulesData(
4219
+ modulesData,
4220
+ themeWebRoot,
4221
+ viteServer
4063
4222
  );
4223
+ let hubLModuleData = { objects: [] };
4224
+ let hubLTemplateData = { objects: [] };
4225
+ if (authedPortalId) {
4226
+ hubLModuleData = await fetchHubLModules(authedPortalId, localPreviewToken);
4227
+ hubLTemplateData = await fetchPreviewTemplates(
4228
+ authedPortalId,
4229
+ localPreviewToken
4230
+ );
4231
+ }
4232
+ const hubLTemplates = (hubLTemplateData == null ? void 0 : hubLTemplateData.objects.filter(
4233
+ (template) => isCodedFile(template.filename)
4234
+ )) || [];
4064
4235
  return {
4065
4236
  authedPortalId,
4066
4237
  projectName,
4067
- moduleNames,
4068
- partialNames,
4238
+ modulesData: mappedModulesData,
4239
+ partialsData: mapPartialsData(partialsData),
4069
4240
  hubLModules: (hubLModuleData == null ? void 0 : hubLModuleData.objects) || [],
4070
- hubLTemplates: (hubLTemplateData == null ? void 0 : hubLTemplateData.objects) || []
4241
+ hubLTemplates,
4242
+ themeWebRoot,
4243
+ webRootProjectComponentFolder
4071
4244
  };
4072
4245
  }
4073
4246
  var getDevServerUIData_default = getDevServerUIData;
@@ -4080,7 +4253,11 @@ async function createAppServer(webRoot, reqLocals, port) {
4080
4253
  server: {
4081
4254
  middlewareMode: true,
4082
4255
  host: "hslocal.net",
4083
- origin
4256
+ origin,
4257
+ hmr: {
4258
+ port: port + 1,
4259
+ host: "hslocal.net"
4260
+ }
4084
4261
  },
4085
4262
  appType: "custom",
4086
4263
  root: webRoot,
@@ -4118,20 +4295,38 @@ async function createAppServer(webRoot, reqLocals, port) {
4118
4295
  };
4119
4296
  const viteServer = await createViteServer2(viteConfig);
4120
4297
  app.use(viteServer.middlewares);
4298
+ app.get("/api/module-pages", async (req, res, next) => {
4299
+ const { path: path15, portalId } = req.query;
4300
+ if (!path15 || !portalId) {
4301
+ return res.status(400).json({ error: "Missing required parameters" });
4302
+ }
4303
+ try {
4304
+ const data = await fetchModulePageDependencies(
4305
+ Number(portalId),
4306
+ path15
4307
+ );
4308
+ res.json(data);
4309
+ } catch (err) {
4310
+ next(err);
4311
+ }
4312
+ });
4121
4313
  app.use("*", async (req, res) => {
4122
4314
  try {
4123
- const inititialProps = await getDevServerUIData_default(reqLocals);
4315
+ const initialProps = await getDevServerUIData_default({
4316
+ ...reqLocals,
4317
+ viteServer
4318
+ });
4124
4319
  const url3 = req.originalUrl.replace("/", "");
4125
- let template = await fs3.readFile("./app/index.html", "utf-8");
4320
+ let template = await fs3.readFile(`${webRoot}/index.html`, "utf-8");
4126
4321
  template = await viteServer.transformIndexHtml(url3, template);
4127
4322
  const { render } = await viteServer.ssrLoadModule(
4128
- "./app/serverEntry.tsx"
4323
+ `${webRoot}/serverEntry.tsx`
4129
4324
  );
4130
- const rendered = await render(inititialProps);
4325
+ const rendered = await render(initialProps);
4131
4326
  const html = template.replace(`<!--app-head-->`, rendered.head ?? "").replace(`<!--app-html-->`, rendered.html ?? "").replace(
4132
4327
  `<!--app-script-->`,
4133
4328
  `<script>window.__hsInitialProps = ${JSON.stringify(
4134
- inititialProps
4329
+ initialProps
4135
4330
  )}</script>` ?? ""
4136
4331
  );
4137
4332
  res.status(200).set({ "Content-Type": "text/html" }).send(html);
@@ -4141,6 +4336,10 @@ async function createAppServer(webRoot, reqLocals, port) {
4141
4336
  res.status(500).end(e.stack);
4142
4337
  }
4143
4338
  });
4339
+ app.use((err, req, res, next) => {
4340
+ console.error("API Error:", err);
4341
+ res.status(500).json({ error: "Internal server error" });
4342
+ });
4144
4343
  app.listen(port, () => {
4145
4344
  console.log(`Server started at http://localhost:${port}`);
4146
4345
  });
@@ -4307,7 +4506,7 @@ async function fetchWebsiteDomainNames(portalId) {
4307
4506
  }
4308
4507
 
4309
4508
  // src/lib/validateHSPlatform.ts
4310
- import path10 from "path";
4509
+ import path12 from "path";
4311
4510
  import fs4 from "fs";
4312
4511
  import select from "@inquirer/select";
4313
4512
  import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
@@ -4319,12 +4518,12 @@ function findHSProjectJson(startPath) {
4319
4518
  let currentDir = startPath;
4320
4519
  let dirLevel = 0;
4321
4520
  const maxDirLevel = 4;
4322
- while (path10.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
4323
- const filePath = path10.join(currentDir, HSPROJECT_JSON);
4521
+ while (path12.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
4522
+ const filePath = path12.join(currentDir, HSPROJECT_JSON);
4324
4523
  if (checkFileExists(filePath)) {
4325
4524
  return filePath;
4326
4525
  }
4327
- currentDir = path10.dirname(currentDir);
4526
+ currentDir = path12.dirname(currentDir);
4328
4527
  dirLevel++;
4329
4528
  }
4330
4529
  console.log(
@@ -4630,7 +4829,7 @@ function writeFieldsType(fields, fileName, typeName) {
4630
4829
 
4631
4830
  // src/lib/watchFieldsUpdates.ts
4632
4831
  import fs5 from "fs";
4633
- import path11 from "path";
4832
+ import path13 from "path";
4634
4833
  import readline from "readline";
4635
4834
  var lastSerializedFieldsCache = {};
4636
4835
  var formatAsTypeName = (str) => {
@@ -4642,9 +4841,9 @@ var isInModulesFolder = (filePath, projectRoot) => {
4642
4841
  const getEntryPathFromId = (id) => {
4643
4842
  return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
4644
4843
  };
4645
- const currentModuleId = path11.normalize(filePath);
4844
+ const currentModuleId = path13.normalize(filePath);
4646
4845
  const moduleEntryPath = getEntryPathFromId(currentModuleId);
4647
- const subFolderTokens = moduleEntryPath.split(path11.sep);
4846
+ const subFolderTokens = moduleEntryPath.split(path13.sep);
4648
4847
  return {
4649
4848
  inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
4650
4849
  isRootModuleFile: subFolderTokens.length === 3
@@ -4671,10 +4870,10 @@ var getIndexFile = (filePath, projectRoot) => {
4671
4870
  return void 0;
4672
4871
  if (isRootModuleFile)
4673
4872
  return { indexFilePath: filePath, isRootModuleFile };
4674
- const dir = path11.dirname(filePath);
4873
+ const dir = path13.dirname(filePath);
4675
4874
  const files = fs5.readdirSync(dir);
4676
4875
  const indexFileName = files.find((file) => file.startsWith("index."));
4677
- return indexFileName ? { indexFilePath: path11.join(dir, indexFileName), isRootModuleFile } : void 0;
4876
+ return indexFileName ? { indexFilePath: path13.join(dir, indexFileName), isRootModuleFile } : void 0;
4678
4877
  };
4679
4878
  var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
4680
4879
  let indexFile;
@@ -4698,7 +4897,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
4698
4897
  if (!indexInfo)
4699
4898
  return;
4700
4899
  const { indexFilePath, isRootModuleFile } = indexInfo;
4701
- const indexFileName = path11.parse(indexFilePath).name;
4900
+ const indexFileName = path13.parse(indexFilePath).name;
4702
4901
  const isTypeFile = filePath.endsWith(".types.ts");
4703
4902
  if (isTypeFile)
4704
4903
  return;
@@ -4709,7 +4908,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
4709
4908
  );
4710
4909
  if (fields) {
4711
4910
  const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
4712
- const typeFilePath = path11.join(path11.dirname(filePath), typeFileName);
4911
+ const typeFilePath = path13.join(path13.dirname(filePath), typeFileName);
4713
4912
  const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
4714
4913
  const serializedFields = JSON.stringify(fields);
4715
4914
  if (lastSerializedFields === serializedFields)
@@ -4717,7 +4916,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
4717
4916
  const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
4718
4917
  if (!hasAutoGenComment)
4719
4918
  return;
4720
- const moduleFolderName = path11.basename(path11.dirname(filePath));
4919
+ const moduleFolderName = path13.basename(path13.dirname(filePath));
4721
4920
  const outputTypeName = formatAsTypeName(moduleFolderName);
4722
4921
  const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
4723
4922
  if (didSucceed) {
@@ -4733,7 +4932,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
4733
4932
  var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
4734
4933
  const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
4735
4934
  moduleSubpaths.forEach((modulePath) => {
4736
- const resolvedPath = path11.resolve(projectRoot, modulePath);
4935
+ const resolvedPath = path13.resolve(projectRoot, modulePath);
4737
4936
  maybeUpdateFields(resolvedPath, viteServer, projectRoot);
4738
4937
  });
4739
4938
  const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
@@ -4871,7 +5070,7 @@ Local proxy functionality and module preview routes will not work without settin
4871
5070
  } catch (e) {
4872
5071
  authedHublet = "na1";
4873
5072
  }
4874
- const absoluteWebRoot = normalizePath7(path12.resolve(process.cwd(), webRoot));
5073
+ const absoluteWebRoot = normalizePath9(path14.resolve(process.cwd(), webRoot));
4875
5074
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
4876
5075
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
4877
5076
  if (authedPortalId) {
@@ -4963,8 +5162,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
4963
5162
  `
4964
5163
  );
4965
5164
  if (showUI) {
4966
- const appWebRoot = path12.join(
4967
- path12.dirname(url2.fileURLToPath(import.meta.url)),
5165
+ const appWebRoot = path14.join(
5166
+ path14.dirname(url2.fileURLToPath(import.meta.url)),
4968
5167
  "../app"
4969
5168
  );
4970
5169
  const reqLocals = {
@@ -4980,8 +5179,8 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
4980
5179
  httpServers.push(appServer);
4981
5180
  }
4982
5181
  if (storybook) {
4983
- const packageRoot = path12.dirname(url2.fileURLToPath(import.meta.url));
4984
- const configPath = path12.resolve(packageRoot, "./storybook-main");
5182
+ const packageRoot = path14.dirname(url2.fileURLToPath(import.meta.url));
5183
+ const configPath = path14.resolve(packageRoot, "./storybook-main");
4985
5184
  sendTrackingRequest("start-storybook");
4986
5185
  const storybookProcess = spawn(
4987
5186
  "sb",
@@ -5001,7 +5200,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
5001
5200
  portalId: authedPortalId.toString(),
5002
5201
  hsEnv: authedEnv,
5003
5202
  hublet: authedHublet,
5004
- WEB_ROOT: path12.join(webRoot, "components")
5203
+ WEB_ROOT: path14.join(webRoot, "components")
5005
5204
  }
5006
5205
  }
5007
5206
  );