@hubspot/cms-dev-server 1.2.80 → 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.80",
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
  }
@@ -5479,7 +6021,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
5479
6021
  var createViteDevServer_default = createViteDevServer;
5480
6022
 
5481
6023
  // src/lib/getDevServerUIData.ts
5482
- import fs6 from "node:fs";
6024
+ import fs9 from "node:fs";
5483
6025
  var templateTypeMap = {
5484
6026
  // Standard templates
5485
6027
  4: "Page",
@@ -5505,7 +6047,7 @@ function mapReactModules(modules, themeWebRoot, appViteServer) {
5505
6047
  return Promise.all(
5506
6048
  modules.moduleNames.map(async (name, index) => {
5507
6049
  const modulePath = normalizePath9(
5508
- path13.resolve(themeWebRoot, "components/modules/", name)
6050
+ path16.resolve(themeWebRoot, "components/modules/", name)
5509
6051
  );
5510
6052
  const fieldsJson = await renderModuleFieldsJson_default(
5511
6053
  appViteServer,
@@ -5551,9 +6093,9 @@ function normalizeTemplatesData(templates, projectName) {
5551
6093
  });
5552
6094
  }
5553
6095
  function detectPackageManager(projectRoot) {
5554
- if (fs6.existsSync(path13.join(projectRoot, "yarn.lock")))
6096
+ if (fs9.existsSync(path16.join(projectRoot, "yarn.lock")))
5555
6097
  return "yarn";
5556
- if (fs6.existsSync(path13.join(projectRoot, "pnpm-lock.yaml")))
6098
+ if (fs9.existsSync(path16.join(projectRoot, "pnpm-lock.yaml")))
5557
6099
  return "pnpm";
5558
6100
  return "npm";
5559
6101
  }
@@ -5637,10 +6179,10 @@ var appServerRouteHandler = async (req, res, __next) => {
5637
6179
  const { appWebRoot, appViteServer } = appLocals;
5638
6180
  const initialProps = await getDevServerUIData(appLocals);
5639
6181
  const url3 = req.originalUrl.replace("/", "");
5640
- const templatePath = path14.join(appWebRoot, "index.html");
5641
- 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");
5642
6184
  let render;
5643
- let template = await fs7.readFile(path14.join(templatePath), "utf-8");
6185
+ let template = await fs10.readFile(path17.join(templatePath), "utf-8");
5644
6186
  if (isProd) {
5645
6187
  const { render: ssrRender } = await import(pathToFileURL(serverEntryPath).href);
5646
6188
  render = ssrRender;
@@ -5671,7 +6213,7 @@ var appServerRouteHandler = async (req, res, __next) => {
5671
6213
  var appServerRouteHandler_default = appServerRouteHandler;
5672
6214
 
5673
6215
  // src/routes/createDevServerRoutes.ts
5674
- import path15 from "path";
6216
+ import path18 from "path";
5675
6217
  var isProd2 = true;
5676
6218
  var STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(
5677
6219
  (domain2) => `storybook.${domain2}`
@@ -5698,7 +6240,7 @@ var createDevServerRoutes = async (viteServer, appLocals, storybookPort) => {
5698
6240
  }
5699
6241
  devServerApp.use(urlencoded());
5700
6242
  if (isProd2) {
5701
- const distAssetsPath = path15.join(appWebRoot, "assets");
6243
+ const distAssetsPath = path18.join(appWebRoot, "assets");
5702
6244
  devServerApp.use("/assets", expressStatic(distAssetsPath));
5703
6245
  } else if (appViteServer) {
5704
6246
  devServerApp.use("/local", appViteServer.middlewares);
@@ -5722,6 +6264,10 @@ var createDevServerRoutes = async (viteServer, appLocals, storybookPort) => {
5722
6264
  moduleFieldsJson_default
5723
6265
  );
5724
6266
  devServerApp.get("/module/:moduleName/*", module_default);
6267
+ devServerApp.post(
6268
+ "/preview/module/:moduleName/validate-fields",
6269
+ moduleValidateFields_default
6270
+ );
5725
6271
  devServerApp.post("/preview/module/:moduleName", modulePreviewRouteHandler_default);
5726
6272
  devServerApp.get("/hublmodule/:modulePath(*)", hublModuleRouteHandler);
5727
6273
  devServerApp.get("/template/:templatePath(*)", templateRouteHandler);
@@ -5935,575 +6481,220 @@ function createHttpsRedirectingServer(opts, handler) {
5935
6481
  "Unknown issue with incoming data, unknown if http or https"
5936
6482
  );
5937
6483
  }
5938
- const proxy = protocol === "http" ? innerHTTPServer : innerHTTPSServer;
5939
- if (proxy) {
5940
- socket.unshift(buffer);
5941
- proxy.emit("connection", socket);
5942
- }
5943
- process.nextTick(() => socket.resume());
5944
- });
5945
- });
5946
- return { server, innerHTTPServer, innerHTTPSServer };
5947
- }
5948
-
5949
- // src/lib/getJSRenderingGates.ts
5950
- import { getAccessToken } from "@hubspot/local-dev-lib/personalAccessKey";
5951
-
5952
- // src/lib/gates.ts
5953
- function getGatesFromEnv() {
5954
- const gates = process.env.GATES ? process.env.GATES.split(",") : [];
5955
- return gates;
5956
- }
5957
-
5958
- // src/lib/getJSRenderingGates.ts
5959
- var mapEnabledFeaturesToGates = (enabledFeatures) => {
5960
- return Object.keys(enabledFeatures).reduce((gates, enabledFeature) => {
5961
- if (enabledFeatures[enabledFeature]) {
5962
- gates.push(ENABLED_FEATURES_GATE_MAP[enabledFeature]);
5963
- }
5964
- return gates;
5965
- }, []);
5966
- };
5967
- async function getJsRenderingGates(portalId, env2, personalAccessKey) {
5968
- const { enabledFeatures } = await getAccessToken(personalAccessKey, env2, portalId);
5969
- const envGates = getGatesFromEnv();
5970
- const gates = mapEnabledFeaturesToGates(enabledFeatures);
5971
- const mergedGates = [...envGates, ...gates];
5972
- process.env.GATES = mergedGates.join(",");
5973
- return mergedGates;
5974
- }
5975
-
5976
- // src/createDevServer.ts
5977
- import {
5978
- getConfigAccountIfExists as getConfigAccountIfExists8,
5979
- getConfigDefaultAccountIfExists,
5980
- validateConfig
5981
- } from "@hubspot/local-dev-lib/config";
5982
- import { fetchSecrets } from "@hubspot/local-dev-lib/api/secrets";
5983
- import { PERSONAL_ACCESS_KEY_AUTH_METHOD } from "@hubspot/local-dev-lib/constants/auth";
5984
-
5985
- // src/proxyPage/fetchDomains.ts
5986
- import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
5987
-
5988
- // src/lib/errors.ts
5989
- var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
5990
- 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
5991
- `;
5992
- var OAUTH_ERROR_REGEX = /^This oauth-token \([\w]+\) does not have proper permissions!/;
5993
- var NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;
5994
- var MissingScopeError = class extends Error {
5995
- constructor(error) {
5996
- let messageEnd = "";
5997
- if (error.error.message.match(OAUTH_ERROR_REGEX)) {
5998
- messageEnd = error.error.message;
5999
- }
6000
- super(`${MISSING_SCOPE_ERROR_PREFIX}
6001
- ${messageEnd}`);
6002
- Object.setPrototypeOf(this, MissingScopeError.prototype);
6003
- }
6004
- };
6005
- function logMissingScopeWarning(error) {
6006
- console.warn(error.message);
6007
- }
6008
- function isMissingScopeError2(error) {
6009
- return error.statusCode === 403 && (error.error.message.match(OAUTH_ERROR_REGEX) || error.error.message.startsWith(NOT_PUBLIC_USE_ERROR));
6010
- }
6011
- function handleSecretsError(error) {
6012
- if (error && error.statusCode && error.error) {
6013
- const { statusCode, error: errorDetails } = error;
6014
- if ((errorDetails == null ? void 0 : errorDetails.category) === "MISSING_SCOPES") {
6015
- console.log(
6016
- "\nMissing scopes for secrets.",
6017
- "\nSecrets require Serverless functions which are scoped to Enterprise portals.\n"
6018
- );
6019
- } else {
6020
- console.error(`Error ${statusCode}: ${errorDetails.message}`);
6021
- if (errorDetails.correlationId) {
6022
- console.error(`Correlation ID: ${errorDetails.correlationId}`);
6023
- }
6024
- if (errorDetails.category) {
6025
- console.error(`Category: ${errorDetails.category}`);
6026
- }
6027
- if (errorDetails.links) {
6028
- if (errorDetails.links.support) {
6029
- console.error(`Support URL: ${errorDetails.links.support}`);
6030
- }
6031
- if (errorDetails.links.forum) {
6032
- console.error(`Forum URL: ${errorDetails.links.forum}`);
6033
- }
6034
- }
6035
- }
6036
- } else {
6037
- console.error("Unexpected error structure:", error);
6038
- }
6039
- }
6040
-
6041
- // src/proxyPage/fetchDomains.ts
6042
- async function fetchDomains(portalId) {
6043
- try {
6044
- const result = (await hsCliHttp10.get(portalId, {
6045
- url: `/cms/v3/domains`,
6046
- params: { portalId },
6047
- responseType: "json"
6048
- })).data;
6049
- return result.results;
6050
- } catch (error) {
6051
- if (isMissingScopeError2(error)) {
6052
- throw new MissingScopeError(error);
6053
- }
6054
- throw error;
6055
- }
6056
- }
6057
- async function fetchWebsiteDomainNames(portalId) {
6058
- const domains = await fetchDomains(portalId);
6059
- const filteredDomains = domains.filter((domain2) => {
6060
- return domain2.isUsedForBlogPost || domain2.isUsedForSitePage || domain2.isUsedForLandingPage;
6061
- });
6062
- const domainNames = filteredDomains.map((r) => r.domain);
6063
- return domainNames;
6064
- }
6065
-
6066
- // src/lib/validateHSPlatform.ts
6067
- import path16 from "path";
6068
- import fs8 from "fs";
6069
- import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
6070
- var HSPROJECT_JSON = "hsproject.json";
6071
- function checkFileExists(filePath) {
6072
- return fs8.existsSync(filePath) && fs8.statSync(filePath).isFile();
6073
- }
6074
- function findHSProjectJson(startPath) {
6075
- let currentDir = startPath;
6076
- let dirLevel = 0;
6077
- const maxDirLevel = 4;
6078
- while (path16.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
6079
- const filePath = path16.join(currentDir, HSPROJECT_JSON);
6080
- if (checkFileExists(filePath)) {
6081
- return filePath;
6082
- }
6083
- currentDir = path16.dirname(currentDir);
6084
- dirLevel++;
6085
- }
6086
- console.log(
6087
- `'${HSPROJECT_JSON}' not found in any parent of dev server target`
6088
- );
6089
- return null;
6090
- }
6091
- async function validateHSPlatform(projectConfigPath, portalId, deferSelection) {
6092
- if (projectConfigPath === null) {
6093
- console.log(
6094
- `Unable to find local ${HSPROJECT_JSON}, skipping platform version validation.`
6095
- );
6096
- return false;
6097
- }
6098
- const hsProjectJSONContents = fs8.readFileSync(projectConfigPath, "utf8");
6099
- const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
6100
- const { platformVersion } = hsProjectJSONData;
6101
- let platformVersionResult;
6102
- try {
6103
- platformVersionResult = (await hsCliHttp11.get(portalId, {
6104
- url: `developer/projects/v1/platformVersion`,
6105
- responseType: "json"
6106
- })).data;
6107
- } catch (e) {
6108
- console.error(e.message);
6109
- console.log(
6110
- "Unable to find active platform versions, skipping platform version validation."
6111
- );
6112
- return false;
6113
- }
6114
- if (platformVersion === void 0 || !platformVersionResult.activePlatformVersions.includes(platformVersion)) {
6115
- const promptAndWrite = async () => {
6116
- const { default: select } = await import("@inquirer/select");
6117
- const answer = await select({
6118
- 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',
6119
- choices: platformVersionResult.activePlatformVersions.map(
6120
- (versionNumber) => ({
6121
- name: versionNumber,
6122
- value: versionNumber
6123
- })
6124
- )
6125
- });
6126
- hsProjectJSONData.platformVersion = answer;
6127
- try {
6128
- fs8.writeFileSync(
6129
- projectConfigPath,
6130
- JSON.stringify(hsProjectJSONData, void 0, 2),
6131
- "utf8"
6132
- );
6133
- return true;
6134
- } catch (e) {
6135
- console.error(
6136
- `unable to write updated valid platform version, please make sure platformVersion in "${HSPROJECT_JSON}" is one of ${platformVersionResult.activePlatformVersions}`
6137
- );
6138
- return false;
6139
- }
6140
- };
6141
- if (deferSelection) {
6142
- deferSelection(promptAndWrite);
6143
- 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]);
6144
6509
  }
6145
- return promptAndWrite();
6146
- }
6147
- 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;
6148
6520
  }
6149
6521
 
6150
6522
  // src/createDevServer.ts
6151
- 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";
6152
6530
 
6153
- // ../cms-js-internal/dist/buildFieldsTypes.js
6154
- import { writeFileSync } from "fs";
6155
- import ts from "typescript";
6156
- var fieldTypeNameByType = {
6157
- alignment: "AlignmentFieldType",
6158
- audioplayer: "AudioFieldType",
6159
- backgroundimage: "BackgroundImageFieldType",
6160
- blog: "BlogFieldType",
6161
- boolean: "BooleanFieldType",
6162
- border: "BorderFieldType",
6163
- choice: "ChoiceFieldType",
6164
- color: "ColorFieldType",
6165
- crmobject: "CrmObjectFieldType",
6166
- cta: "CtaFieldType",
6167
- date: "DateFieldType",
6168
- datetime: "DateTimeFieldType",
6169
- email: "EmailFieldType",
6170
- embed: "EmbedFieldType",
6171
- file: "FileFieldType",
6172
- followupemail: "FollowUpEmailFieldType",
6173
- font: "FontFieldType",
6174
- form: "FormFieldType",
6175
- gradient: "GradientFieldType",
6176
- group: "GroupFieldType",
6177
- html: "HtmlFieldType",
6178
- hubdbrow: "HubDbRowFieldType",
6179
- hubdbtable: "HubDbTableFieldType",
6180
- hubl: "HublFieldType",
6181
- icon: "IconFieldType",
6182
- image: "ImageFieldType",
6183
- link: "LinkFieldType",
6184
- logo: "LogoFieldType",
6185
- meeting: "MeetingFieldType",
6186
- menu: "MenuFieldType",
6187
- number: "NumberFieldType",
6188
- page: "PageFieldType",
6189
- payment: "PaymentFieldType",
6190
- podcast: "PodcastFieldType",
6191
- richtext: "RichTextFieldType",
6192
- salesforcecampaign: "SfdcCamapaignFieldType",
6193
- simplemenu: "SimpleMenuFieldType",
6194
- spacing: "SpacingFieldType",
6195
- survey: "SurveyFieldType",
6196
- tag: "TagFieldType",
6197
- textalignment: "TextAlignmentFieldType",
6198
- text: "TextFieldType",
6199
- url: "UrlFieldType",
6200
- variantselection: "VariantSelectionFieldType",
6201
- videoplayer: "VideoFieldType",
6202
- workflow: "WorkflowFieldType"
6203
- };
6204
- function getFieldEntries(fields) {
6205
- if (!Array.isArray(fields)) {
6206
- return void 0;
6207
- }
6208
- return fields.filter((field) => field.name && field.type).map((field) => {
6209
- const { name, type } = field;
6210
- const fieldType = fieldTypeNameByType[type];
6211
- if (!fieldType) {
6212
- return void 0;
6213
- }
6214
- const entry = {
6215
- type: fieldType,
6216
- name,
6217
- isRepeater: "occurrence" in field,
6218
- isRequired: !!field.required,
6219
- choices: (
6220
- // Choices are pair [value, label] but only the value is printed to the page, so flatten it.
6221
- "choices" in field ? field.choices.map(([value, label]) => value) : void 0
6222
- ),
6223
- children: []
6224
- };
6225
- if (fieldType === "GroupFieldType" && "children" in field) {
6226
- const children = getFieldEntries(field.children);
6227
- 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;
6228
6545
  }
6229
- return entry;
6230
- }).filter((entry) => entry !== void 0);
6231
- }
6232
- var INVALID_IMPORTS = ["ChoiceFieldType", "GroupFieldType"];
6233
- var FIELD_GROUP_TYPE = "FieldGroupWithChildren";
6234
- var REPEATER_GROUP_TYPE = "RepeaterGroup";
6235
- var REQUIRED_TYPE = "RequiredField";
6236
- var DEFAULT_VALUES_TYPE = "DefaultValues";
6237
- var CMS_COMPONENTS = "@hubspot/cms-components";
6238
- var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
6239
- var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
6240
- var createPropertySignature = (identifier, type, hasQuestionToken = false) => ts.factory.createPropertySignature(
6241
- [],
6242
- identifier,
6243
- hasQuestionToken ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0,
6244
- type
6245
- );
6246
- var createUnionTypeFromArray = (values) => ts.factory.createUnionTypeNode(
6247
- values.map(
6248
- (value) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value))
6249
- )
6250
- );
6251
- var buildTypeFromField = (field, additionalNode) => {
6252
- const imports = [field.type];
6253
- const identifier = ts.factory.createIdentifier(field.name);
6254
- const baseType = ts.factory.createTypeReferenceNode(field.type);
6255
- const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
6256
- baseType
6257
- ]);
6258
- let finalType = field.isRequired ? requiredType : baseType;
6259
- if (field.choices) {
6260
- finalType = createUnionTypeFromArray(field.choices);
6261
- }
6262
- if (field.isRequired) {
6263
- imports.push(REQUIRED_TYPE);
6264
- }
6265
- if (additionalNode) {
6266
- const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
6267
- const genericType = field.isRepeater ? REPEATER_GROUP_TYPE : FIELD_GROUP_TYPE;
6268
- imports.push(genericType);
6269
- finalType = ts.factory.createTypeReferenceNode(genericType, [typeLiteral]);
6546
+ super(`${MISSING_SCOPE_ERROR_PREFIX}
6547
+ ${messageEnd}`);
6548
+ Object.setPrototypeOf(this, MissingScopeError.prototype);
6270
6549
  }
6271
- return {
6272
- type: createPropertySignature(
6273
- identifier,
6274
- finalType,
6275
- !field.isRequired && !additionalNode
6276
- ),
6277
- imports
6278
- };
6279
6550
  };
6280
- var filterUnusedImports = (imports, type) => {
6281
- const usedImports = /* @__PURE__ */ new Set();
6282
- const visit = (node) => {
6283
- if (ts.isTypeReferenceNode(node)) {
6284
- const typeName = node.typeName;
6285
- if ("escapedText" in typeName) {
6286
- usedImports.add(typeName.escapedText.toString());
6287
- }
6288
- }
6289
- ts.forEachChild(node, visit);
6290
- };
6291
- visit(type);
6292
- return imports.filter((name) => usedImports.has(name));
6293
- };
6294
- function getImportDeclaration(imports, moduleSpecifier) {
6295
- const importSpecifiers = Array.from(imports).map(
6296
- (importName) => ts.factory.createImportSpecifier(
6297
- true,
6298
- void 0,
6299
- ts.factory.createIdentifier(importName)
6300
- )
6301
- );
6302
- const namedImports = ts.factory.createNamedImports(importSpecifiers);
6303
- return ts.factory.createImportDeclaration(
6304
- [],
6305
- [],
6306
- ts.factory.createImportClause(false, void 0, namedImports),
6307
- ts.factory.createStringLiteral(moduleSpecifier)
6308
- );
6551
+ function logMissingScopeWarning(error) {
6552
+ console.warn(error.message);
6309
6553
  }
6310
- function getFieldTypes(fields) {
6311
- const imports = [];
6312
- const types = fields.map((field) => {
6313
- if (field.children) {
6314
- const childrenResult = getFieldTypes(field.children);
6315
- imports.push(...childrenResult.imports);
6316
- if (childrenResult.types.length || field.type === "GroupFieldType") {
6317
- const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
6318
- const { type: type2, imports: newImports2 } = buildTypeFromField(
6319
- field,
6320
- subType
6321
- );
6322
- imports.push(...newImports2);
6323
- 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
+ }
6324
6580
  }
6325
6581
  }
6326
- const { type, imports: newImports } = buildTypeFromField(field);
6327
- imports.push(...newImports);
6328
- 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;
6329
6607
  });
6330
- const validImports = Array.from(
6331
- new Set(imports.filter((name) => !INVALID_IMPORTS.includes(name)))
6332
- );
6333
- return { types, imports: validImports };
6608
+ const domainNames = filteredDomains.map((r) => r.domain);
6609
+ return domainNames;
6334
6610
  }
6335
- function constructFinalType(fields, typeName) {
6336
- const { types, imports } = getFieldTypes(fields);
6337
- const baseType = ts.factory.createTypeAliasDeclaration(
6338
- [],
6339
- [],
6340
- "",
6341
- void 0,
6342
- ts.factory.createTypeLiteralNode(types)
6343
- );
6344
- const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
6345
- baseType.type
6346
- ]);
6347
- const finalType = ts.factory.createTypeAliasDeclaration(
6348
- [],
6349
- [],
6350
- typeName,
6351
- void 0,
6352
- wrappedType
6353
- );
6354
- const filteredImports = filterUnusedImports(imports, finalType);
6355
- const importDeclaration = getImportDeclaration(
6356
- [...filteredImports, DEFAULT_VALUES_TYPE],
6357
- CMS_COMPONENTS_FIELD_TYPES
6358
- );
6359
- const defaultExport = ts.factory.createExportDefault(
6360
- ts.factory.createIdentifier(typeName)
6361
- );
6362
- 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();
6363
6619
  }
6364
- function writeFieldsType(fields, fileName, typeName) {
6365
- const entries = getFieldEntries(fields);
6366
- if (!entries) {
6367
- 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++;
6368
6631
  }
6369
- try {
6370
- const file = ts.createSourceFile(
6371
- fileName,
6372
- "",
6373
- ts.ScriptTarget.ESNext,
6374
- false,
6375
- ts.ScriptKind.TS
6376
- );
6377
- const printer = ts.createPrinter();
6378
- const nodes = constructFinalType(entries, typeName);
6379
- const comments = [
6380
- AUTO_GEN_COMMENT,
6381
- "Removing the above comment will disable type generation for this module",
6382
- "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"
6383
- ].map((comment) => `// ${comment}`);
6384
- const typeResult = nodes.map(
6385
- (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.`
6386
6641
  );
6387
- const result = [...comments, ...typeResult].join("\n");
6388
- writeFileSync(fileName, result);
6389
- return true;
6390
- } catch (e) {
6391
- console.error(e);
6392
6642
  return false;
6393
6643
  }
6394
- }
6395
-
6396
- // src/lib/watchFieldsUpdates.ts
6397
- import fs9 from "fs";
6398
- import path17 from "path";
6399
- import readline from "readline";
6400
- var lastSerializedFieldsCache = {};
6401
- var formatAsTypeName = (str) => {
6402
- const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
6403
- const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
6404
- return validFirstChar ? typeName : `_${typeName}`;
6405
- };
6406
- var isInModulesFolder = (filePath, projectRoot) => {
6407
- const getEntryPathFromId = (id) => {
6408
- return id.startsWith(projectRoot) ? id.replace(`${projectRoot}${path17.sep}`, "") : "";
6409
- };
6410
- const currentModuleId = path17.normalize(filePath);
6411
- const moduleEntryPath = getEntryPathFromId(currentModuleId);
6412
- const subFolderTokens = moduleEntryPath.split(path17.sep);
6413
- return {
6414
- inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
6415
- isRootModuleFile: subFolderTokens.length === 3
6416
- };
6417
- };
6418
- var fileContainsAutoGenComment = async (filePath) => {
6419
- if (!fs9.existsSync(filePath))
6420
- return true;
6421
- const stream2 = fs9.createReadStream(filePath);
6422
- const reader = readline.createInterface({ input: stream2 });
6423
- const firstLine = await new Promise(
6424
- (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
6425
- );
6426
- reader.close();
6427
- stream2.close();
6428
- return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
6429
- };
6430
- var getIndexFile = (filePath, projectRoot) => {
6431
- const { inModuleFolder, isRootModuleFile } = isInModulesFolder(
6432
- filePath,
6433
- projectRoot
6434
- );
6435
- if (!inModuleFolder)
6436
- return void 0;
6437
- if (isRootModuleFile)
6438
- return { indexFilePath: filePath, isRootModuleFile };
6439
- const dir = path17.dirname(filePath);
6440
- const files = fs9.readdirSync(dir);
6441
- const indexFileName = files.find((file) => file.startsWith("index."));
6442
- return indexFileName ? { indexFilePath: path17.join(dir, indexFileName), isRootModuleFile } : void 0;
6443
- };
6444
- var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
6445
- let indexFile;
6446
- let renderFieldsToJson;
6644
+ const hsProjectJSONContents = fs11.readFileSync(projectConfigPath, "utf8");
6645
+ const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
6646
+ const { platformVersion } = hsProjectJSONData;
6647
+ let platformVersionResult;
6447
6648
  try {
6448
- indexFile = await viteServer.ssrLoadModule(indexFilePath);
6449
- const internalSsrPath = packagePath(import.meta.url, "internalSsr");
6450
- ({ renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath));
6649
+ platformVersionResult = (await hsCliHttp12.get(portalId, {
6650
+ url: `developer/projects/v1/platformVersion`,
6651
+ responseType: "json"
6652
+ })).data;
6451
6653
  } catch (e) {
6452
- 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;
6453
6659
  }
6454
- if (!indexFile.fields)
6455
- return void 0;
6456
- const fields = indexFile.fields;
6457
- const renderedFieldsJson = renderFieldsToJson(fields, indexFileName);
6458
- const isValidFields = Array.isArray(renderedFieldsJson);
6459
- return isValidFields ? renderedFieldsJson : void 0;
6460
- };
6461
- var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
6462
- const indexInfo = getIndexFile(filePath, projectRoot);
6463
- if (!indexInfo)
6464
- return;
6465
- const { indexFilePath, isRootModuleFile } = indexInfo;
6466
- const indexFileName = path17.parse(indexFilePath).name;
6467
- const isTypeFile = filePath.endsWith(".types.ts");
6468
- if (isTypeFile)
6469
- return;
6470
- const fields = await getIndexFileFields(
6471
- indexFilePath,
6472
- indexFileName,
6473
- viteServer
6474
- );
6475
- if (fields) {
6476
- const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
6477
- const typeFilePath = path17.join(path17.dirname(filePath), typeFileName);
6478
- const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
6479
- const serializedFields = JSON.stringify(fields);
6480
- if (lastSerializedFields === serializedFields)
6481
- return;
6482
- const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
6483
- if (!hasAutoGenComment)
6484
- return;
6485
- const moduleFolderName = path17.basename(path17.dirname(filePath));
6486
- const outputTypeName = formatAsTypeName(moduleFolderName);
6487
- const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
6488
- if (didSucceed) {
6489
- 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;
6490
6690
  }
6491
- const pathToLog = isRootModuleFile ? `${moduleFolderName}/${indexFileName}` : moduleFolderName;
6492
- const successMsg = `Successfully generated types for ${pathToLog}`;
6493
- const errorMsg = `Failed to generate types for ${pathToLog}`;
6494
- const message = didSucceed ? successMsg : errorMsg;
6495
- console.log(wrapMessageInColor(didSucceed ? "green" : "red", message));
6691
+ return promptAndWrite();
6496
6692
  }
6497
- };
6498
- var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
6499
- const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
6500
- moduleSubpaths.forEach((modulePath) => {
6501
- const resolvedPath = path17.resolve(projectRoot, modulePath);
6502
- maybeUpdateFields(resolvedPath, viteServer, projectRoot);
6503
- });
6504
- const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
6505
- viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
6506
- };
6693
+ return true;
6694
+ }
6695
+
6696
+ // src/createDevServer.ts
6697
+ import { http as hsCliHttp13 } from "@hubspot/local-dev-lib/http";
6507
6698
 
6508
6699
  // src/lib/configHelpers.ts
6509
6700
  function getSecretNamesFromConfig(config) {
@@ -6530,8 +6721,8 @@ function getWebRootProjectComponentFolder(absoluteWebRoot, projectConfigPath) {
6530
6721
  return themeFolderName;
6531
6722
  }
6532
6723
  try {
6533
- const projectDir = path18.dirname(projectConfigPath);
6534
- const configContent = fs10.readFileSync(projectConfigPath, "utf8");
6724
+ const projectDir = path20.dirname(projectConfigPath);
6725
+ const configContent = fs12.readFileSync(projectConfigPath, "utf8");
6535
6726
  const projectConfig = JSON.parse(configContent);
6536
6727
  if (hasNewDirectoryStructure(projectConfig.platformVersion)) {
6537
6728
  const srcDir = projectConfig.srcDir || "src";
@@ -6601,7 +6792,7 @@ Local proxy functionality and module preview routes will not work without settin
6601
6792
  }
6602
6793
  setTrackingInfo(authedPortalId, authedEnv);
6603
6794
  sendTrackingRequest("start-dev-server");
6604
- const absoluteWebRoot = normalizePath10(path18.resolve(process.cwd(), webRoot2));
6795
+ const absoluteWebRoot = normalizePath10(path20.resolve(process.cwd(), webRoot2));
6605
6796
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
6606
6797
  const webRootProjectComponentFolder = getWebRootProjectComponentFolder(
6607
6798
  absoluteWebRoot,
@@ -6673,7 +6864,7 @@ Local proxy functionality and module preview routes will not work without settin
6673
6864
  });
6674
6865
  bootTasks.push(async () => {
6675
6866
  try {
6676
- const accountInformation = (await hsCliHttp12.get(portalId, {
6867
+ const accountInformation = (await hsCliHttp13.get(portalId, {
6677
6868
  url: "/account-info/v3/details"
6678
6869
  })).data;
6679
6870
  authedHublet = accountInformation.dataHostingLocation;
@@ -6715,7 +6906,7 @@ Local proxy functionality and module preview routes will not work without settin
6715
6906
  secretNames
6716
6907
  );
6717
6908
  if (fieldGenEnabledOption2) {
6718
- const normalizedAbsoluteWebRoot = path18.normalize(absoluteWebRoot);
6909
+ const normalizedAbsoluteWebRoot = path20.normalize(absoluteWebRoot);
6719
6910
  startFieldsTypeGenWatcher(viteServer, normalizedAbsoluteWebRoot);
6720
6911
  }
6721
6912
  const viteHTTPSConfig = viteServer.config.server.https;
@@ -6741,10 +6932,10 @@ Local proxy functionality and module preview routes will not work without settin
6741
6932
  expressServer.locals.sslEnabled = sslEnabledOption2;
6742
6933
  expressServer.locals.fullHeightPreview = fullHeightPreview;
6743
6934
  expressServer.use(bodyParser.json());
6744
- const __dirname = path18.dirname(url2.fileURLToPath(new URL(import.meta.url)));
6745
- 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"));
6746
6937
  if (true) {
6747
- appWebRoot = path18.join(__dirname, "app");
6938
+ appWebRoot = path20.join(__dirname, "app");
6748
6939
  }
6749
6940
  const skipUiServer = isLocalUiDisabled(cmsAssetConfig);
6750
6941
  const appViteServer = skipUiServer ? null : await createAppServer_default(appWebRoot, PORT, sslEnabledOption2);
@@ -6812,17 +7003,17 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
6812
7003
  `;
6813
7004
  console.log(startMessage);
6814
7005
  if (storybook2) {
6815
- const packageRoot = path18.dirname(url2.fileURLToPath(import.meta.url));
6816
- 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");
6817
7008
  sendTrackingRequest("start-storybook");
6818
7009
  let storybookBin;
6819
7010
  try {
6820
7011
  const sbPackagePath = await import.meta.resolve("storybook/package.json");
6821
- const sbPackageDir = path18.dirname(url2.fileURLToPath(sbPackagePath));
7012
+ const sbPackageDir = path20.dirname(url2.fileURLToPath(sbPackagePath));
6822
7013
  const packageJson = JSON.parse(
6823
- fs10.readFileSync(path18.join(sbPackageDir, "package.json"), "utf-8")
7014
+ fs12.readFileSync(path20.join(sbPackageDir, "package.json"), "utf-8")
6824
7015
  );
6825
- storybookBin = path18.join(
7016
+ storybookBin = path20.join(
6826
7017
  sbPackageDir,
6827
7018
  packageJson.bin.storybook || packageJson.bin
6828
7019
  );
@@ -6859,7 +7050,7 @@ HubSpot CMS dev server running at ${protocol}://hslocal.net:${PORT}${extraServer
6859
7050
  portalId: authedPortalId.toString(),
6860
7051
  hsEnv: authedEnv,
6861
7052
  hublet: authedHublet,
6862
- WEB_ROOT: path18.join(webRoot2, "components")
7053
+ WEB_ROOT: path20.join(webRoot2, "components")
6863
7054
  },
6864
7055
  stdio: "inherit"
6865
7056
  }