@hubspot/cms-dev-server 1.2.79 → 1.2.82

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
@@ -842,8 +842,8 @@ async function buildThemePreviewOptions(webRoot2, isUsingLocalWorkspace = false)
842
842
  }
843
843
 
844
844
  // src/createDevServer.ts
845
- import path18 from "path";
846
- import fs10 from "fs";
845
+ import path20 from "path";
846
+ import fs12 from "fs";
847
847
  import url2 from "url";
848
848
  import express2 from "express";
849
849
  import http3 from "http";
@@ -896,7 +896,7 @@ function packagePath(metaUrl, projectPath) {
896
896
  );
897
897
  }
898
898
 
899
- // ../cms-js-internal/dist/types-Dvw_fW6p.js
899
+ // ../cms-js-internal/dist/types-C8bPIEz4.js
900
900
  import path4 from "path";
901
901
  import { createHash } from "crypto";
902
902
  import fs3, { readFileSync, existsSync as existsSync2, readdirSync, lstatSync } from "fs";
@@ -1155,12 +1155,8 @@ function isLocalUiDisabled(config) {
1155
1155
  return false;
1156
1156
  }
1157
1157
  var ENABLED_FEATURES_GATE_MAP = {
1158
- "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules",
1159
- "PortalsAccessIdentity:DesignManager:UrlSigning": "PortalsAccessIdentity:DesignManager:UrlSigning"
1158
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
1160
1159
  };
1161
- function isUngatedFor(gates, gate) {
1162
- return gates.includes(gate);
1163
- }
1164
1160
  var findAllComponentsIn = (webRoot2, componentsFolder) => {
1165
1161
  const fullComponentsFolderPath = join2(webRoot2, componentsFolder);
1166
1162
  const componentsByName = {};
@@ -1579,8 +1575,8 @@ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap)
1579
1575
  );
1580
1576
  return Object.fromEntries(relativeEntries);
1581
1577
  }
1582
- function toRelativePath(config, path19) {
1583
- return path19.replace(`${config.root}/`, "");
1578
+ function toRelativePath(config, path21) {
1579
+ return path21.replace(`${config.root}/`, "");
1584
1580
  }
1585
1581
  function shouldAnalyzeModule(config, moduleInfo, code) {
1586
1582
  const [fileId, __] = moduleInfo.id.split("?");
@@ -1623,11 +1619,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1623
1619
  let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
1624
1620
  let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
1625
1621
  traverse(sourceAst, {
1626
- ImportDeclaration(path19) {
1627
- if (t.isStringLiteral(path19.node.source, {
1622
+ ImportDeclaration(path21) {
1623
+ if (t.isStringLiteral(path21.node.source, {
1628
1624
  value: "@hubspot/cms-components"
1629
1625
  })) {
1630
- for (const specifier of path19.node.specifiers) {
1626
+ for (const specifier of path21.node.specifiers) {
1631
1627
  if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
1632
1628
  name: CMS_MODULE_COMPONENT_NAME
1633
1629
  })) {
@@ -1641,14 +1637,14 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1641
1637
  }
1642
1638
  }
1643
1639
  },
1644
- JSXOpeningElement(path19) {
1645
- if (t.isJSXIdentifier(path19.node.name, {
1640
+ JSXOpeningElement(path21) {
1641
+ if (t.isJSXIdentifier(path21.node.name, {
1646
1642
  name: moduleComponentLocalImportName
1647
1643
  })) {
1648
1644
  let cmsModuleName;
1649
1645
  let cmsModulePath;
1650
1646
  let cmsModuleLabel;
1651
- for (const prop of path19.node.attributes) {
1647
+ for (const prop of path21.node.attributes) {
1652
1648
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
1653
1649
  cmsModuleName = prop.value.value;
1654
1650
  continue;
@@ -1683,11 +1679,11 @@ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1683
1679
  }
1684
1680
  contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
1685
1681
  }
1686
- if (t.isJSXIdentifier(path19.node.name, {
1682
+ if (t.isJSXIdentifier(path21.node.name, {
1687
1683
  name: dndAreaComponentLocalImportName
1688
1684
  })) {
1689
1685
  let dndAreaName;
1690
- for (const prop of path19.node.attributes) {
1686
+ for (const prop of path21.node.attributes) {
1691
1687
  if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
1692
1688
  dndAreaName = prop.value.value;
1693
1689
  continue;
@@ -2262,7 +2258,7 @@ function trackUsage(action) {
2262
2258
  eventName: EVENT_NAME,
2263
2259
  action,
2264
2260
  nodeVersion: getNodeVersionData(),
2265
- version: "1.2.79",
2261
+ version: "1.2.82",
2266
2262
  os: getPlatform()
2267
2263
  };
2268
2264
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -2336,12 +2332,12 @@ var findLocalRenderPlaceholders = (body) => {
2336
2332
  );
2337
2333
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
2338
2334
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
2339
- const path19 = body.substring(
2335
+ const path21 = body.substring(
2340
2336
  startOffset + localJsRenderStartString.length,
2341
2337
  pathEndOffset
2342
2338
  );
2343
2339
  offsetSoFar = pathEndOffset + 1;
2344
- if (startOffset >= 0 && path19) {
2340
+ if (startOffset >= 0 && path21) {
2345
2341
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
2346
2342
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
2347
2343
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -2366,7 +2362,7 @@ var findLocalRenderPlaceholders = (body) => {
2366
2362
  result.push({
2367
2363
  startOffset,
2368
2364
  endOffset: endOffset + localJsRenderEndString.length,
2369
- path: path19,
2365
+ path: path21,
2370
2366
  json
2371
2367
  });
2372
2368
  }
@@ -2765,9 +2761,9 @@ var customColors = [
2765
2761
  ];
2766
2762
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
2767
2763
  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;`;
2768
- var renderLocalError_default = (path19, error) => {
2764
+ var renderLocalError_default = (path21, error) => {
2769
2765
  const stackWithColorClasses = Converter.toHtml(error.stack);
2770
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path19}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2766
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path21}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2771
2767
  };
2772
2768
 
2773
2769
  // src/proxyPage/fetchPreviewInfo.ts
@@ -3790,7 +3786,6 @@ function getWebDefaultStylesCss(metaUrl) {
3790
3786
  }
3791
3787
  return _webDefaultStylesCss;
3792
3788
  }
3793
- var URL_SIGNING_GATE = "PortalsAccessIdentity:DesignManager:UrlSigning";
3794
3789
  async function signGetUrl(authedPortalId, unsignedUrl) {
3795
3790
  const urlWithPortalId = new URL(unsignedUrl);
3796
3791
  urlWithPortalId.searchParams.set("portalId", `${authedPortalId}`);
@@ -3807,14 +3802,7 @@ async function signGetUrl(authedPortalId, unsignedUrl) {
3807
3802
  });
3808
3803
  return response.data.signedUrl;
3809
3804
  }
3810
- async function signedGet(authedPortalId, unsignedUrl, headers, gates) {
3811
- if (!isUngatedFor(gates, URL_SIGNING_GATE)) {
3812
- const { data } = await hsCliHttp7.get(authedPortalId, {
3813
- url: unsignedUrl,
3814
- headers
3815
- });
3816
- return data;
3817
- }
3805
+ async function signedGet(authedPortalId, unsignedUrl, headers) {
3818
3806
  const signedUrl = await signGetUrl(authedPortalId, unsignedUrl);
3819
3807
  const accountConfig = getConfigAccountIfExists5(authedPortalId);
3820
3808
  const authHeaders = {};
@@ -3841,7 +3829,7 @@ async function signedGet(authedPortalId, unsignedUrl, headers, gates) {
3841
3829
  }
3842
3830
  return await response.text();
3843
3831
  }
3844
- async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue, gates) {
3832
+ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue) {
3845
3833
  const moduleInfoQueryParams = new URLSearchParams({
3846
3834
  portalId: `${authedPortalId}`
3847
3835
  });
@@ -3865,34 +3853,13 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
3865
3853
  buffer_theme: `${true}`
3866
3854
  });
3867
3855
  const cosRenderingUrl = `https://api.hubspot${authedEnv === "qa" ? "qa" : ""}.com/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`;
3868
- const previousHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
3869
- const needsDomainOverride = !isUngatedFor(gates, URL_SIGNING_GATE);
3870
- if (needsDomainOverride) {
3871
- process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
3872
- }
3873
- let modulePreviewHtml;
3874
- try {
3875
- modulePreviewHtml = await signedGet(
3876
- authedPortalId,
3877
- cosRenderingUrl,
3878
- {
3879
- ["content-type"]: "application/x-www-form-urlencoded",
3880
- ["Accept"]: "text/html",
3881
- referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
3882
- cookie: cookieValue,
3883
- "User-Agent": "HubSpot CMS Dev Server"
3884
- },
3885
- gates
3886
- );
3887
- } finally {
3888
- if (needsDomainOverride) {
3889
- if (previousHubApiDomainOverride) {
3890
- process.env.HUBAPI_DOMAIN_OVERRIDE = previousHubApiDomainOverride;
3891
- } else {
3892
- delete process.env.HUBAPI_DOMAIN_OVERRIDE;
3893
- }
3894
- }
3895
- }
3856
+ const modulePreviewHtml = await signedGet(authedPortalId, cosRenderingUrl, {
3857
+ ["content-type"]: "application/x-www-form-urlencoded",
3858
+ ["Accept"]: "text/html",
3859
+ referer: `https://app.hubspot${authedEnv === "qa" ? "qa" : ""}.com`,
3860
+ cookie: cookieValue,
3861
+ "User-Agent": "HubSpot CMS Dev Server"
3862
+ });
3896
3863
  const previewDoc = parseHtml(modulePreviewHtml);
3897
3864
  const modulePreviewContent = extractModuleOuterHtml(previewDoc);
3898
3865
  const allStyleContent = extractStyleText(previewDoc);
@@ -4133,8 +4100,7 @@ var partialRouteHandler = async (request, response) => {
4133
4100
  remoteModule.path,
4134
4101
  authedPortalId,
4135
4102
  authedEnv,
4136
- request.get("COOKIE"),
4137
- jsRenderingGates
4103
+ request.get("COOKIE")
4138
4104
  ).then((result) => ({
4139
4105
  remoteModule,
4140
4106
  result
@@ -4458,142 +4424,723 @@ var moduleFieldsJsonRouteHandler = async (request, response) => {
4458
4424
  };
4459
4425
  var moduleFieldsJson_default = moduleFieldsJsonRouteHandler;
4460
4426
 
4461
- // src/proxyPage/fetchContentMetadata.ts
4462
- import http from "http";
4463
- import https from "https";
4464
- import { getConfigAccountIfExists as getConfigAccountIfExists6 } from "@hubspot/local-dev-lib/config";
4465
- async function requestPage(url3, redirects = 0, originalUrl) {
4466
- if (redirects > 5) {
4467
- throw new Error(
4468
- `Hit too many redirects to HEAD requests for ${originalUrl}`
4469
- );
4427
+ // src/routes/moduleValidateFields.ts
4428
+ import path14 from "path";
4429
+ import fs8 from "fs/promises";
4430
+
4431
+ // src/validateFields.ts
4432
+ import path13 from "path";
4433
+ import fs7 from "fs/promises";
4434
+
4435
+ // ../cms-js-internal/dist/buildFieldsTypes.js
4436
+ import { writeFileSync } from "fs";
4437
+ import ts from "typescript";
4438
+ var fieldTypeNameByType = {
4439
+ alignment: "AlignmentFieldType",
4440
+ audioplayer: "AudioFieldType",
4441
+ backgroundimage: "BackgroundImageFieldType",
4442
+ blog: "BlogFieldType",
4443
+ boolean: "BooleanFieldType",
4444
+ border: "BorderFieldType",
4445
+ choice: "ChoiceFieldType",
4446
+ color: "ColorFieldType",
4447
+ crmobject: "CrmObjectFieldType",
4448
+ cta: "CtaFieldType",
4449
+ date: "DateFieldType",
4450
+ datetime: "DateTimeFieldType",
4451
+ email: "EmailFieldType",
4452
+ embed: "EmbedFieldType",
4453
+ file: "FileFieldType",
4454
+ followupemail: "FollowUpEmailFieldType",
4455
+ font: "FontFieldType",
4456
+ form: "FormFieldType",
4457
+ gradient: "GradientFieldType",
4458
+ group: "GroupFieldType",
4459
+ html: "HtmlFieldType",
4460
+ hubdbrow: "HubDbRowFieldType",
4461
+ hubdbtable: "HubDbTableFieldType",
4462
+ hubl: "HublFieldType",
4463
+ icon: "IconFieldType",
4464
+ image: "ImageFieldType",
4465
+ link: "LinkFieldType",
4466
+ logo: "LogoFieldType",
4467
+ meeting: "MeetingFieldType",
4468
+ menu: "MenuFieldType",
4469
+ number: "NumberFieldType",
4470
+ page: "PageFieldType",
4471
+ payment: "PaymentFieldType",
4472
+ podcast: "PodcastFieldType",
4473
+ richtext: "RichTextFieldType",
4474
+ salesforcecampaign: "SfdcCamapaignFieldType",
4475
+ simplemenu: "SimpleMenuFieldType",
4476
+ spacing: "SpacingFieldType",
4477
+ survey: "SurveyFieldType",
4478
+ tag: "TagFieldType",
4479
+ textalignment: "TextAlignmentFieldType",
4480
+ text: "TextFieldType",
4481
+ url: "UrlFieldType",
4482
+ variantselection: "VariantSelectionFieldType",
4483
+ videoplayer: "VideoFieldType",
4484
+ workflow: "WorkflowFieldType"
4485
+ };
4486
+ function getFieldEntries(fields) {
4487
+ if (!Array.isArray(fields)) {
4488
+ return void 0;
4470
4489
  }
4471
- return new Promise((resolve3, reject) => {
4472
- const protocolAPI = url3.startsWith("https://") ? https : http;
4473
- protocolAPI.request(
4474
- url3,
4475
- {
4476
- method: "HEAD",
4477
- headers: {
4478
- // Keep this user agent, so we don't get 403s from the request
4479
- ["User-Agent"]: "cms-dev-server"
4480
- }
4481
- },
4482
- async (res) => {
4483
- let portalIdHeader;
4484
- let contentId;
4485
- const isContentMembershipRedirect = Boolean(
4486
- res.headers["x-hs-content-membership-redirect"]
4487
- );
4488
- if (isContentMembershipRedirect) {
4489
- debug("Content Membership Redirect", res.headers);
4490
- portalIdHeader = res.headers["x-hs-portal-id"];
4491
- contentId = res.headers["x-hs-content-id"];
4492
- if (portalIdHeader && contentId) {
4493
- return resolve3({
4494
- portalIdHeader,
4495
- contentId,
4496
- res
4497
- });
4498
- }
4499
- }
4500
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
4501
- console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
4502
- return resolve3(
4503
- requestPage(
4504
- res.headers.location,
4505
- redirects + 1,
4506
- originalUrl ?? url3
4507
- )
4508
- );
4509
- }
4510
- portalIdHeader = res.headers["x-hs-hub-id"];
4511
- contentId = res.headers["x-hs-content-id"];
4512
- return resolve3({
4513
- res,
4514
- portalIdHeader,
4515
- contentId
4516
- });
4517
- }
4518
- ).on("error", (err) => {
4519
- console.error(err);
4520
- reject(err);
4521
- }).end();
4522
- });
4523
- }
4524
- async function fetchContentMetadata(url3, portalId) {
4525
- const { portalIdHeader, contentId, res } = await requestPage(url3);
4526
- if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
4527
- throw new Error(
4528
- `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
4529
- );
4530
- } else {
4531
- const portalIdFromResponse = parseInt(portalIdHeader, 10);
4532
- const pageAccount = await getConfigAccountIfExists6(portalIdFromResponse);
4533
- if (!pageAccount) {
4534
- throw new Error(
4535
- `No CLI auth for portal ${portalIdFromResponse} found, please run \`hs auth\``
4536
- );
4490
+ return fields.filter((field) => field.name && field.type).map((field) => {
4491
+ const { name, type } = field;
4492
+ const fieldType = fieldTypeNameByType[type];
4493
+ if (!fieldType) {
4494
+ return void 0;
4537
4495
  }
4538
- if (res.statusCode !== 200 && !(portalIdFromResponse && pageAccount && contentId)) {
4539
- throw new Error(
4540
- `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url3}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
4541
- );
4542
- } else if (!portalId || !contentId) {
4543
- throw new Error(
4544
- `Missing hub ID or content ID headers on HEAD request to ${url3}`
4545
- );
4546
- } else if (isNaN(portalId)) {
4547
- throw new Error(
4548
- `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
4549
- );
4496
+ const entry = {
4497
+ type: fieldType,
4498
+ name,
4499
+ isRepeater: "occurrence" in field,
4500
+ isRequired: !!field.required,
4501
+ choices: (
4502
+ // Choices are pair [value, label] but only the value is printed to the page, so flatten it.
4503
+ "choices" in field ? field.choices.map(([value, label]) => value) : void 0
4504
+ ),
4505
+ children: []
4506
+ };
4507
+ if (fieldType === "GroupFieldType" && "children" in field) {
4508
+ const children = getFieldEntries(field.children);
4509
+ return { ...entry, children };
4550
4510
  }
4551
- const hublet = "na1";
4552
- return { portalId, contentId, hublet };
4553
- }
4511
+ return entry;
4512
+ }).filter((entry) => entry !== void 0);
4554
4513
  }
4555
-
4556
- // src/routes/proxyPageRouteHandler.ts
4557
- async function proxyPageRouteHandler(request, response, next) {
4558
- sendTrackingRequest("view-proxy-page-route");
4559
- const {
4560
- viteServer,
4561
- webRoot: webRoot2,
4562
- projectName,
4563
- projectComponentPath,
4564
- jsRenderingGates
4565
- } = request.app.locals;
4566
- if (!request.accepts().includes("text/html")) {
4567
- return response.sendStatus(404);
4514
+ var INVALID_IMPORTS = ["ChoiceFieldType", "GroupFieldType"];
4515
+ var FIELD_GROUP_TYPE = "FieldGroupWithChildren";
4516
+ var REPEATER_GROUP_TYPE = "RepeaterGroup";
4517
+ var REQUIRED_TYPE = "RequiredField";
4518
+ var DEFAULT_VALUES_TYPE = "DefaultValues";
4519
+ var CMS_COMPONENTS = "@hubspot/cms-components";
4520
+ var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
4521
+ var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
4522
+ var createPropertySignature = (identifier, type, hasQuestionToken = false) => ts.factory.createPropertySignature(
4523
+ [],
4524
+ identifier,
4525
+ hasQuestionToken ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0,
4526
+ type
4527
+ );
4528
+ var createUnionTypeFromArray = (values) => ts.factory.createUnionTypeNode(
4529
+ values.map(
4530
+ (value) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value))
4531
+ )
4532
+ );
4533
+ var buildTypeFromField = (field, additionalNode) => {
4534
+ const imports = [field.type];
4535
+ const identifier = ts.factory.createIdentifier(field.name);
4536
+ const baseType = ts.factory.createTypeReferenceNode(field.type);
4537
+ const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
4538
+ baseType
4539
+ ]);
4540
+ let finalType = field.isRequired ? requiredType : baseType;
4541
+ if (field.choices) {
4542
+ finalType = createUnionTypeFromArray(field.choices);
4568
4543
  }
4569
- const fullOriginalUrl = fullOriginalUrlFromRequest(request);
4570
- const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);
4571
- const urlToProxy = `http://${domainToProxy}${request.originalUrl}`;
4572
- if (!domainToProxy) {
4573
- if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {
4574
- const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;
4575
- consoleWarn(message);
4576
- return response.status(400).send(message);
4577
- } else {
4578
- const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;
4579
- consoleWarn(message);
4580
- return response.status(400).send(message);
4581
- }
4544
+ if (field.isRequired) {
4545
+ imports.push(REQUIRED_TYPE);
4582
4546
  }
4583
- try {
4584
- const { portalId, contentId, hublet } = await fetchContentMetadata(
4585
- urlToProxy,
4586
- request.app.locals.authedPortalId
4587
- );
4588
- await proxySpecificPage(
4589
- request,
4590
- response,
4591
- portalId,
4592
- hublet,
4593
- contentId,
4594
- webRoot2,
4595
- viteServer,
4596
- projectName,
4547
+ if (additionalNode) {
4548
+ const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
4549
+ const genericType = field.isRepeater ? REPEATER_GROUP_TYPE : FIELD_GROUP_TYPE;
4550
+ imports.push(genericType);
4551
+ finalType = ts.factory.createTypeReferenceNode(genericType, [typeLiteral]);
4552
+ }
4553
+ return {
4554
+ type: createPropertySignature(
4555
+ identifier,
4556
+ finalType,
4557
+ !field.isRequired && !additionalNode
4558
+ ),
4559
+ imports
4560
+ };
4561
+ };
4562
+ var filterUnusedImports = (imports, type) => {
4563
+ const usedImports = /* @__PURE__ */ new Set();
4564
+ const visit = (node) => {
4565
+ if (ts.isTypeReferenceNode(node)) {
4566
+ const typeName = node.typeName;
4567
+ if ("escapedText" in typeName) {
4568
+ usedImports.add(typeName.escapedText.toString());
4569
+ }
4570
+ }
4571
+ ts.forEachChild(node, visit);
4572
+ };
4573
+ visit(type);
4574
+ return imports.filter((name) => usedImports.has(name));
4575
+ };
4576
+ function getImportDeclaration(imports, moduleSpecifier) {
4577
+ const importSpecifiers = Array.from(imports).map(
4578
+ (importName) => ts.factory.createImportSpecifier(
4579
+ true,
4580
+ void 0,
4581
+ ts.factory.createIdentifier(importName)
4582
+ )
4583
+ );
4584
+ const namedImports = ts.factory.createNamedImports(importSpecifiers);
4585
+ return ts.factory.createImportDeclaration(
4586
+ [],
4587
+ [],
4588
+ ts.factory.createImportClause(false, void 0, namedImports),
4589
+ ts.factory.createStringLiteral(moduleSpecifier)
4590
+ );
4591
+ }
4592
+ function getFieldTypes(fields) {
4593
+ const imports = [];
4594
+ const types = fields.map((field) => {
4595
+ if (field.children) {
4596
+ const childrenResult = getFieldTypes(field.children);
4597
+ imports.push(...childrenResult.imports);
4598
+ if (childrenResult.types.length || field.type === "GroupFieldType") {
4599
+ const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
4600
+ const { type: type2, imports: newImports2 } = buildTypeFromField(
4601
+ field,
4602
+ subType
4603
+ );
4604
+ imports.push(...newImports2);
4605
+ return type2;
4606
+ }
4607
+ }
4608
+ const { type, imports: newImports } = buildTypeFromField(field);
4609
+ imports.push(...newImports);
4610
+ return type;
4611
+ });
4612
+ const validImports = Array.from(
4613
+ new Set(imports.filter((name) => !INVALID_IMPORTS.includes(name)))
4614
+ );
4615
+ return { types, imports: validImports };
4616
+ }
4617
+ function constructFinalType(fields, typeName) {
4618
+ const { types, imports } = getFieldTypes(fields);
4619
+ const baseType = ts.factory.createTypeAliasDeclaration(
4620
+ [],
4621
+ [],
4622
+ "",
4623
+ void 0,
4624
+ ts.factory.createTypeLiteralNode(types)
4625
+ );
4626
+ const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
4627
+ baseType.type
4628
+ ]);
4629
+ const finalType = ts.factory.createTypeAliasDeclaration(
4630
+ [],
4631
+ [],
4632
+ typeName,
4633
+ void 0,
4634
+ wrappedType
4635
+ );
4636
+ const filteredImports = filterUnusedImports(imports, finalType);
4637
+ const importDeclaration = getImportDeclaration(
4638
+ [...filteredImports, DEFAULT_VALUES_TYPE],
4639
+ CMS_COMPONENTS_FIELD_TYPES
4640
+ );
4641
+ const defaultExport = ts.factory.createExportDefault(
4642
+ ts.factory.createIdentifier(typeName)
4643
+ );
4644
+ return [importDeclaration, finalType, defaultExport];
4645
+ }
4646
+ function writeFieldsType(fields, fileName, typeName) {
4647
+ const entries = getFieldEntries(fields);
4648
+ if (!entries) {
4649
+ return false;
4650
+ }
4651
+ try {
4652
+ const file = ts.createSourceFile(
4653
+ fileName,
4654
+ "",
4655
+ ts.ScriptTarget.ESNext,
4656
+ false,
4657
+ ts.ScriptKind.TS
4658
+ );
4659
+ const printer = ts.createPrinter();
4660
+ const nodes = constructFinalType(entries, typeName);
4661
+ const comments = [
4662
+ AUTO_GEN_COMMENT,
4663
+ "Removing the above comment will disable type generation for this module",
4664
+ "This file was created by @hubspot/cms-dev-server, for more information see https://github.hubspot.com/cms-react/reference/js-modules.html#module-fields"
4665
+ ].map((comment) => `// ${comment}`);
4666
+ const typeResult = nodes.map(
4667
+ (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)
4668
+ );
4669
+ const result = [...comments, ...typeResult].join("\n");
4670
+ writeFileSync(fileName, result);
4671
+ return true;
4672
+ } catch (e) {
4673
+ console.error(e);
4674
+ return false;
4675
+ }
4676
+ }
4677
+
4678
+ // src/lib/watchFieldsUpdates.ts
4679
+ import fs6 from "fs";
4680
+ import path12 from "path";
4681
+ import readline from "readline";
4682
+ var lastSerializedFieldsCache = {};
4683
+ var formatAsTypeName = (str) => {
4684
+ const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
4685
+ const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
4686
+ return validFirstChar ? typeName : `_${typeName}`;
4687
+ };
4688
+ var isInModulesFolder = (filePath, projectRoot) => {
4689
+ const getEntryPathFromId = (id) => {
4690
+ return id.startsWith(projectRoot) ? id.replace(`${projectRoot}${path12.sep}`, "") : "";
4691
+ };
4692
+ const currentModuleId = path12.normalize(filePath);
4693
+ const moduleEntryPath = getEntryPathFromId(currentModuleId);
4694
+ const subFolderTokens = moduleEntryPath.split(path12.sep);
4695
+ return {
4696
+ inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
4697
+ isRootModuleFile: subFolderTokens.length === 3
4698
+ };
4699
+ };
4700
+ var fileContainsAutoGenComment = async (filePath) => {
4701
+ if (!fs6.existsSync(filePath))
4702
+ return true;
4703
+ const stream2 = fs6.createReadStream(filePath);
4704
+ const reader = readline.createInterface({ input: stream2 });
4705
+ const firstLine = await new Promise(
4706
+ (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
4707
+ );
4708
+ reader.close();
4709
+ stream2.close();
4710
+ return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
4711
+ };
4712
+ var getIndexFile = (filePath, projectRoot) => {
4713
+ const { inModuleFolder, isRootModuleFile } = isInModulesFolder(
4714
+ filePath,
4715
+ projectRoot
4716
+ );
4717
+ if (!inModuleFolder)
4718
+ return void 0;
4719
+ if (isRootModuleFile)
4720
+ return { indexFilePath: filePath, isRootModuleFile };
4721
+ const dir = path12.dirname(filePath);
4722
+ const files = fs6.readdirSync(dir);
4723
+ const indexFileName = files.find((file) => file.startsWith("index."));
4724
+ return indexFileName ? { indexFilePath: path12.join(dir, indexFileName), isRootModuleFile } : void 0;
4725
+ };
4726
+ var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
4727
+ let indexFile;
4728
+ let renderFieldsToJson;
4729
+ try {
4730
+ indexFile = await viteServer.ssrLoadModule(indexFilePath);
4731
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
4732
+ ({ renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath));
4733
+ } catch (e) {
4734
+ return void 0;
4735
+ }
4736
+ if (!indexFile.fields)
4737
+ return void 0;
4738
+ const fields = indexFile.fields;
4739
+ const renderedFieldsJson = renderFieldsToJson(fields, indexFileName);
4740
+ const isValidFields = Array.isArray(renderedFieldsJson);
4741
+ return isValidFields ? renderedFieldsJson : void 0;
4742
+ };
4743
+ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
4744
+ const indexInfo = getIndexFile(filePath, projectRoot);
4745
+ if (!indexInfo)
4746
+ return;
4747
+ const { indexFilePath, isRootModuleFile } = indexInfo;
4748
+ const indexFileName = path12.parse(indexFilePath).name;
4749
+ const isTypeFile = filePath.endsWith(".types.ts");
4750
+ if (isTypeFile)
4751
+ return;
4752
+ const fields = await getIndexFileFields(
4753
+ indexFilePath,
4754
+ indexFileName,
4755
+ viteServer
4756
+ );
4757
+ if (fields) {
4758
+ const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
4759
+ const typeFilePath = path12.join(path12.dirname(filePath), typeFileName);
4760
+ const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
4761
+ const serializedFields = JSON.stringify(fields);
4762
+ if (lastSerializedFields === serializedFields)
4763
+ return;
4764
+ const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
4765
+ if (!hasAutoGenComment)
4766
+ return;
4767
+ const moduleFolderName = path12.basename(path12.dirname(filePath));
4768
+ const outputTypeName = formatAsTypeName(moduleFolderName);
4769
+ const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
4770
+ if (didSucceed) {
4771
+ lastSerializedFieldsCache[typeFilePath] = serializedFields;
4772
+ }
4773
+ const pathToLog = isRootModuleFile ? `${moduleFolderName}/${indexFileName}` : moduleFolderName;
4774
+ const successMsg = `Successfully generated types for ${pathToLog}`;
4775
+ const errorMsg = `Failed to generate types for ${pathToLog}`;
4776
+ const message = didSucceed ? successMsg : errorMsg;
4777
+ console.log(wrapMessageInColor(didSucceed ? "green" : "red", message));
4778
+ }
4779
+ };
4780
+ var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
4781
+ const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
4782
+ moduleSubpaths.forEach((modulePath) => {
4783
+ const resolvedPath = path12.resolve(projectRoot, modulePath);
4784
+ maybeUpdateFields(resolvedPath, viteServer, projectRoot);
4785
+ });
4786
+ const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
4787
+ viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
4788
+ };
4789
+
4790
+ // src/validateFields.ts
4791
+ import { http as hsCliHttp8 } from "@hubspot/local-dev-lib/http";
4792
+ import { getConfigDefaultAccount } from "@hubspot/local-dev-lib/config";
4793
+ var EDITOR_VERSION_V2 = "2.0";
4794
+ async function generateAndWriteFieldsJson(absoluteModulePath, modulePath, viteServer) {
4795
+ let fieldsJson;
4796
+ try {
4797
+ fieldsJson = await renderModuleFieldsJson_default(viteServer, absoluteModulePath);
4798
+ } catch {
4799
+ return {
4800
+ severity: "FATAL",
4801
+ errorType: "MODULE_BUILD_ERROR",
4802
+ message: `Failed to SSR-load module at ${modulePath}`
4803
+ };
4804
+ }
4805
+ if (!Array.isArray(fieldsJson)) {
4806
+ return {
4807
+ severity: "FATAL",
4808
+ errorType: "INVALID_FIELDS",
4809
+ message: `renderModuleFieldsJson returned non-array for ${modulePath}`
4810
+ };
4811
+ }
4812
+ const fieldsJsonPath = path13.join(absoluteModulePath, "fields.json");
4813
+ await fs7.writeFile(fieldsJsonPath, JSON.stringify(fieldsJson, null, 2));
4814
+ return { fieldsJson, fieldsJsonPath };
4815
+ }
4816
+ async function generateAndWriteFieldsType(absoluteModulePath, modulePath, moduleDir, fieldsJson) {
4817
+ const fieldsTypePath = path13.join(absoluteModulePath, "fields.type.ts");
4818
+ const hasAutoGenComment = await fileContainsAutoGenComment(fieldsTypePath);
4819
+ if (hasAutoGenComment) {
4820
+ const typeName = formatAsTypeName(moduleDir);
4821
+ const didSucceed = writeFieldsType(fieldsJson, fieldsTypePath, typeName);
4822
+ if (!didSucceed) {
4823
+ return {
4824
+ severity: "FATAL",
4825
+ errorType: "TYPE_GEN_ERROR",
4826
+ message: `Failed to generate fields.type.ts for ${modulePath}`
4827
+ };
4828
+ }
4829
+ }
4830
+ return { fieldsTypePath };
4831
+ }
4832
+ async function extractAndValidateFields(fieldsJson, metaJson, modulePath) {
4833
+ if (!metaJson) {
4834
+ return {
4835
+ fieldErrors: [],
4836
+ metaErrors: [
4837
+ {
4838
+ severity: "FATAL",
4839
+ errorType: "MISSING_META",
4840
+ message: `Module does not have a named meta export: ${modulePath}`
4841
+ }
4842
+ ]
4843
+ };
4844
+ }
4845
+ const portalId = getConfigDefaultAccount().accountId;
4846
+ const [fieldsResult, metaResult] = await Promise.allSettled([
4847
+ hsCliHttp8.post(portalId, {
4848
+ url: `${VALIDATE_FIELDS_ENDPOINT}?editorVersion=${metaJson.editor_version ?? EDITOR_VERSION_V2}`,
4849
+ data: fieldsJson
4850
+ }),
4851
+ hsCliHttp8.post(portalId, {
4852
+ url: VALIDATE_META_ENDPOINT,
4853
+ data: metaJson
4854
+ })
4855
+ ]);
4856
+ const mapErrors = (entities) => entities.filter((e) => e.severity === "FATAL").map((e) => ({
4857
+ severity: e.severity,
4858
+ errorType: e.errorType,
4859
+ message: e.message,
4860
+ fieldPath: e.errorTokens.path[0]
4861
+ }));
4862
+ return {
4863
+ fieldErrors: fieldsResult.status === "fulfilled" ? mapErrors(fieldsResult.value.data) : [
4864
+ {
4865
+ severity: "FATAL",
4866
+ errorType: "API_UNREACHABLE",
4867
+ message: `Field validation API error: ${fieldsResult.reason}`
4868
+ }
4869
+ ],
4870
+ metaErrors: metaResult.status === "fulfilled" ? mapErrors(metaResult.value.data) : [
4871
+ {
4872
+ severity: "FATAL",
4873
+ errorType: "API_UNREACHABLE",
4874
+ message: `Meta validation API error: ${metaResult.reason}`
4875
+ }
4876
+ ]
4877
+ };
4878
+ }
4879
+ async function validateSingleModule(modulePath, absoluteRoot, viteServer) {
4880
+ const absoluteModulePath = path13.resolve(absoluteRoot, modulePath);
4881
+ const moduleDir = path13.basename(modulePath);
4882
+ let files;
4883
+ try {
4884
+ files = await fs7.readdir(absoluteModulePath);
4885
+ } catch {
4886
+ return {
4887
+ fieldsJsonPath: "",
4888
+ fieldsTypePath: "",
4889
+ fieldErrors: [
4890
+ {
4891
+ severity: "FATAL",
4892
+ errorType: "MODULE_NOT_FOUND",
4893
+ message: `Module directory does not exist: ${modulePath}`
4894
+ }
4895
+ ],
4896
+ metaErrors: []
4897
+ };
4898
+ }
4899
+ const indexFile = files.find((f) => f.startsWith("index."));
4900
+ if (!indexFile) {
4901
+ return {
4902
+ fieldsJsonPath: "",
4903
+ fieldsTypePath: "",
4904
+ fieldErrors: [
4905
+ {
4906
+ severity: "FATAL",
4907
+ errorType: "NO_INDEX_FILE",
4908
+ message: `No index file found in ${modulePath}`
4909
+ }
4910
+ ],
4911
+ metaErrors: []
4912
+ };
4913
+ }
4914
+ const jsonResult = await generateAndWriteFieldsJson(
4915
+ absoluteModulePath,
4916
+ modulePath,
4917
+ viteServer
4918
+ );
4919
+ if ("severity" in jsonResult) {
4920
+ return {
4921
+ fieldsJsonPath: "",
4922
+ fieldsTypePath: "",
4923
+ fieldErrors: [jsonResult],
4924
+ metaErrors: []
4925
+ };
4926
+ }
4927
+ const typeResult = await generateAndWriteFieldsType(
4928
+ absoluteModulePath,
4929
+ modulePath,
4930
+ moduleDir,
4931
+ jsonResult.fieldsJson
4932
+ );
4933
+ if ("severity" in typeResult) {
4934
+ return {
4935
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
4936
+ fieldsTypePath: "",
4937
+ fieldErrors: [typeResult],
4938
+ metaErrors: []
4939
+ };
4940
+ }
4941
+ let mod;
4942
+ try {
4943
+ mod = await viteServer.ssrLoadModule(
4944
+ path13.join(absoluteModulePath, indexFile)
4945
+ );
4946
+ } catch {
4947
+ return {
4948
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
4949
+ fieldsTypePath: typeResult.fieldsTypePath,
4950
+ fieldErrors: [
4951
+ {
4952
+ severity: "FATAL",
4953
+ errorType: "MODULE_BUILD_ERROR",
4954
+ message: `Failed to SSR-load module for meta extraction: ${modulePath}`
4955
+ }
4956
+ ],
4957
+ metaErrors: []
4958
+ };
4959
+ }
4960
+ const { fieldErrors, metaErrors } = await extractAndValidateFields(
4961
+ jsonResult.fieldsJson,
4962
+ mod.meta,
4963
+ modulePath
4964
+ );
4965
+ return {
4966
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
4967
+ fieldsTypePath: typeResult.fieldsTypePath,
4968
+ fieldErrors,
4969
+ metaErrors
4970
+ };
4971
+ }
4972
+
4973
+ // src/routes/moduleValidateFields.ts
4974
+ var invalidateModuleFiles = async (viteServer, absoluteModulePath) => {
4975
+ const files = await fs8.readdir(absoluteModulePath).catch(() => []);
4976
+ files.forEach(
4977
+ (file) => {
4978
+ var _a;
4979
+ return (_a = viteServer.moduleGraph.getModulesByFile(path14.join(absoluteModulePath, file))) == null ? void 0 : _a.forEach((mod) => viteServer.moduleGraph.invalidateModule(mod));
4980
+ }
4981
+ );
4982
+ };
4983
+ var moduleValidateFieldsRouteHandler = async (request, response) => {
4984
+ try {
4985
+ const { webRoot: webRoot2, viteServer } = request.app.locals;
4986
+ const { moduleName } = request.params;
4987
+ const modulesRoot = path14.resolve(webRoot2, "components/modules");
4988
+ const absoluteModulePath = path14.resolve(modulesRoot, moduleName);
4989
+ if (!absoluteModulePath.startsWith(modulesRoot + path14.sep) || path14.dirname(absoluteModulePath) !== modulesRoot) {
4990
+ return response.status(400).json({ error: "Invalid module name" });
4991
+ }
4992
+ await invalidateModuleFiles(viteServer, absoluteModulePath);
4993
+ const result = await validateSingleModule(
4994
+ absoluteModulePath,
4995
+ webRoot2,
4996
+ viteServer
4997
+ );
4998
+ return response.status(200).json([result]);
4999
+ } catch (error) {
5000
+ console.error("Error validating module fields:", error);
5001
+ return response.status(500).json({
5002
+ error: "Failed to validate module fields"
5003
+ });
5004
+ }
5005
+ };
5006
+ var moduleValidateFields_default = moduleValidateFieldsRouteHandler;
5007
+
5008
+ // src/proxyPage/fetchContentMetadata.ts
5009
+ import http from "http";
5010
+ import https from "https";
5011
+ import { getConfigAccountIfExists as getConfigAccountIfExists6 } from "@hubspot/local-dev-lib/config";
5012
+ async function requestPage(url3, redirects = 0, originalUrl) {
5013
+ if (redirects > 5) {
5014
+ throw new Error(
5015
+ `Hit too many redirects to HEAD requests for ${originalUrl}`
5016
+ );
5017
+ }
5018
+ return new Promise((resolve3, reject) => {
5019
+ const protocolAPI = url3.startsWith("https://") ? https : http;
5020
+ protocolAPI.request(
5021
+ url3,
5022
+ {
5023
+ method: "HEAD",
5024
+ headers: {
5025
+ // Keep this user agent, so we don't get 403s from the request
5026
+ ["User-Agent"]: "cms-dev-server"
5027
+ }
5028
+ },
5029
+ async (res) => {
5030
+ let portalIdHeader;
5031
+ let contentId;
5032
+ const isContentMembershipRedirect = Boolean(
5033
+ res.headers["x-hs-content-membership-redirect"]
5034
+ );
5035
+ if (isContentMembershipRedirect) {
5036
+ debug("Content Membership Redirect", res.headers);
5037
+ portalIdHeader = res.headers["x-hs-portal-id"];
5038
+ contentId = res.headers["x-hs-content-id"];
5039
+ if (portalIdHeader && contentId) {
5040
+ return resolve3({
5041
+ portalIdHeader,
5042
+ contentId,
5043
+ res
5044
+ });
5045
+ }
5046
+ }
5047
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
5048
+ console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
5049
+ return resolve3(
5050
+ requestPage(
5051
+ res.headers.location,
5052
+ redirects + 1,
5053
+ originalUrl ?? url3
5054
+ )
5055
+ );
5056
+ }
5057
+ portalIdHeader = res.headers["x-hs-hub-id"];
5058
+ contentId = res.headers["x-hs-content-id"];
5059
+ return resolve3({
5060
+ res,
5061
+ portalIdHeader,
5062
+ contentId
5063
+ });
5064
+ }
5065
+ ).on("error", (err) => {
5066
+ console.error(err);
5067
+ reject(err);
5068
+ }).end();
5069
+ });
5070
+ }
5071
+ async function fetchContentMetadata(url3, portalId) {
5072
+ const { portalIdHeader, contentId, res } = await requestPage(url3);
5073
+ if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
5074
+ throw new Error(
5075
+ `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
5076
+ );
5077
+ } else {
5078
+ const portalIdFromResponse = parseInt(portalIdHeader, 10);
5079
+ const pageAccount = await getConfigAccountIfExists6(portalIdFromResponse);
5080
+ if (!pageAccount) {
5081
+ throw new Error(
5082
+ `No CLI auth for portal ${portalIdFromResponse} found, please run \`hs auth\``
5083
+ );
5084
+ }
5085
+ if (res.statusCode !== 200 && !(portalIdFromResponse && pageAccount && contentId)) {
5086
+ throw new Error(
5087
+ `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url3}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
5088
+ );
5089
+ } else if (!portalId || !contentId) {
5090
+ throw new Error(
5091
+ `Missing hub ID or content ID headers on HEAD request to ${url3}`
5092
+ );
5093
+ } else if (isNaN(portalId)) {
5094
+ throw new Error(
5095
+ `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
5096
+ );
5097
+ }
5098
+ const hublet = "na1";
5099
+ return { portalId, contentId, hublet };
5100
+ }
5101
+ }
5102
+
5103
+ // src/routes/proxyPageRouteHandler.ts
5104
+ async function proxyPageRouteHandler(request, response, next) {
5105
+ sendTrackingRequest("view-proxy-page-route");
5106
+ const {
5107
+ viteServer,
5108
+ webRoot: webRoot2,
5109
+ projectName,
5110
+ projectComponentPath,
5111
+ jsRenderingGates
5112
+ } = request.app.locals;
5113
+ if (!request.accepts().includes("text/html")) {
5114
+ return response.sendStatus(404);
5115
+ }
5116
+ const fullOriginalUrl = fullOriginalUrlFromRequest(request);
5117
+ const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);
5118
+ const urlToProxy = `http://${domainToProxy}${request.originalUrl}`;
5119
+ if (!domainToProxy) {
5120
+ if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {
5121
+ const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;
5122
+ consoleWarn(message);
5123
+ return response.status(400).send(message);
5124
+ } else {
5125
+ const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;
5126
+ consoleWarn(message);
5127
+ return response.status(400).send(message);
5128
+ }
5129
+ }
5130
+ try {
5131
+ const { portalId, contentId, hublet } = await fetchContentMetadata(
5132
+ urlToProxy,
5133
+ request.app.locals.authedPortalId
5134
+ );
5135
+ await proxySpecificPage(
5136
+ request,
5137
+ response,
5138
+ portalId,
5139
+ hublet,
5140
+ contentId,
5141
+ webRoot2,
5142
+ viteServer,
5143
+ projectName,
4597
5144
  projectComponentPath,
4598
5145
  jsRenderingGates,
4599
5146
  urlToProxy,
@@ -4659,31 +5206,31 @@ function HubLModulesList({ modules }) {
4659
5206
  }
4660
5207
 
4661
5208
  // src/api/designmanager.ts
4662
- import { http as hsCliHttp8 } from "@hubspot/local-dev-lib/http";
5209
+ import { http as hsCliHttp9 } from "@hubspot/local-dev-lib/http";
4663
5210
  var DESIGN_MANAGER_API_PATH = "designmanager/v1";
4664
5211
  async function fetchHubLModules(accountId, previewToken, limit = 250) {
4665
- return (await hsCliHttp8.get(accountId, {
5212
+ return (await hsCliHttp9.get(accountId, {
4666
5213
  url: `${DESIGN_MANAGER_API_PATH}/modules/local-preview?previewToken=${previewToken}&limit=${limit}`
4667
5214
  })).data;
4668
5215
  }
4669
5216
  async function fetchPreviewTemplates(accountId, previewToken, limit = 250) {
4670
- return (await hsCliHttp8.get(accountId, {
5217
+ return (await hsCliHttp9.get(accountId, {
4671
5218
  url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}&limit=${limit}`
4672
5219
  })).data;
4673
5220
  }
4674
- async function fetchModuleByPath(accountId, path19) {
4675
- return (await hsCliHttp8.get(accountId, {
4676
- url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path19}?portalId=${accountId}`
5221
+ async function fetchModuleByPath(accountId, path21) {
5222
+ return (await hsCliHttp9.get(accountId, {
5223
+ url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path21}?portalId=${accountId}`
4677
5224
  })).data;
4678
5225
  }
4679
- async function fetchTemplateByPath(accountId, path19) {
4680
- return (await hsCliHttp8.get(accountId, {
4681
- url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path19}?portalId=${accountId}`
5226
+ async function fetchTemplateByPath(accountId, path21) {
5227
+ return (await hsCliHttp9.get(accountId, {
5228
+ url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path21}?portalId=${accountId}`
4682
5229
  })).data;
4683
5230
  }
4684
- async function fetchModulePageDependencies(accountId, path19) {
4685
- const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path19}`;
4686
- return (await hsCliHttp8.get(accountId, { url: url3 })).data;
5231
+ async function fetchModulePageDependencies(accountId, path21) {
5232
+ const url3 = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path21}`;
5233
+ return (await hsCliHttp9.get(accountId, { url: url3 })).data;
4687
5234
  }
4688
5235
 
4689
5236
  // src/components/HubLTemplatesList.tsx
@@ -4918,7 +5465,7 @@ function proxyServerlessRequest(req, res, next) {
4918
5465
  }
4919
5466
 
4920
5467
  // src/routes/modulePreviewRouteHandler.ts
4921
- import path12 from "path";
5468
+ import path15 from "path";
4922
5469
  import { normalizePath as normalizePath8 } from "vite";
4923
5470
  async function modulePreviewRouteHandler(request, response) {
4924
5471
  sendTrackingRequest("view-module-preview-route");
@@ -4935,7 +5482,7 @@ async function modulePreviewRouteHandler(request, response) {
4935
5482
  } = request.app.locals;
4936
5483
  const moduleName = request.params.moduleName;
4937
5484
  const modulePath = normalizePath8(
4938
- path12.resolve(webRoot2, "components/modules/", moduleName)
5485
+ path15.resolve(webRoot2, "components/modules/", moduleName)
4939
5486
  );
4940
5487
  const PREVIEWER_APP_PARAM = "hsPreviewerApp";
4941
5488
  let fieldOverrides = {};
@@ -5036,7 +5583,7 @@ var modulePreviewRouteHandler_default = modulePreviewRouteHandler;
5036
5583
  // src/routes/hublModuleRouteHandler.ts
5037
5584
  var hublModuleRouteHandler = async (request, response) => {
5038
5585
  sendTrackingRequest("view-hubl-module-route");
5039
- const { authedPortalId, localPreviewToken, projectName, jsRenderingGates } = request.app.locals;
5586
+ const { authedPortalId, localPreviewToken, projectName } = request.app.locals;
5040
5587
  const { modulePath } = request.params;
5041
5588
  if (!modulePath) {
5042
5589
  response.status(200).set({ "Content-Type": "text/html" }).end(buildModuleIndex());
@@ -5064,7 +5611,7 @@ var hublModuleRouteHandler = async (request, response) => {
5064
5611
  };
5065
5612
  const previewUrl = getPreviewUrl(request, params);
5066
5613
  try {
5067
- const result = await signedGet(authedPortalId, previewUrl, {}, jsRenderingGates);
5614
+ const result = await signedGet(authedPortalId, previewUrl, {});
5068
5615
  const html = addRefreshScript(result);
5069
5616
  response.status(200).set({ "Content-Type": "text/html" }).end(html);
5070
5617
  } catch (err) {
@@ -5139,12 +5686,7 @@ var templateRouteHandler = async (request, response) => {
5139
5686
  const previewUrl = getPreviewUrl(request, params);
5140
5687
  const fullOriginalUrl = `${request.protocol}://${request.get("host")}${request.originalUrl}`;
5141
5688
  try {
5142
- const result = await signedGet(
5143
- authedPortalId,
5144
- previewUrl,
5145
- {},
5146
- jsRenderingGates
5147
- );
5689
+ const result = await signedGet(authedPortalId, previewUrl, {});
5148
5690
  const pageHtml = addRefreshScript(result);
5149
5691
  const finalHtml = pageHtml.replace(
5150
5692
  HUBSPOT_PREVIEW_BASE_TAG_REGEX,
@@ -5198,15 +5740,15 @@ function getOpenCommand() {
5198
5740
  }
5199
5741
  }
5200
5742
  async function handleGetModulePages(req, res, next) {
5201
- const { path: path19, portalId } = req.query;
5202
- if (!path19 || !portalId) {
5743
+ const { path: path21, portalId } = req.query;
5744
+ if (!path21 || !portalId) {
5203
5745
  return res.status(400).json({ error: "Missing required parameters" });
5204
5746
  }
5205
5747
  try {
5206
5748
  sendTrackingRequest("handle-module-dependencies");
5207
5749
  const data = await fetchModulePageDependencies(
5208
5750
  Number(portalId),
5209
- path19
5751
+ path21
5210
5752
  );
5211
5753
  res.json(data);
5212
5754
  } catch (err) {
@@ -5214,14 +5756,14 @@ async function handleGetModulePages(req, res, next) {
5214
5756
  }
5215
5757
  }
5216
5758
  function handleOpenFile(req, res, next) {
5217
- const { path: path19 } = req.query;
5218
- if (!path19) {
5759
+ const { path: path21 } = req.query;
5760
+ if (!path21) {
5219
5761
  return res.status(400).json({ error: "Missing required parameters" });
5220
5762
  }
5221
5763
  try {
5222
5764
  sendTrackingRequest("handle-open-file");
5223
5765
  const command = getOpenCommand();
5224
- spawn(command, [path19], { detached: true }).unref();
5766
+ spawn(command, [path21], { detached: true }).unref();
5225
5767
  res.sendStatus(200);
5226
5768
  } catch (err) {
5227
5769
  next(err);
@@ -5236,19 +5778,19 @@ function createAppServerAPIRoutes() {
5236
5778
  var createAppServerAPIRoutes_default = createAppServerAPIRoutes;
5237
5779
 
5238
5780
  // src/routes/appServerRouteHandler.ts
5239
- import fs7 from "node:fs/promises";
5240
- import path14 from "path";
5781
+ import fs10 from "node:fs/promises";
5782
+ import path17 from "path";
5241
5783
  import { pathToFileURL } from "url";
5242
5784
 
5243
5785
  // src/lib/getDevServerUIData.ts
5244
- import path13 from "path";
5786
+ import path16 from "path";
5245
5787
  import { normalizePath as normalizePath9 } from "vite";
5246
5788
 
5247
5789
  // src/api/project.ts
5248
- import { http as hsCliHttp9 } from "@hubspot/local-dev-lib/http";
5790
+ import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
5249
5791
  var DEVELOPER_PROJECTS_API_PATH = "/developer/projects/v1";
5250
5792
  async function fetchProjectByName(accountId, projectName) {
5251
- return (await hsCliHttp9.get(accountId, {
5793
+ return (await hsCliHttp10.get(accountId, {
5252
5794
  url: `${DEVELOPER_PROJECTS_API_PATH}/by-name/${projectName}`
5253
5795
  })).data;
5254
5796
  }
@@ -5376,18 +5918,25 @@ import { join as join4 } from "path";
5376
5918
  function getPackageJson(packagePath2) {
5377
5919
  return JSON.parse(readFileSync3(join4(packagePath2, "package.json")).toString());
5378
5920
  }
5379
- function getDepsForPackage(packagePath2) {
5380
- const packageJson = getPackageJson(packagePath2);
5381
- return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];
5382
- }
5383
- function getDepsForPackageIfExists(packagePath2) {
5921
+ function getAllDepsForPackageIfExists(packagePath2) {
5384
5922
  try {
5385
- return getDepsForPackage(packagePath2);
5923
+ const packageJson = getPackageJson(packagePath2);
5924
+ return [
5925
+ .../* @__PURE__ */ new Set([
5926
+ ...Object.keys(packageJson.dependencies ?? {}),
5927
+ ...Object.keys(packageJson.peerDependencies ?? {})
5928
+ ])
5929
+ ];
5386
5930
  } catch (e) {
5387
5931
  console.warn("No package.json at ", packagePath2);
5388
5932
  return [];
5389
5933
  }
5390
5934
  }
5935
+ function hasCmsComponentsDependency(packagePath2) {
5936
+ return getAllDepsForPackageIfExists(packagePath2).includes(
5937
+ "@hubspot/cms-components"
5938
+ );
5939
+ }
5391
5940
  async function createViteDevServer(webRoot2, port, sslEnabled, domainsToProxy = [], jsRenderingGates, secretNames, logLevel) {
5392
5941
  const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
5393
5942
  `${proxyDomain}.localhost`,
@@ -5399,8 +5948,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
5399
5948
  `);
5400
5949
  }
5401
5950
  const origin = process.env.VITE_ORIGIN ?? (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);
5402
- const consumerDeps = getDepsForPackageIfExists(webRoot2);
5403
- const isProjectWithReact = consumerDeps.includes("@hubspot/cms-components") || process.env.TRANSLATE_ASSET;
5951
+ const isProjectWithReact = hasCmsComponentsDependency(webRoot2) || process.env.TRANSLATE_ASSET;
5404
5952
  const componentsShimPlugin = isProjectWithReact ? null : cmsComponentsShimPlugin();
5405
5953
  const ssrAndOptimizeDep = isProjectWithReact ? {
5406
5954
  ssr: {
@@ -5473,7 +6021,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
5473
6021
  var createViteDevServer_default = createViteDevServer;
5474
6022
 
5475
6023
  // src/lib/getDevServerUIData.ts
5476
- import fs6 from "node:fs";
6024
+ import fs9 from "node:fs";
5477
6025
  var templateTypeMap = {
5478
6026
  // Standard templates
5479
6027
  4: "Page",
@@ -5499,7 +6047,7 @@ function mapReactModules(modules, themeWebRoot, appViteServer) {
5499
6047
  return Promise.all(
5500
6048
  modules.moduleNames.map(async (name, index) => {
5501
6049
  const modulePath = normalizePath9(
5502
- path13.resolve(themeWebRoot, "components/modules/", name)
6050
+ path16.resolve(themeWebRoot, "components/modules/", name)
5503
6051
  );
5504
6052
  const fieldsJson = await renderModuleFieldsJson_default(
5505
6053
  appViteServer,
@@ -5545,9 +6093,9 @@ function normalizeTemplatesData(templates, projectName) {
5545
6093
  });
5546
6094
  }
5547
6095
  function detectPackageManager(projectRoot) {
5548
- if (fs6.existsSync(path13.join(projectRoot, "yarn.lock")))
6096
+ if (fs9.existsSync(path16.join(projectRoot, "yarn.lock")))
5549
6097
  return "yarn";
5550
- if (fs6.existsSync(path13.join(projectRoot, "pnpm-lock.yaml")))
6098
+ if (fs9.existsSync(path16.join(projectRoot, "pnpm-lock.yaml")))
5551
6099
  return "pnpm";
5552
6100
  return "npm";
5553
6101
  }
@@ -5631,10 +6179,10 @@ var appServerRouteHandler = async (req, res, __next) => {
5631
6179
  const { appWebRoot, appViteServer } = appLocals;
5632
6180
  const initialProps = await getDevServerUIData(appLocals);
5633
6181
  const url3 = req.originalUrl.replace("/", "");
5634
- const templatePath = path14.join(appWebRoot, "index.html");
5635
- const serverEntryPath = isProd ? path14.join(appWebRoot, "server/serverEntry.js") : path14.join(appWebRoot, "serverEntry.tsx");
6182
+ const templatePath = path17.join(appWebRoot, "index.html");
6183
+ const serverEntryPath = isProd ? path17.join(appWebRoot, "server/serverEntry.js") : path17.join(appWebRoot, "serverEntry.tsx");
5636
6184
  let render;
5637
- let template = await fs7.readFile(path14.join(templatePath), "utf-8");
6185
+ let template = await fs10.readFile(path17.join(templatePath), "utf-8");
5638
6186
  if (isProd) {
5639
6187
  const { render: ssrRender } = await import(pathToFileURL(serverEntryPath).href);
5640
6188
  render = ssrRender;
@@ -5665,7 +6213,7 @@ var appServerRouteHandler = async (req, res, __next) => {
5665
6213
  var appServerRouteHandler_default = appServerRouteHandler;
5666
6214
 
5667
6215
  // src/routes/createDevServerRoutes.ts
5668
- import path15 from "path";
6216
+ import path18 from "path";
5669
6217
  var isProd2 = true;
5670
6218
  var STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(
5671
6219
  (domain2) => `storybook.${domain2}`
@@ -5692,7 +6240,7 @@ var createDevServerRoutes = async (viteServer, appLocals, storybookPort) => {
5692
6240
  }
5693
6241
  devServerApp.use(urlencoded());
5694
6242
  if (isProd2) {
5695
- const distAssetsPath = path15.join(appWebRoot, "assets");
6243
+ const distAssetsPath = path18.join(appWebRoot, "assets");
5696
6244
  devServerApp.use("/assets", expressStatic(distAssetsPath));
5697
6245
  } else if (appViteServer) {
5698
6246
  devServerApp.use("/local", appViteServer.middlewares);
@@ -5716,6 +6264,10 @@ var createDevServerRoutes = async (viteServer, appLocals, storybookPort) => {
5716
6264
  moduleFieldsJson_default
5717
6265
  );
5718
6266
  devServerApp.get("/module/:moduleName/*", module_default);
6267
+ devServerApp.post(
6268
+ "/preview/module/:moduleName/validate-fields",
6269
+ moduleValidateFields_default
6270
+ );
5719
6271
  devServerApp.post("/preview/module/:moduleName", modulePreviewRouteHandler_default);
5720
6272
  devServerApp.get("/hublmodule/:modulePath(*)", hublModuleRouteHandler);
5721
6273
  devServerApp.get("/template/:templatePath(*)", templateRouteHandler);
@@ -5929,575 +6481,220 @@ function createHttpsRedirectingServer(opts, handler) {
5929
6481
  "Unknown issue with incoming data, unknown if http or https"
5930
6482
  );
5931
6483
  }
5932
- const proxy = protocol === "http" ? innerHTTPServer : innerHTTPSServer;
5933
- if (proxy) {
5934
- socket.unshift(buffer);
5935
- proxy.emit("connection", socket);
5936
- }
5937
- process.nextTick(() => socket.resume());
5938
- });
5939
- });
5940
- return { server, innerHTTPServer, innerHTTPSServer };
5941
- }
5942
-
5943
- // src/lib/getJSRenderingGates.ts
5944
- import { getAccessToken } from "@hubspot/local-dev-lib/personalAccessKey";
5945
-
5946
- // src/lib/gates.ts
5947
- function getGatesFromEnv() {
5948
- const gates = process.env.GATES ? process.env.GATES.split(",") : [];
5949
- return gates;
5950
- }
5951
-
5952
- // src/lib/getJSRenderingGates.ts
5953
- var mapEnabledFeaturesToGates = (enabledFeatures) => {
5954
- return Object.keys(enabledFeatures).reduce((gates, enabledFeature) => {
5955
- if (enabledFeatures[enabledFeature]) {
5956
- gates.push(ENABLED_FEATURES_GATE_MAP[enabledFeature]);
5957
- }
5958
- return gates;
5959
- }, []);
5960
- };
5961
- async function getJsRenderingGates(portalId, env2, personalAccessKey) {
5962
- const { enabledFeatures } = await getAccessToken(personalAccessKey, env2, portalId);
5963
- const envGates = getGatesFromEnv();
5964
- const gates = mapEnabledFeaturesToGates(enabledFeatures);
5965
- const mergedGates = [...envGates, ...gates];
5966
- process.env.GATES = mergedGates.join(",");
5967
- return mergedGates;
5968
- }
5969
-
5970
- // src/createDevServer.ts
5971
- import {
5972
- getConfigAccountIfExists as getConfigAccountIfExists8,
5973
- getConfigDefaultAccountIfExists,
5974
- validateConfig
5975
- } from "@hubspot/local-dev-lib/config";
5976
- import { fetchSecrets } from "@hubspot/local-dev-lib/api/secrets";
5977
- import { PERSONAL_ACCESS_KEY_AUTH_METHOD } from "@hubspot/local-dev-lib/constants/auth";
5978
-
5979
- // src/proxyPage/fetchDomains.ts
5980
- import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
5981
-
5982
- // src/lib/errors.ts
5983
- var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
5984
- You may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account
5985
- `;
5986
- var OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
5987
- var NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
5988
- var MissingScopeError = class extends Error {
5989
- constructor(error) {
5990
- let messageEnd = "";
5991
- if (error.error.message.match(OAUTH_ERROR_REGEX)) {
5992
- messageEnd = error.error.message;
5993
- }
5994
- super(`${MISSING_SCOPE_ERROR_PREFIX}
5995
- ${messageEnd}`);
5996
- Object.setPrototypeOf(this, MissingScopeError.prototype);
5997
- }
5998
- };
5999
- function logMissingScopeWarning(error) {
6000
- console.warn(error.message);
6001
- }
6002
- function isMissingScopeError2(error) {
6003
- return error.statusCode === 403 && (error.error.message.match(OAUTH_ERROR_REGEX) || error.error.message.startsWith(NOT_PUBLIC_USE_ERROR));
6004
- }
6005
- function handleSecretsError(error) {
6006
- if (error && error.statusCode && error.error) {
6007
- const { statusCode, error: errorDetails } = error;
6008
- if ((errorDetails == null ? void 0 : errorDetails.category) === "MISSING_SCOPES") {
6009
- console.log(
6010
- "\nMissing scopes for secrets.",
6011
- "\nSecrets require Serverless functions which are scoped to Enterprise portals.\n"
6012
- );
6013
- } else {
6014
- console.error(`Error ${statusCode}: ${errorDetails.message}`);
6015
- if (errorDetails.correlationId) {
6016
- console.error(`Correlation ID: ${errorDetails.correlationId}`);
6017
- }
6018
- if (errorDetails.category) {
6019
- console.error(`Category: ${errorDetails.category}`);
6020
- }
6021
- if (errorDetails.links) {
6022
- if (errorDetails.links.support) {
6023
- console.error(`Support URL: ${errorDetails.links.support}`);
6024
- }
6025
- if (errorDetails.links.forum) {
6026
- console.error(`Forum URL: ${errorDetails.links.forum}`);
6027
- }
6028
- }
6029
- }
6030
- } else {
6031
- console.error("Unexpected error structure:", error);
6032
- }
6033
- }
6034
-
6035
- // src/proxyPage/fetchDomains.ts
6036
- async function fetchDomains(portalId) {
6037
- try {
6038
- const result = (await hsCliHttp10.get(portalId, {
6039
- url: `/cms/v3/domains`,
6040
- params: { portalId },
6041
- responseType: "json"
6042
- })).data;
6043
- return result.results;
6044
- } catch (error) {
6045
- if (isMissingScopeError2(error)) {
6046
- throw new MissingScopeError(error);
6047
- }
6048
- throw error;
6049
- }
6050
- }
6051
- async function fetchWebsiteDomainNames(portalId) {
6052
- const domains = await fetchDomains(portalId);
6053
- const filteredDomains = domains.filter((domain2) => {
6054
- return domain2.isUsedForBlogPost || domain2.isUsedForSitePage || domain2.isUsedForLandingPage;
6055
- });
6056
- const domainNames = filteredDomains.map((r) => r.domain);
6057
- return domainNames;
6058
- }
6059
-
6060
- // src/lib/validateHSPlatform.ts
6061
- import path16 from "path";
6062
- import fs8 from "fs";
6063
- import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
6064
- var HSPROJECT_JSON = "hsproject.json";
6065
- function checkFileExists(filePath) {
6066
- return fs8.existsSync(filePath) && fs8.statSync(filePath).isFile();
6067
- }
6068
- function findHSProjectJson(startPath) {
6069
- let currentDir = startPath;
6070
- let dirLevel = 0;
6071
- const maxDirLevel = 4;
6072
- while (path16.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
6073
- const filePath = path16.join(currentDir, HSPROJECT_JSON);
6074
- if (checkFileExists(filePath)) {
6075
- return filePath;
6076
- }
6077
- currentDir = path16.dirname(currentDir);
6078
- dirLevel++;
6079
- }
6080
- console.log(
6081
- `'${HSPROJECT_JSON}' not found in any parent of dev server target`
6082
- );
6083
- return null;
6084
- }
6085
- async function validateHSPlatform(projectConfigPath, portalId, deferSelection) {
6086
- if (projectConfigPath === null) {
6087
- console.log(
6088
- `Unable to find local ${HSPROJECT_JSON}, skipping platform version validation.`
6089
- );
6090
- return false;
6091
- }
6092
- const hsProjectJSONContents = fs8.readFileSync(projectConfigPath, "utf8");
6093
- const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
6094
- const { platformVersion } = hsProjectJSONData;
6095
- let platformVersionResult;
6096
- try {
6097
- platformVersionResult = (await hsCliHttp11.get(portalId, {
6098
- url: `developer/projects/v1/platformVersion`,
6099
- responseType: "json"
6100
- })).data;
6101
- } catch (e) {
6102
- console.error(e.message);
6103
- console.log(
6104
- "Unable to find active platform versions, skipping platform version validation."
6105
- );
6106
- return false;
6107
- }
6108
- if (platformVersion === void 0 || !platformVersionResult.activePlatformVersions.includes(platformVersion)) {
6109
- const promptAndWrite = async () => {
6110
- const { default: select } = await import("@inquirer/select");
6111
- const answer = await select({
6112
- message: 'Your local "hsproject.json" does not have a valid platform version, please select a valid platform version. You can read more about Platform Versioning here https://developers.hubspot.com/docs/platform/platform-versioning',
6113
- choices: platformVersionResult.activePlatformVersions.map(
6114
- (versionNumber) => ({
6115
- name: versionNumber,
6116
- value: versionNumber
6117
- })
6118
- )
6119
- });
6120
- hsProjectJSONData.platformVersion = answer;
6121
- try {
6122
- fs8.writeFileSync(
6123
- projectConfigPath,
6124
- JSON.stringify(hsProjectJSONData, void 0, 2),
6125
- "utf8"
6126
- );
6127
- return true;
6128
- } catch (e) {
6129
- console.error(
6130
- `unable to write updated valid platform version, please make sure platformVersion in "${HSPROJECT_JSON}" is one of ${platformVersionResult.activePlatformVersions}`
6131
- );
6132
- return false;
6133
- }
6134
- };
6135
- if (deferSelection) {
6136
- deferSelection(promptAndWrite);
6137
- return false;
6484
+ const proxy = protocol === "http" ? innerHTTPServer : innerHTTPSServer;
6485
+ if (proxy) {
6486
+ socket.unshift(buffer);
6487
+ proxy.emit("connection", socket);
6488
+ }
6489
+ process.nextTick(() => socket.resume());
6490
+ });
6491
+ });
6492
+ return { server, innerHTTPServer, innerHTTPSServer };
6493
+ }
6494
+
6495
+ // src/lib/getJSRenderingGates.ts
6496
+ import { getAccessToken } from "@hubspot/local-dev-lib/personalAccessKey";
6497
+
6498
+ // src/lib/gates.ts
6499
+ function getGatesFromEnv() {
6500
+ const gates = process.env.GATES ? process.env.GATES.split(",") : [];
6501
+ return gates;
6502
+ }
6503
+
6504
+ // src/lib/getJSRenderingGates.ts
6505
+ var mapEnabledFeaturesToGates = (enabledFeatures) => {
6506
+ return Object.keys(enabledFeatures).reduce((gates, enabledFeature) => {
6507
+ if (enabledFeatures[enabledFeature]) {
6508
+ gates.push(ENABLED_FEATURES_GATE_MAP[enabledFeature]);
6138
6509
  }
6139
- return promptAndWrite();
6140
- }
6141
- return true;
6510
+ return gates;
6511
+ }, []);
6512
+ };
6513
+ async function getJsRenderingGates(portalId, env2, personalAccessKey) {
6514
+ const { enabledFeatures } = await getAccessToken(personalAccessKey, env2, portalId);
6515
+ const envGates = getGatesFromEnv();
6516
+ const gates = mapEnabledFeaturesToGates(enabledFeatures);
6517
+ const mergedGates = [...envGates, ...gates];
6518
+ process.env.GATES = mergedGates.join(",");
6519
+ return mergedGates;
6142
6520
  }
6143
6521
 
6144
6522
  // src/createDevServer.ts
6145
- import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
6523
+ import {
6524
+ getConfigAccountIfExists as getConfigAccountIfExists8,
6525
+ getConfigDefaultAccountIfExists,
6526
+ validateConfig
6527
+ } from "@hubspot/local-dev-lib/config";
6528
+ import { fetchSecrets } from "@hubspot/local-dev-lib/api/secrets";
6529
+ import { PERSONAL_ACCESS_KEY_AUTH_METHOD } from "@hubspot/local-dev-lib/constants/auth";
6146
6530
 
6147
- // ../cms-js-internal/dist/buildFieldsTypes.js
6148
- import { writeFileSync } from "fs";
6149
- import ts from "typescript";
6150
- var fieldTypeNameByType = {
6151
- alignment: "AlignmentFieldType",
6152
- audioplayer: "AudioFieldType",
6153
- backgroundimage: "BackgroundImageFieldType",
6154
- blog: "BlogFieldType",
6155
- boolean: "BooleanFieldType",
6156
- border: "BorderFieldType",
6157
- choice: "ChoiceFieldType",
6158
- color: "ColorFieldType",
6159
- crmobject: "CrmObjectFieldType",
6160
- cta: "CtaFieldType",
6161
- date: "DateFieldType",
6162
- datetime: "DateTimeFieldType",
6163
- email: "EmailFieldType",
6164
- embed: "EmbedFieldType",
6165
- file: "FileFieldType",
6166
- followupemail: "FollowUpEmailFieldType",
6167
- font: "FontFieldType",
6168
- form: "FormFieldType",
6169
- gradient: "GradientFieldType",
6170
- group: "GroupFieldType",
6171
- html: "HtmlFieldType",
6172
- hubdbrow: "HubDbRowFieldType",
6173
- hubdbtable: "HubDbTableFieldType",
6174
- hubl: "HublFieldType",
6175
- icon: "IconFieldType",
6176
- image: "ImageFieldType",
6177
- link: "LinkFieldType",
6178
- logo: "LogoFieldType",
6179
- meeting: "MeetingFieldType",
6180
- menu: "MenuFieldType",
6181
- number: "NumberFieldType",
6182
- page: "PageFieldType",
6183
- payment: "PaymentFieldType",
6184
- podcast: "PodcastFieldType",
6185
- richtext: "RichTextFieldType",
6186
- salesforcecampaign: "SfdcCamapaignFieldType",
6187
- simplemenu: "SimpleMenuFieldType",
6188
- spacing: "SpacingFieldType",
6189
- survey: "SurveyFieldType",
6190
- tag: "TagFieldType",
6191
- textalignment: "TextAlignmentFieldType",
6192
- text: "TextFieldType",
6193
- url: "UrlFieldType",
6194
- variantselection: "VariantSelectionFieldType",
6195
- videoplayer: "VideoFieldType",
6196
- workflow: "WorkflowFieldType"
6197
- };
6198
- function getFieldEntries(fields) {
6199
- if (!Array.isArray(fields)) {
6200
- return void 0;
6201
- }
6202
- return fields.filter((field) => field.name && field.type).map((field) => {
6203
- const { name, type } = field;
6204
- const fieldType = fieldTypeNameByType[type];
6205
- if (!fieldType) {
6206
- return void 0;
6207
- }
6208
- const entry = {
6209
- type: fieldType,
6210
- name,
6211
- isRepeater: "occurrence" in field,
6212
- isRequired: !!field.required,
6213
- choices: (
6214
- // Choices are pair [value, label] but only the value is printed to the page, so flatten it.
6215
- "choices" in field ? field.choices.map(([value, label]) => value) : void 0
6216
- ),
6217
- children: []
6218
- };
6219
- if (fieldType === "GroupFieldType" && "children" in field) {
6220
- const children = getFieldEntries(field.children);
6221
- return { ...entry, children };
6531
+ // src/proxyPage/fetchDomains.ts
6532
+ import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
6533
+
6534
+ // src/lib/errors.ts
6535
+ var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
6536
+ You may need to re-generate a new personal access key with the required scopes and re-run \`hs-auth\`, or you may not have this functionality enabled in your account
6537
+ `;
6538
+ var OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
6539
+ var NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
6540
+ var MissingScopeError = class extends Error {
6541
+ constructor(error) {
6542
+ let messageEnd = "";
6543
+ if (error.error.message.match(OAUTH_ERROR_REGEX)) {
6544
+ messageEnd = error.error.message;
6222
6545
  }
6223
- return entry;
6224
- }).filter((entry) => entry !== void 0);
6225
- }
6226
- var INVALID_IMPORTS = ["ChoiceFieldType", "GroupFieldType"];
6227
- var FIELD_GROUP_TYPE = "FieldGroupWithChildren";
6228
- var REPEATER_GROUP_TYPE = "RepeaterGroup";
6229
- var REQUIRED_TYPE = "RequiredField";
6230
- var DEFAULT_VALUES_TYPE = "DefaultValues";
6231
- var CMS_COMPONENTS = "@hubspot/cms-components";
6232
- var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
6233
- var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
6234
- var createPropertySignature = (identifier, type, hasQuestionToken = false) => ts.factory.createPropertySignature(
6235
- [],
6236
- identifier,
6237
- hasQuestionToken ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0,
6238
- type
6239
- );
6240
- var createUnionTypeFromArray = (values) => ts.factory.createUnionTypeNode(
6241
- values.map(
6242
- (value) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value))
6243
- )
6244
- );
6245
- var buildTypeFromField = (field, additionalNode) => {
6246
- const imports = [field.type];
6247
- const identifier = ts.factory.createIdentifier(field.name);
6248
- const baseType = ts.factory.createTypeReferenceNode(field.type);
6249
- const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
6250
- baseType
6251
- ]);
6252
- let finalType = field.isRequired ? requiredType : baseType;
6253
- if (field.choices) {
6254
- finalType = createUnionTypeFromArray(field.choices);
6255
- }
6256
- if (field.isRequired) {
6257
- imports.push(REQUIRED_TYPE);
6258
- }
6259
- if (additionalNode) {
6260
- const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
6261
- const genericType = field.isRepeater ? REPEATER_GROUP_TYPE : FIELD_GROUP_TYPE;
6262
- imports.push(genericType);
6263
- finalType = ts.factory.createTypeReferenceNode(genericType, [typeLiteral]);
6546
+ super(`${MISSING_SCOPE_ERROR_PREFIX}
6547
+ ${messageEnd}`);
6548
+ Object.setPrototypeOf(this, MissingScopeError.prototype);
6264
6549
  }
6265
- return {
6266
- type: createPropertySignature(
6267
- identifier,
6268
- finalType,
6269
- !field.isRequired && !additionalNode
6270
- ),
6271
- imports
6272
- };
6273
6550
  };
6274
- var filterUnusedImports = (imports, type) => {
6275
- const usedImports = /* @__PURE__ */ new Set();
6276
- const visit = (node) => {
6277
- if (ts.isTypeReferenceNode(node)) {
6278
- const typeName = node.typeName;
6279
- if ("escapedText" in typeName) {
6280
- usedImports.add(typeName.escapedText.toString());
6281
- }
6282
- }
6283
- ts.forEachChild(node, visit);
6284
- };
6285
- visit(type);
6286
- return imports.filter((name) => usedImports.has(name));
6287
- };
6288
- function getImportDeclaration(imports, moduleSpecifier) {
6289
- const importSpecifiers = Array.from(imports).map(
6290
- (importName) => ts.factory.createImportSpecifier(
6291
- true,
6292
- void 0,
6293
- ts.factory.createIdentifier(importName)
6294
- )
6295
- );
6296
- const namedImports = ts.factory.createNamedImports(importSpecifiers);
6297
- return ts.factory.createImportDeclaration(
6298
- [],
6299
- [],
6300
- ts.factory.createImportClause(false, void 0, namedImports),
6301
- ts.factory.createStringLiteral(moduleSpecifier)
6302
- );
6551
+ function logMissingScopeWarning(error) {
6552
+ console.warn(error.message);
6303
6553
  }
6304
- function getFieldTypes(fields) {
6305
- const imports = [];
6306
- const types = fields.map((field) => {
6307
- if (field.children) {
6308
- const childrenResult = getFieldTypes(field.children);
6309
- imports.push(...childrenResult.imports);
6310
- if (childrenResult.types.length || field.type === "GroupFieldType") {
6311
- const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
6312
- const { type: type2, imports: newImports2 } = buildTypeFromField(
6313
- field,
6314
- subType
6315
- );
6316
- imports.push(...newImports2);
6317
- return type2;
6554
+ function isMissingScopeError2(error) {
6555
+ return error.statusCode === 403 && (error.error.message.match(OAUTH_ERROR_REGEX) || error.error.message.startsWith(NOT_PUBLIC_USE_ERROR));
6556
+ }
6557
+ function handleSecretsError(error) {
6558
+ if (error && error.statusCode && error.error) {
6559
+ const { statusCode, error: errorDetails } = error;
6560
+ if ((errorDetails == null ? void 0 : errorDetails.category) === "MISSING_SCOPES") {
6561
+ console.log(
6562
+ "\nMissing scopes for secrets.",
6563
+ "\nSecrets require Serverless functions which are scoped to Enterprise portals.\n"
6564
+ );
6565
+ } else {
6566
+ console.error(`Error ${statusCode}: ${errorDetails.message}`);
6567
+ if (errorDetails.correlationId) {
6568
+ console.error(`Correlation ID: ${errorDetails.correlationId}`);
6569
+ }
6570
+ if (errorDetails.category) {
6571
+ console.error(`Category: ${errorDetails.category}`);
6572
+ }
6573
+ if (errorDetails.links) {
6574
+ if (errorDetails.links.support) {
6575
+ console.error(`Support URL: ${errorDetails.links.support}`);
6576
+ }
6577
+ if (errorDetails.links.forum) {
6578
+ console.error(`Forum URL: ${errorDetails.links.forum}`);
6579
+ }
6318
6580
  }
6319
6581
  }
6320
- const { type, imports: newImports } = buildTypeFromField(field);
6321
- imports.push(...newImports);
6322
- return type;
6582
+ } else {
6583
+ console.error("Unexpected error structure:", error);
6584
+ }
6585
+ }
6586
+
6587
+ // src/proxyPage/fetchDomains.ts
6588
+ async function fetchDomains(portalId) {
6589
+ try {
6590
+ const result = (await hsCliHttp11.get(portalId, {
6591
+ url: `/cms/v3/domains`,
6592
+ params: { portalId },
6593
+ responseType: "json"
6594
+ })).data;
6595
+ return result.results;
6596
+ } catch (error) {
6597
+ if (isMissingScopeError2(error)) {
6598
+ throw new MissingScopeError(error);
6599
+ }
6600
+ throw error;
6601
+ }
6602
+ }
6603
+ async function fetchWebsiteDomainNames(portalId) {
6604
+ const domains = await fetchDomains(portalId);
6605
+ const filteredDomains = domains.filter((domain2) => {
6606
+ return domain2.isUsedForBlogPost || domain2.isUsedForSitePage || domain2.isUsedForLandingPage;
6323
6607
  });
6324
- const validImports = Array.from(
6325
- new Set(imports.filter((name) => !INVALID_IMPORTS.includes(name)))
6326
- );
6327
- return { types, imports: validImports };
6608
+ const domainNames = filteredDomains.map((r) => r.domain);
6609
+ return domainNames;
6328
6610
  }
6329
- function constructFinalType(fields, typeName) {
6330
- const { types, imports } = getFieldTypes(fields);
6331
- const baseType = ts.factory.createTypeAliasDeclaration(
6332
- [],
6333
- [],
6334
- "",
6335
- void 0,
6336
- ts.factory.createTypeLiteralNode(types)
6337
- );
6338
- const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
6339
- baseType.type
6340
- ]);
6341
- const finalType = ts.factory.createTypeAliasDeclaration(
6342
- [],
6343
- [],
6344
- typeName,
6345
- void 0,
6346
- wrappedType
6347
- );
6348
- const filteredImports = filterUnusedImports(imports, finalType);
6349
- const importDeclaration = getImportDeclaration(
6350
- [...filteredImports, DEFAULT_VALUES_TYPE],
6351
- CMS_COMPONENTS_FIELD_TYPES
6352
- );
6353
- const defaultExport = ts.factory.createExportDefault(
6354
- ts.factory.createIdentifier(typeName)
6355
- );
6356
- return [importDeclaration, finalType, defaultExport];
6611
+
6612
+ // src/lib/validateHSPlatform.ts
6613
+ import path19 from "path";
6614
+ import fs11 from "fs";
6615
+ import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
6616
+ var HSPROJECT_JSON = "hsproject.json";
6617
+ function checkFileExists(filePath) {
6618
+ return fs11.existsSync(filePath) && fs11.statSync(filePath).isFile();
6357
6619
  }
6358
- function writeFieldsType(fields, fileName, typeName) {
6359
- const entries = getFieldEntries(fields);
6360
- if (!entries) {
6361
- return false;
6620
+ function findHSProjectJson(startPath) {
6621
+ let currentDir = startPath;
6622
+ let dirLevel = 0;
6623
+ const maxDirLevel = 4;
6624
+ while (path19.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
6625
+ const filePath = path19.join(currentDir, HSPROJECT_JSON);
6626
+ if (checkFileExists(filePath)) {
6627
+ return filePath;
6628
+ }
6629
+ currentDir = path19.dirname(currentDir);
6630
+ dirLevel++;
6362
6631
  }
6363
- try {
6364
- const file = ts.createSourceFile(
6365
- fileName,
6366
- "",
6367
- ts.ScriptTarget.ESNext,
6368
- false,
6369
- ts.ScriptKind.TS
6370
- );
6371
- const printer = ts.createPrinter();
6372
- const nodes = constructFinalType(entries, typeName);
6373
- const comments = [
6374
- AUTO_GEN_COMMENT,
6375
- "Removing the above comment will disable type generation for this module",
6376
- "This file was created by @hubspot/cms-dev-server, for more information see https://github.hubspot.com/cms-react/reference/js-modules.html#module-fields"
6377
- ].map((comment) => `// ${comment}`);
6378
- const typeResult = nodes.map(
6379
- (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)
6632
+ console.log(
6633
+ `'${HSPROJECT_JSON}' not found in any parent of dev server target`
6634
+ );
6635
+ return null;
6636
+ }
6637
+ async function validateHSPlatform(projectConfigPath, portalId, deferSelection) {
6638
+ if (projectConfigPath === null) {
6639
+ console.log(
6640
+ `Unable to find local ${HSPROJECT_JSON}, skipping platform version validation.`
6380
6641
  );
6381
- const result = [...comments, ...typeResult].join("\n");
6382
- writeFileSync(fileName, result);
6383
- return true;
6384
- } catch (e) {
6385
- console.error(e);
6386
6642
  return false;
6387
6643
  }
6388
- }
6389
-
6390
- // src/lib/watchFieldsUpdates.ts
6391
- import fs9 from "fs";
6392
- import path17 from "path";
6393
- import readline from "readline";
6394
- var lastSerializedFieldsCache = {};
6395
- var formatAsTypeName = (str) => {
6396
- const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
6397
- const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
6398
- return validFirstChar ? typeName : `_${typeName}`;
6399
- };
6400
- var isInModulesFolder = (filePath, projectRoot) => {
6401
- const getEntryPathFromId = (id) => {
6402
- return id.startsWith(projectRoot) ? id.replace(`${projectRoot}${path17.sep}`, "") : "";
6403
- };
6404
- const currentModuleId = path17.normalize(filePath);
6405
- const moduleEntryPath = getEntryPathFromId(currentModuleId);
6406
- const subFolderTokens = moduleEntryPath.split(path17.sep);
6407
- return {
6408
- inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
6409
- isRootModuleFile: subFolderTokens.length === 3
6410
- };
6411
- };
6412
- var fileContainsAutoGenComment = async (filePath) => {
6413
- if (!fs9.existsSync(filePath))
6414
- return true;
6415
- const stream2 = fs9.createReadStream(filePath);
6416
- const reader = readline.createInterface({ input: stream2 });
6417
- const firstLine = await new Promise(
6418
- (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
6419
- );
6420
- reader.close();
6421
- stream2.close();
6422
- return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
6423
- };
6424
- var getIndexFile = (filePath, projectRoot) => {
6425
- const { inModuleFolder, isRootModuleFile } = isInModulesFolder(
6426
- filePath,
6427
- projectRoot
6428
- );
6429
- if (!inModuleFolder)
6430
- return void 0;
6431
- if (isRootModuleFile)
6432
- return { indexFilePath: filePath, isRootModuleFile };
6433
- const dir = path17.dirname(filePath);
6434
- const files = fs9.readdirSync(dir);
6435
- const indexFileName = files.find((file) => file.startsWith("index."));
6436
- return indexFileName ? { indexFilePath: path17.join(dir, indexFileName), isRootModuleFile } : void 0;
6437
- };
6438
- var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
6439
- let indexFile;
6440
- let renderFieldsToJson;
6644
+ const hsProjectJSONContents = fs11.readFileSync(projectConfigPath, "utf8");
6645
+ const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
6646
+ const { platformVersion } = hsProjectJSONData;
6647
+ let platformVersionResult;
6441
6648
  try {
6442
- indexFile = await viteServer.ssrLoadModule(indexFilePath);
6443
- const internalSsrPath = packagePath(import.meta.url, "internalSsr");
6444
- ({ renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath));
6649
+ platformVersionResult = (await hsCliHttp12.get(portalId, {
6650
+ url: `developer/projects/v1/platformVersion`,
6651
+ responseType: "json"
6652
+ })).data;
6445
6653
  } catch (e) {
6446
- return void 0;
6654
+ console.error(e.message);
6655
+ console.log(
6656
+ "Unable to find active platform versions, skipping platform version validation."
6657
+ );
6658
+ return false;
6447
6659
  }
6448
- if (!indexFile.fields)
6449
- return void 0;
6450
- const fields = indexFile.fields;
6451
- const renderedFieldsJson = renderFieldsToJson(fields, indexFileName);
6452
- const isValidFields = Array.isArray(renderedFieldsJson);
6453
- return isValidFields ? renderedFieldsJson : void 0;
6454
- };
6455
- var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
6456
- const indexInfo = getIndexFile(filePath, projectRoot);
6457
- if (!indexInfo)
6458
- return;
6459
- const { indexFilePath, isRootModuleFile } = indexInfo;
6460
- const indexFileName = path17.parse(indexFilePath).name;
6461
- const isTypeFile = filePath.endsWith(".types.ts");
6462
- if (isTypeFile)
6463
- return;
6464
- const fields = await getIndexFileFields(
6465
- indexFilePath,
6466
- indexFileName,
6467
- viteServer
6468
- );
6469
- if (fields) {
6470
- const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
6471
- const typeFilePath = path17.join(path17.dirname(filePath), typeFileName);
6472
- const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
6473
- const serializedFields = JSON.stringify(fields);
6474
- if (lastSerializedFields === serializedFields)
6475
- return;
6476
- const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
6477
- if (!hasAutoGenComment)
6478
- return;
6479
- const moduleFolderName = path17.basename(path17.dirname(filePath));
6480
- const outputTypeName = formatAsTypeName(moduleFolderName);
6481
- const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
6482
- if (didSucceed) {
6483
- lastSerializedFieldsCache[typeFilePath] = serializedFields;
6660
+ if (platformVersion === void 0 || !platformVersionResult.activePlatformVersions.includes(platformVersion)) {
6661
+ const promptAndWrite = async () => {
6662
+ const { default: select } = await import("@inquirer/select");
6663
+ const answer = await select({
6664
+ message: 'Your local "hsproject.json" does not have a valid platform version, please select a valid platform version. You can read more about Platform Versioning here https://developers.hubspot.com/docs/platform/platform-versioning',
6665
+ choices: platformVersionResult.activePlatformVersions.map(
6666
+ (versionNumber) => ({
6667
+ name: versionNumber,
6668
+ value: versionNumber
6669
+ })
6670
+ )
6671
+ });
6672
+ hsProjectJSONData.platformVersion = answer;
6673
+ try {
6674
+ fs11.writeFileSync(
6675
+ projectConfigPath,
6676
+ JSON.stringify(hsProjectJSONData, void 0, 2),
6677
+ "utf8"
6678
+ );
6679
+ return true;
6680
+ } catch (e) {
6681
+ console.error(
6682
+ `unable to write updated valid platform version, please make sure platformVersion in "${HSPROJECT_JSON}" is one of ${platformVersionResult.activePlatformVersions}`
6683
+ );
6684
+ return false;
6685
+ }
6686
+ };
6687
+ if (deferSelection) {
6688
+ deferSelection(promptAndWrite);
6689
+ return false;
6484
6690
  }
6485
- const pathToLog = isRootModuleFile ? `${moduleFolderName}/${indexFileName}` : moduleFolderName;
6486
- const successMsg = `Successfully generated types for ${pathToLog}`;
6487
- const errorMsg = `Failed to generate types for ${pathToLog}`;
6488
- const message = didSucceed ? successMsg : errorMsg;
6489
- console.log(wrapMessageInColor(didSucceed ? "green" : "red", message));
6691
+ return promptAndWrite();
6490
6692
  }
6491
- };
6492
- var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
6493
- const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
6494
- moduleSubpaths.forEach((modulePath) => {
6495
- const resolvedPath = path17.resolve(projectRoot, modulePath);
6496
- maybeUpdateFields(resolvedPath, viteServer, projectRoot);
6497
- });
6498
- const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
6499
- viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
6500
- };
6693
+ return true;
6694
+ }
6695
+
6696
+ // src/createDevServer.ts
6697
+ import { http as hsCliHttp13 } from "@hubspot/local-dev-lib/http";
6501
6698
 
6502
6699
  // src/lib/configHelpers.ts
6503
6700
  function getSecretNamesFromConfig(config) {
@@ -6524,8 +6721,8 @@ function getWebRootProjectComponentFolder(absoluteWebRoot, projectConfigPath) {
6524
6721
  return themeFolderName;
6525
6722
  }
6526
6723
  try {
6527
- const projectDir = path18.dirname(projectConfigPath);
6528
- const configContent = fs10.readFileSync(projectConfigPath, "utf8");
6724
+ const projectDir = path20.dirname(projectConfigPath);
6725
+ const configContent = fs12.readFileSync(projectConfigPath, "utf8");
6529
6726
  const projectConfig = JSON.parse(configContent);
6530
6727
  if (hasNewDirectoryStructure(projectConfig.platformVersion)) {
6531
6728
  const srcDir = projectConfig.srcDir || "src";
@@ -6595,7 +6792,7 @@ Local proxy functionality and module preview routes will not work without settin
6595
6792
  }
6596
6793
  setTrackingInfo(authedPortalId, authedEnv);
6597
6794
  sendTrackingRequest("start-dev-server");
6598
- const absoluteWebRoot = normalizePath10(path18.resolve(process.cwd(), webRoot2));
6795
+ const absoluteWebRoot = normalizePath10(path20.resolve(process.cwd(), webRoot2));
6599
6796
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
6600
6797
  const webRootProjectComponentFolder = getWebRootProjectComponentFolder(
6601
6798
  absoluteWebRoot,
@@ -6667,7 +6864,7 @@ Local proxy functionality and module preview routes will not work without settin
6667
6864
  });
6668
6865
  bootTasks.push(async () => {
6669
6866
  try {
6670
- const accountInformation = (await hsCliHttp12.get(portalId, {
6867
+ const accountInformation = (await hsCliHttp13.get(portalId, {
6671
6868
  url: "/account-info/v3/details"
6672
6869
  })).data;
6673
6870
  authedHublet = accountInformation.dataHostingLocation;
@@ -6709,7 +6906,7 @@ Local proxy functionality and module preview routes will not work without settin
6709
6906
  secretNames
6710
6907
  );
6711
6908
  if (fieldGenEnabledOption2) {
6712
- const normalizedAbsoluteWebRoot = path18.normalize(absoluteWebRoot);
6909
+ const normalizedAbsoluteWebRoot = path20.normalize(absoluteWebRoot);
6713
6910
  startFieldsTypeGenWatcher(viteServer, normalizedAbsoluteWebRoot);
6714
6911
  }
6715
6912
  const viteHTTPSConfig = viteServer.config.server.https;
@@ -6735,10 +6932,10 @@ Local proxy functionality and module preview routes will not work without settin
6735
6932
  expressServer.locals.sslEnabled = sslEnabledOption2;
6736
6933
  expressServer.locals.fullHeightPreview = fullHeightPreview;
6737
6934
  expressServer.use(bodyParser.json());
6738
- const __dirname = path18.dirname(url2.fileURLToPath(new URL(import.meta.url)));
6739
- let appWebRoot = normalizePath10(path18.resolve(__dirname, "../app"));
6935
+ const __dirname = path20.dirname(url2.fileURLToPath(new URL(import.meta.url)));
6936
+ let appWebRoot = normalizePath10(path20.resolve(__dirname, "../app"));
6740
6937
  if (true) {
6741
- appWebRoot = path18.join(__dirname, "app");
6938
+ appWebRoot = path20.join(__dirname, "app");
6742
6939
  }
6743
6940
  const skipUiServer = isLocalUiDisabled(cmsAssetConfig);
6744
6941
  const appViteServer = skipUiServer ? null : await createAppServer_default(appWebRoot, PORT, sslEnabledOption2);
@@ -6806,17 +7003,17 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
6806
7003
  `;
6807
7004
  console.log(startMessage);
6808
7005
  if (storybook2) {
6809
- const packageRoot = path18.dirname(url2.fileURLToPath(import.meta.url));
6810
- const configPath = path18.resolve(packageRoot, "./storybook-main");
7006
+ const packageRoot = path20.dirname(url2.fileURLToPath(import.meta.url));
7007
+ const configPath = path20.resolve(packageRoot, "./storybook-main");
6811
7008
  sendTrackingRequest("start-storybook");
6812
7009
  let storybookBin;
6813
7010
  try {
6814
7011
  const sbPackagePath = await import.meta.resolve("storybook/package.json");
6815
- const sbPackageDir = path18.dirname(url2.fileURLToPath(sbPackagePath));
7012
+ const sbPackageDir = path20.dirname(url2.fileURLToPath(sbPackagePath));
6816
7013
  const packageJson = JSON.parse(
6817
- fs10.readFileSync(path18.join(sbPackageDir, "package.json"), "utf-8")
7014
+ fs12.readFileSync(path20.join(sbPackageDir, "package.json"), "utf-8")
6818
7015
  );
6819
- storybookBin = path18.join(
7016
+ storybookBin = path20.join(
6820
7017
  sbPackageDir,
6821
7018
  packageJson.bin.storybook || packageJson.bin
6822
7019
  );
@@ -6853,7 +7050,7 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
6853
7050
  portalId: authedPortalId.toString(),
6854
7051
  hsEnv: authedEnv,
6855
7052
  hublet: authedHublet,
6856
- WEB_ROOT: path18.join(webRoot2, "components")
7053
+ WEB_ROOT: path20.join(webRoot2, "components")
6857
7054
  },
6858
7055
  stdio: "inherit"
6859
7056
  }