@hubspot/cms-dev-server 1.2.50 → 1.2.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1651,7 +1651,7 @@ function trackUsage(action) {
1651
1651
  eventName: EVENT_NAME,
1652
1652
  action,
1653
1653
  nodeVersion: getNodeVersionData(),
1654
- version: "1.2.50",
1654
+ version: "1.2.60",
1655
1655
  os: getPlatform()
1656
1656
  };
1657
1657
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -2399,9 +2399,8 @@ function isModuleFolderChild(filePath) {
2399
2399
  import path4 from "path";
2400
2400
  var removePreviewPrefix = (t2) => t2.split("/").slice(2).join("/");
2401
2401
  var getPreviewUrl = (request, queryParams) => {
2402
- const { authedPortalId, authedEnv, authedHublet, sslEnabled } = request.app.locals;
2403
- const protocol = sslEnabled ? "https" : "http";
2404
- return `${protocol}://${authedPortalId}.hubspotpreview${authedEnv === "qa" ? "qa" : ""}-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;
2402
+ const { authedPortalId, authedEnv, authedHublet } = request.app.locals;
2403
+ return `https://${authedPortalId}.hubspotpreview${authedEnv === "qa" ? "qa" : ""}-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;
2405
2404
  };
2406
2405
  var buildHTMLResponse = (content) => {
2407
2406
  return `
@@ -3027,6 +3026,50 @@ async function fetchSignedModulePreview(signedUrl, authedEnv, cookieValue, postB
3027
3026
  return response.text();
3028
3027
  }
3029
3028
 
3029
+ // src/lib/extractRelevantCss.ts
3030
+ import postcss from "postcss";
3031
+ function isRelevantSelector(selector) {
3032
+ return selector.split(",").some(
3033
+ (part) => part.trim() === ":root" || /\[data-\w+-variant=/.test(part)
3034
+ );
3035
+ }
3036
+ function filterNodes(container) {
3037
+ const kept = [];
3038
+ container.each((node) => {
3039
+ if (node.type === "rule" && isRelevantSelector(node.selector)) {
3040
+ kept.push(node.clone());
3041
+ } else if (node.type === "atrule") {
3042
+ const children = filterNodes(node);
3043
+ if (children.length > 0) {
3044
+ const cloned = node.clone({ nodes: [] });
3045
+ for (const child of children) {
3046
+ cloned.append(child);
3047
+ }
3048
+ kept.push(cloned);
3049
+ }
3050
+ }
3051
+ });
3052
+ return kept;
3053
+ }
3054
+ function extractRelevantCss(cssText) {
3055
+ if (!cssText.trim()) {
3056
+ return "";
3057
+ }
3058
+ let root;
3059
+ try {
3060
+ root = postcss.parse(cssText);
3061
+ } catch (e) {
3062
+ console.warn("Failed to parse CSS for filtering, using unfiltered CSS:", e);
3063
+ return cssText;
3064
+ }
3065
+ const result = postcss.root();
3066
+ for (const node of filterNodes(root)) {
3067
+ result.append(node);
3068
+ }
3069
+ const output = result.toString();
3070
+ return output;
3071
+ }
3072
+
3030
3073
  // src/lib/renderModulePreview.ts
3031
3074
  import jsdom from "jsdom";
3032
3075
  var URL_SIGNING_GATE = "PortalsAccessIdentity:DesignManager:UrlSigning";
@@ -3055,15 +3098,23 @@ async function signedGet(authedPortalId, unsignedUrl, headers, gates) {
3055
3098
  return data;
3056
3099
  }
3057
3100
  const signedUrl = await signGetUrl(authedPortalId, unsignedUrl);
3058
- const authHeaders = {};
3059
3101
  const accountConfig = getConfigAccountIfExists4(authedPortalId);
3102
+ const authHeaders = {};
3060
3103
  if (accountConfig && accountConfig.authType === "personalaccesskey") {
3061
3104
  const accessToken = await accessTokenForPersonalAccessKey2(authedPortalId);
3062
3105
  authHeaders["Authorization"] = `Bearer ${accessToken}`;
3063
3106
  }
3107
+ const env2 = accountConfig == null ? void 0 : accountConfig.env;
3108
+ const referer = `https://api.hubspot${env2 === "qa" ? "qa" : ""}.com`;
3064
3109
  const response = await fetch(signedUrl, {
3065
3110
  method: "GET",
3066
- headers: { ...headers, ...authHeaders }
3111
+ headers: {
3112
+ ["Accept"]: "text/html",
3113
+ "User-Agent": "HubSpot CMS Dev Server",
3114
+ referer,
3115
+ ...headers,
3116
+ ...authHeaders
3117
+ }
3067
3118
  });
3068
3119
  if (!response.ok) {
3069
3120
  throw new Error(
@@ -3128,7 +3179,11 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
3128
3179
  const modulePreviewContent = dom.window.document.querySelector(
3129
3180
  'div[data-hs-cos-type="module"]'
3130
3181
  ).outerHTML;
3131
- const cssNeeded = Array.from(dom.window.document.querySelectorAll("style")).map((element) => element.outerHTML).join("");
3182
+ const allStyleContent = Array.from(
3183
+ dom.window.document.querySelectorAll("style")
3184
+ ).map((element) => element.textContent || "").join("\n");
3185
+ const filteredCss = extractRelevantCss(allStyleContent);
3186
+ const cssNeeded = filteredCss ? `<style>${filteredCss}</style>` : "";
3132
3187
  return { html: modulePreviewContent, cssNeeded };
3133
3188
  }
3134
3189
  async function signUrl(authedPortalId, unsignedUrl, requestBody) {
@@ -3213,7 +3268,8 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3213
3268
  const queryParams = new URLSearchParams({
3214
3269
  hsLocalProxy: `${true}`,
3215
3270
  localProxySchemaVersion: "2",
3216
- portalId: `${authedPortalId}`
3271
+ portalId: `${authedPortalId}`,
3272
+ ...meta.editor_version === "2.0" ? { editor_version: "2.0" } : {}
3217
3273
  });
3218
3274
  const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
3219
3275
  process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
@@ -3249,7 +3305,13 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3249
3305
  );
3250
3306
  }
3251
3307
  localRenderPlaceholders[0].json.props.fieldValues = localFieldValues;
3252
- return await renderComponentForPlaceholder(
3308
+ const previewDom = new JSDOM(templatePreview);
3309
+ const allStyleContent = Array.from(
3310
+ previewDom.window.document.querySelectorAll("head style")
3311
+ ).map((element) => element.textContent || "").join("\n");
3312
+ const filteredCss = extractRelevantCss(allStyleContent);
3313
+ const globalStylesCss = filteredCss ? `<style>${filteredCss}</style>` : "";
3314
+ const renderResult = await renderComponentForPlaceholder(
3253
3315
  0,
3254
3316
  localRenderPlaceholders[0],
3255
3317
  webRoot,
@@ -3260,6 +3322,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3260
3322
  projectName,
3261
3323
  projectComponentPath
3262
3324
  );
3325
+ return { ...renderResult, globalStylesCss };
3263
3326
  }
3264
3327
 
3265
3328
  // src/routes/partial.ts
@@ -4199,7 +4262,8 @@ async function modulePreviewRouteHandler(request, response) {
4199
4262
  html: renderedHtml,
4200
4263
  cssNeeded,
4201
4264
  renderContext,
4202
- inlineAssets
4265
+ inlineAssets,
4266
+ globalStylesCss
4203
4267
  } = await renderLocalProjectModulePreview(
4204
4268
  moduleName,
4205
4269
  authedPortalId,
@@ -4231,6 +4295,7 @@ async function modulePreviewRouteHandler(request, response) {
4231
4295
  htmlShell.replace(
4232
4296
  "<!--headend-->",
4233
4297
  [
4298
+ globalStylesCss,
4234
4299
  fullHeightCss,
4235
4300
  cssNeeded,
4236
4301
  ...inlineAssets.map((inlineAsset) => inlineAsset.html)
package/dist/run.js CHANGED
@@ -2256,7 +2256,7 @@ function trackUsage(action) {
2256
2256
  eventName: EVENT_NAME,
2257
2257
  action,
2258
2258
  nodeVersion: getNodeVersionData(),
2259
- version: "1.2.50",
2259
+ version: "1.2.60",
2260
2260
  os: getPlatform()
2261
2261
  };
2262
2262
  const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
@@ -3004,9 +3004,8 @@ function isModuleFolderChild(filePath) {
3004
3004
  import path6 from "path";
3005
3005
  var removePreviewPrefix = (t2) => t2.split("/").slice(2).join("/");
3006
3006
  var getPreviewUrl = (request, queryParams) => {
3007
- const { authedPortalId, authedEnv, authedHublet, sslEnabled } = request.app.locals;
3008
- const protocol = sslEnabled ? "https" : "http";
3009
- return `${protocol}://${authedPortalId}.hubspotpreview${authedEnv === "qa" ? "qa" : ""}-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;
3007
+ const { authedPortalId, authedEnv, authedHublet } = request.app.locals;
3008
+ return `https://${authedPortalId}.hubspotpreview${authedEnv === "qa" ? "qa" : ""}-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;
3010
3009
  };
3011
3010
  var buildHTMLResponse = (content) => {
3012
3011
  return `
@@ -3632,6 +3631,50 @@ async function fetchSignedModulePreview(signedUrl, authedEnv, cookieValue, postB
3632
3631
  return response.text();
3633
3632
  }
3634
3633
 
3634
+ // src/lib/extractRelevantCss.ts
3635
+ import postcss from "postcss";
3636
+ function isRelevantSelector(selector) {
3637
+ return selector.split(",").some(
3638
+ (part) => part.trim() === ":root" || /\[data-\w+-variant=/.test(part)
3639
+ );
3640
+ }
3641
+ function filterNodes(container) {
3642
+ const kept = [];
3643
+ container.each((node) => {
3644
+ if (node.type === "rule" && isRelevantSelector(node.selector)) {
3645
+ kept.push(node.clone());
3646
+ } else if (node.type === "atrule") {
3647
+ const children = filterNodes(node);
3648
+ if (children.length > 0) {
3649
+ const cloned = node.clone({ nodes: [] });
3650
+ for (const child of children) {
3651
+ cloned.append(child);
3652
+ }
3653
+ kept.push(cloned);
3654
+ }
3655
+ }
3656
+ });
3657
+ return kept;
3658
+ }
3659
+ function extractRelevantCss(cssText) {
3660
+ if (!cssText.trim()) {
3661
+ return "";
3662
+ }
3663
+ let root;
3664
+ try {
3665
+ root = postcss.parse(cssText);
3666
+ } catch (e) {
3667
+ console.warn("Failed to parse CSS for filtering, using unfiltered CSS:", e);
3668
+ return cssText;
3669
+ }
3670
+ const result = postcss.root();
3671
+ for (const node of filterNodes(root)) {
3672
+ result.append(node);
3673
+ }
3674
+ const output = result.toString();
3675
+ return output;
3676
+ }
3677
+
3635
3678
  // src/lib/renderModulePreview.ts
3636
3679
  import jsdom from "jsdom";
3637
3680
  var URL_SIGNING_GATE = "PortalsAccessIdentity:DesignManager:UrlSigning";
@@ -3660,15 +3703,23 @@ async function signedGet(authedPortalId, unsignedUrl, headers, gates) {
3660
3703
  return data;
3661
3704
  }
3662
3705
  const signedUrl = await signGetUrl(authedPortalId, unsignedUrl);
3663
- const authHeaders = {};
3664
3706
  const accountConfig = getConfigAccountIfExists5(authedPortalId);
3707
+ const authHeaders = {};
3665
3708
  if (accountConfig && accountConfig.authType === "personalaccesskey") {
3666
3709
  const accessToken = await accessTokenForPersonalAccessKey2(authedPortalId);
3667
3710
  authHeaders["Authorization"] = `Bearer ${accessToken}`;
3668
3711
  }
3712
+ const env2 = accountConfig == null ? void 0 : accountConfig.env;
3713
+ const referer = `https://api.hubspot${env2 === "qa" ? "qa" : ""}.com`;
3669
3714
  const response = await fetch(signedUrl, {
3670
3715
  method: "GET",
3671
- headers: { ...headers, ...authHeaders }
3716
+ headers: {
3717
+ ["Accept"]: "text/html",
3718
+ "User-Agent": "HubSpot CMS Dev Server",
3719
+ referer,
3720
+ ...headers,
3721
+ ...authHeaders
3722
+ }
3672
3723
  });
3673
3724
  if (!response.ok) {
3674
3725
  throw new Error(
@@ -3733,7 +3784,11 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
3733
3784
  const modulePreviewContent = dom.window.document.querySelector(
3734
3785
  'div[data-hs-cos-type="module"]'
3735
3786
  ).outerHTML;
3736
- const cssNeeded = Array.from(dom.window.document.querySelectorAll("style")).map((element) => element.outerHTML).join("");
3787
+ const allStyleContent = Array.from(
3788
+ dom.window.document.querySelectorAll("style")
3789
+ ).map((element) => element.textContent || "").join("\n");
3790
+ const filteredCss = extractRelevantCss(allStyleContent);
3791
+ const cssNeeded = filteredCss ? `<style>${filteredCss}</style>` : "";
3737
3792
  return { html: modulePreviewContent, cssNeeded };
3738
3793
  }
3739
3794
  async function signUrl(authedPortalId, unsignedUrl, requestBody) {
@@ -3818,7 +3873,8 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3818
3873
  const queryParams = new URLSearchParams({
3819
3874
  hsLocalProxy: `${true}`,
3820
3875
  localProxySchemaVersion: "2",
3821
- portalId: `${authedPortalId}`
3876
+ portalId: `${authedPortalId}`,
3877
+ ...meta.editor_version === "2.0" ? { editor_version: "2.0" } : {}
3822
3878
  });
3823
3879
  const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
3824
3880
  process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
@@ -3854,7 +3910,13 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3854
3910
  );
3855
3911
  }
3856
3912
  localRenderPlaceholders[0].json.props.fieldValues = localFieldValues;
3857
- return await renderComponentForPlaceholder(
3913
+ const previewDom = new JSDOM(templatePreview);
3914
+ const allStyleContent = Array.from(
3915
+ previewDom.window.document.querySelectorAll("head style")
3916
+ ).map((element) => element.textContent || "").join("\n");
3917
+ const filteredCss = extractRelevantCss(allStyleContent);
3918
+ const globalStylesCss = filteredCss ? `<style>${filteredCss}</style>` : "";
3919
+ const renderResult = await renderComponentForPlaceholder(
3858
3920
  0,
3859
3921
  localRenderPlaceholders[0],
3860
3922
  webRoot2,
@@ -3865,6 +3927,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
3865
3927
  projectName,
3866
3928
  projectComponentPath
3867
3929
  );
3930
+ return { ...renderResult, globalStylesCss };
3868
3931
  }
3869
3932
 
3870
3933
  // src/routes/partial.ts
@@ -4804,7 +4867,8 @@ async function modulePreviewRouteHandler(request, response) {
4804
4867
  html: renderedHtml,
4805
4868
  cssNeeded,
4806
4869
  renderContext,
4807
- inlineAssets
4870
+ inlineAssets,
4871
+ globalStylesCss
4808
4872
  } = await renderLocalProjectModulePreview(
4809
4873
  moduleName,
4810
4874
  authedPortalId,
@@ -4836,6 +4900,7 @@ async function modulePreviewRouteHandler(request, response) {
4836
4900
  htmlShell.replace(
4837
4901
  "<!--headend-->",
4838
4902
  [
4903
+ globalStylesCss,
4839
4904
  fullHeightCss,
4840
4905
  cssNeeded,
4841
4906
  ...inlineAssets.map((inlineAsset) => inlineAsset.html)
@@ -3,10 +3,7 @@
3
3
  // src/validateFields.ts
4
4
  import path3 from "path";
5
5
  import fs3 from "fs/promises";
6
- import { normalizePath as normalizePath2 } from "vite";
7
-
8
- // src/createViteDevServer.ts
9
- import { createServer as createViteServer } from "vite";
6
+ import { createServer as createViteServer, normalizePath as normalizePath2 } from "vite";
10
7
  import { createRequire } from "module";
11
8
  import { default as react } from "@vitejs/plugin-react";
12
9
 
@@ -174,9 +171,7 @@ function findAllModulesInRoot(webRoot) {
174
171
 
175
172
  // ../cms-js-internal/dist/index.js
176
173
  import * as dotProp from "dot-prop";
177
- import * as parser from "@babel/parser";
178
174
  import _traverse from "@babel/traverse";
179
- import * as t from "@babel/types";
180
175
  import * as cmsComponents from "@hubspot/cms-components";
181
176
  var { setProperty, getProperty, hasProperty } = dotProp;
182
177
  function noncePlaceholderPlugin() {
@@ -202,550 +197,15 @@ function noncePlaceholderPlugin() {
202
197
  };
203
198
  }
204
199
  var traverse = _traverse.default;
205
- var CMS_MODULE_COMPONENT_NAME = "Module";
206
- var DND_AREA_COMPONENT_NAME = "DndArea";
207
- var PLUGIN_NAME = "findCmsModules";
208
- function findCmsModules(buildContentDescriptors = {}) {
209
- let config;
210
- return {
211
- enforce: "pre",
212
- name: "findCmsModules",
213
- configResolved(resolvedConfig) {
214
- config = resolvedConfig;
215
- },
216
- transform(code, id) {
217
- const moduleInfo = this.getModuleInfo(id);
218
- if (!shouldAnalyzeModule(config, moduleInfo, code))
219
- return null;
220
- const contentDescriptors = analyzeSourceCodeUsages(
221
- this,
222
- moduleInfo,
223
- config,
224
- code
225
- );
226
- if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
227
- return {
228
- meta: {
229
- findCmsModules: contentDescriptors
230
- }
231
- };
232
- }
233
- },
234
- buildEnd(error) {
235
- if (error)
236
- throw error;
237
- const entryPoints = getEntryPoints(this, config);
238
- const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
239
- this,
240
- entryPoints
241
- );
242
- const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
243
- config,
244
- entryPointCmsModuleMap
245
- );
246
- const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
247
- this,
248
- entryPoints
249
- );
250
- const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
251
- config,
252
- entryPointIslandCmsModuleMap
253
- );
254
- if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
255
- this.error(`
256
- Error: <Module /> cannot be used within <Island />
257
- Found invalid usages:
258
- ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
259
- `);
260
- }
261
- const modulesWithinModules = filterEntryPointsToModules(
262
- relativeEntryPointCmsModuleMap
263
- );
264
- if (Object.keys(modulesWithinModules).length > 0) {
265
- this.error(`
266
- Error: <Module /> can only be used in React Partials
267
- Found invalid usages:
268
- ${JSON.stringify(modulesWithinModules, null, 2)}
269
- `);
270
- }
271
- Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
272
- }
273
- };
274
- }
275
- function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
276
- const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
277
- ([entryPointPath, cmsModules]) => {
278
- return [toRelativePath(config, entryPointPath), cmsModules];
279
- }
280
- );
281
- return Object.fromEntries(relativeEntries);
282
- }
283
- function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
284
- const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
285
- ([entryPointPath, islandContentDescriptors]) => {
286
- const islandCmsModuleUsage = Object.fromEntries(
287
- Object.entries(islandContentDescriptors).map(
288
- ([islandPath, contentDescriptors]) => {
289
- return [
290
- toRelativePath(config, islandPath).replace("?client-entry", ""),
291
- contentDescriptors
292
- ];
293
- }
294
- )
295
- );
296
- return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
297
- }
298
- );
299
- return Object.fromEntries(relativeEntries);
300
- }
301
- function toRelativePath(config, path4) {
302
- return path4.replace(`${config.root}/`, "");
303
- }
304
- function shouldAnalyzeModule(config, moduleInfo, code) {
305
- const [fileId, __] = moduleInfo.id.split("?");
306
- const isExternal = config.command !== "serve" && moduleInfo.isExternal;
307
- return (
308
- // analyze customer code only
309
- !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
310
- (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
311
- );
312
- }
313
- function getEntryPoints(ctx, config) {
314
- return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
315
- }
316
- function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
317
- const entryPointCmsModuleUsage = {};
318
- for (const entryPoint of entryPoints) {
319
- const result = findCmsModuleUsages(ctx, entryPoint.id);
320
- if (result) {
321
- entryPointCmsModuleUsage[entryPoint.id] = result;
322
- }
323
- }
324
- return entryPointCmsModuleUsage;
325
- }
326
- function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
327
- const entryPointIslandsCmsModuleMap = {};
328
- for (const entryPoint of entryPoints) {
329
- const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
330
- if (result) {
331
- entryPointIslandsCmsModuleMap[entryPoint.id] = result;
332
- }
333
- }
334
- return entryPointIslandsCmsModuleMap;
335
- }
336
- function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
337
- const sourceAst = parser.parse(code, {
338
- sourceType: "module",
339
- plugins: ["jsx", "typescript"]
340
- });
341
- const contentDescriptors = { modules: {}, dndAreas: {} };
342
- let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
343
- let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
344
- traverse(sourceAst, {
345
- ImportDeclaration(path4) {
346
- if (t.isStringLiteral(path4.node.source, {
347
- value: "@hubspot/cms-components"
348
- })) {
349
- for (const specifier of path4.node.specifiers) {
350
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
351
- name: CMS_MODULE_COMPONENT_NAME
352
- })) {
353
- moduleComponentLocalImportName = specifier.local.name;
354
- }
355
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
356
- name: DND_AREA_COMPONENT_NAME
357
- })) {
358
- dndAreaComponentLocalImportName = specifier.local.name;
359
- }
360
- }
361
- }
362
- },
363
- JSXOpeningElement(path4) {
364
- if (t.isJSXIdentifier(path4.node.name, {
365
- name: moduleComponentLocalImportName
366
- })) {
367
- let cmsModuleName;
368
- let cmsModulePath;
369
- let cmsModuleLabel;
370
- for (const prop of path4.node.attributes) {
371
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
372
- cmsModuleName = prop.value.value;
373
- continue;
374
- }
375
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
376
- cmsModulePath = prop.value.value;
377
- continue;
378
- }
379
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
380
- cmsModuleLabel = prop.value.value;
381
- continue;
382
- }
383
- ctx.error(
384
- new Error(
385
- `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
386
- )
387
- );
388
- }
389
- const cmsModuleProps = {
390
- name: cmsModuleName,
391
- path: cmsModulePath
392
- };
393
- if (cmsModuleLabel) {
394
- cmsModuleProps.label = cmsModuleLabel;
395
- }
396
- if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
397
- ctx.error(
398
- new Error(
399
- `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
400
- )
401
- );
402
- }
403
- contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
404
- }
405
- if (t.isJSXIdentifier(path4.node.name, {
406
- name: dndAreaComponentLocalImportName
407
- })) {
408
- let dndAreaName;
409
- for (const prop of path4.node.attributes) {
410
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
411
- dndAreaName = prop.value.value;
412
- continue;
413
- }
414
- ctx.error(
415
- new Error(
416
- `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
417
- )
418
- );
419
- }
420
- const dndArea = {
421
- name: dndAreaName
422
- };
423
- if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
424
- ctx.error(
425
- new Error(
426
- `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
427
- )
428
- );
429
- }
430
- contentDescriptors.dndAreas[dndArea.name] = dndArea;
431
- }
432
- }
433
- });
434
- return contentDescriptors;
435
- }
436
- function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
437
- if (Object.hasOwn(result, moduleId)) {
438
- return result[moduleId];
439
- }
440
- const moduleInfo = ctx.getModuleInfo(moduleId);
441
- let entryPointContentDescriptors = null;
442
- if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
443
- entryPointContentDescriptors = {
444
- ...entryPointContentDescriptors,
445
- ...moduleInfo.meta[PLUGIN_NAME]
446
- };
447
- }
448
- for (const importedId of [
449
- ...moduleInfo.importedIds,
450
- ...moduleInfo.dynamicallyImportedIds
451
- ]) {
452
- if (processed.has(importedId)) {
453
- continue;
454
- }
455
- const importedResult = findCmsModuleUsages(
456
- ctx,
457
- importedId,
458
- processed,
459
- result
460
- );
461
- if (importedResult) {
462
- entryPointContentDescriptors = {
463
- ...entryPointContentDescriptors,
464
- ...importedResult
465
- };
466
- }
467
- }
468
- if (entryPointContentDescriptors) {
469
- result[moduleId] = entryPointContentDescriptors;
470
- }
471
- processed.add(moduleId);
472
- return entryPointContentDescriptors;
473
- }
474
- function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
475
- processedIslands.add(moduleId);
476
- if (Object.hasOwn(islandModuleResults, moduleId)) {
477
- return islandModuleResults[moduleId];
478
- }
479
- const moduleInfo = ctx.getModuleInfo(moduleId);
480
- let resultForModuleId = {};
481
- if (moduleInfo.id.endsWith("?client-entry")) {
482
- const mergedDataDependencies = findCmsModuleUsages(
483
- ctx,
484
- moduleInfo.id,
485
- processed,
486
- results
487
- );
488
- if (mergedDataDependencies) {
489
- resultForModuleId[moduleInfo.id] = mergedDataDependencies;
490
- }
491
- }
492
- for (const importedId of [
493
- ...moduleInfo.importedIds,
494
- ...moduleInfo.dynamicallyImportedIds
495
- ]) {
496
- if (processedIslands.has(importedId)) {
497
- continue;
498
- }
499
- const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
500
- ctx,
501
- importedId,
502
- processedIslands,
503
- islandModuleResults,
504
- processed,
505
- results
506
- );
507
- if (importerCmsModuleUsageResult) {
508
- resultForModuleId = {
509
- ...resultForModuleId,
510
- ...importerCmsModuleUsageResult
511
- };
512
- }
513
- }
514
- if (Object.keys(resultForModuleId).length > 0) {
515
- islandModuleResults[moduleId] = resultForModuleId;
516
- return resultForModuleId;
517
- }
518
- return null;
519
- }
520
- function filterEntryPointsToModules(entryPointCmsModuleMap) {
521
- return Object.fromEntries(
522
- Object.entries(entryPointCmsModuleMap).filter(
523
- ([entryPoint]) => entryPoint.startsWith("components/modules/")
524
- )
525
- );
526
- }
527
200
  var {
528
201
  createServerRenderContextV2: createServerRenderContextV22,
529
202
  createServerRenderContext: createServerRenderContext2,
530
203
  renderServerSidePropsWithAsyncLocalStoreContext
531
204
  } = cmsComponents;
532
205
 
533
- // src/createViteDevServer.ts
534
- import { default as mkcert } from "vite-plugin-mkcert";
206
+ // src/validateFields.ts
535
207
  import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
536
208
 
537
- // src/plugins/devSecretsPlugin.ts
538
- function devSecretsPlugin(secretNames = []) {
539
- return {
540
- name: "dev-secrets",
541
- config: () => {
542
- return {
543
- define: {
544
- "import.meta.env.secretNames": secretNames
545
- }
546
- };
547
- }
548
- };
549
- }
550
-
551
- // src/plugins/cmsComponentsShimPlugin.ts
552
- function cmsComponentsShimPlugin() {
553
- return {
554
- name: "cms-components-shim",
555
- resolveId(id) {
556
- if (id === "@hubspot/cms-components" || id.startsWith("@hubspot/cms-components/")) {
557
- return `\0${id}`;
558
- }
559
- return null;
560
- },
561
- load(id) {
562
- if (id === "\0@hubspot/cms-components") {
563
- return `
564
- export const HSEnvironment = {};
565
- export const Hublet = {};
566
- export const createEmptyServerRenderContext = () => ({});
567
- export const buildStaticEnvConfig = () => ({});
568
- export const initConfigSingletonFromJSON = () => ({});
569
- export default {};
570
- `;
571
- }
572
- if (id === "\0@hubspot/cms-components/config") {
573
- return `
574
- export const EnvironmentConfig = {};
575
- export const initConfigSingletonFromJSON = () => ({});
576
- export default {};
577
- `;
578
- }
579
- if (id === "\0@hubspot/cms-components/fields") {
580
- return `
581
- export const Field = {};
582
- export const traverseFieldsJSON = () => ({});
583
- export default {};
584
- `;
585
- }
586
- if (id.startsWith("\0@hubspot/cms-components/")) {
587
- return "export default {};";
588
- }
589
- return null;
590
- }
591
- };
592
- }
593
-
594
- // src/plugins/hsStaticAssetPlugin.ts
595
- import { createProxyMiddleware } from "http-proxy-middleware";
596
- function hsStaticAssetPlugin() {
597
- return {
598
- name: "hsstatic-assets-plugin",
599
- enforce: "pre",
600
- configureServer(server) {
601
- return () => {
602
- const getDomainInfo = (req) => {
603
- const { authedPortalId, authedHublet, sslEnabled, authedEnv } = req.app.locals;
604
- const env = authedEnv === "qa" ? "qa" : "";
605
- const previewDomain = `${authedPortalId}.hubspotpreview${env}-${authedHublet}.com`;
606
- const protocol = sslEnabled ? "https" : "http";
607
- return { previewDomain, protocol };
608
- };
609
- server.middlewares.use(
610
- createProxyMiddleware(
611
- (__pathname, req) => {
612
- var _a;
613
- if (!((_a = req.url) == null ? void 0 : _a.match("^/hs/hsstatic/.*")))
614
- return false;
615
- const { authedPortalId, authedHublet, authedEnv } = req.app.locals;
616
- return !!(authedPortalId && authedHublet && authedEnv);
617
- },
618
- {
619
- changeOrigin: true,
620
- secure: false,
621
- xfwd: true,
622
- logLevel: "silent",
623
- // This is a placeholder target that gets overridden by the router
624
- // but is a required parameter for initialization
625
- target: "https://hubspot.com",
626
- router: (req) => {
627
- const { previewDomain, protocol } = getDomainInfo(req);
628
- return `${protocol}://${previewDomain}`;
629
- },
630
- onProxyReq: (proxyReq, req, __res) => {
631
- const { previewDomain, protocol } = getDomainInfo(req);
632
- proxyReq.setHeader("X-Forwarded-Proto", protocol);
633
- proxyReq.setHeader("host", previewDomain);
634
- proxyReq.setHeader(
635
- "referer",
636
- `${protocol}://${previewDomain}/content-rendering/v1/public/_hcms/preview/template/multi`
637
- );
638
- }
639
- }
640
- )
641
- );
642
- };
643
- }
644
- };
645
- }
646
-
647
- // src/createViteDevServer.ts
648
- import { readFileSync as readFileSync2 } from "fs";
649
- import { join as join2 } from "path";
650
- function getPackageJson(packagePath2) {
651
- return JSON.parse(readFileSync2(join2(packagePath2, "package.json")).toString());
652
- }
653
- function getDepsForPackage(packagePath2) {
654
- const packageJson = getPackageJson(packagePath2);
655
- return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];
656
- }
657
- function getDepsForPackageIfExists(packagePath2) {
658
- try {
659
- return getDepsForPackage(packagePath2);
660
- } catch (e) {
661
- console.warn("No package.json at ", packagePath2);
662
- return [];
663
- }
664
- }
665
- async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = [], jsRenderingGates, secretNames, logLevel) {
666
- const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
667
- `${proxyDomain}.localhost`,
668
- `${proxyDomain}.hslocal.net`
669
- ]).flat();
670
- if (process.env.VITE_ORIGIN) {
671
- console.log(`
672
- Custom origin: ${process.env.VITE_ORIGIN}
673
- `);
674
- }
675
- const origin = process.env.VITE_ORIGIN ?? (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);
676
- const consumerDeps = getDepsForPackageIfExists(webRoot);
677
- const isProjectWithReact = consumerDeps.includes("@hubspot/cms-components") || process.env.TRANSLATE_ASSET;
678
- const componentsShimPlugin = isProjectWithReact ? null : cmsComponentsShimPlugin();
679
- const ssrAndOptimizeDep = isProjectWithReact ? {
680
- ssr: {
681
- // TODO: might need more entries here to get things to resolve through
682
- // resolveWebRootDepsPlugin
683
- noExternal: "@hubspot/cms-components"
684
- },
685
- resolve: {
686
- conditions: ["server"],
687
- dedupe: [
688
- "react",
689
- "react-dom",
690
- "@hubspot/cms-components",
691
- "styled-jsx"
692
- ]
693
- },
694
- optimizeDeps: {
695
- include: ["react", "react-dom", "react-dom/client"]
696
- }
697
- } : {};
698
- const require2 = createRequire(import.meta.url);
699
- const reactAndIslandsPlugins = isProjectWithReact || process.env.VITEST ? [
700
- react({
701
- babel: {
702
- plugins: [
703
- require2.resolve("babel-plugin-styled-components"),
704
- require2.resolve("styled-jsx/babel"),
705
- require2.resolve("babel-plugin-macros")
706
- ]
707
- }
708
- }),
709
- clientIslandEntryPlugin(),
710
- resolveIslandPlugin(),
711
- viteCommonjs(),
712
- devSecretsPlugin(secretNames),
713
- noncePlaceholderPlugin()
714
- ] : [];
715
- const viteConfig = {
716
- logLevel,
717
- appType: "custom",
718
- server: {
719
- middlewareMode: true,
720
- host: "hslocal.net",
721
- origin,
722
- hmr: {
723
- protocol: sslEnabled ? "wss" : void 0
724
- },
725
- allowedHosts: ["localhost", "hslocal.net", ...additionalMkcertHosts]
726
- },
727
- root: webRoot,
728
- ...ssrAndOptimizeDep,
729
- plugins: [
730
- hsStaticAssetPlugin(),
731
- jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
732
- sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
733
- componentsShimPlugin,
734
- ...reactAndIslandsPlugins
735
- ],
736
- css: {
737
- postcss: webRoot
738
- },
739
- envDir: webRoot,
740
- envPrefix: "HS_",
741
- define: {
742
- "process.env": {}
743
- }
744
- };
745
- return createViteServer(viteConfig);
746
- }
747
- var createViteDevServer_default = createViteDevServer;
748
-
749
209
  // src/lib/renderModuleFieldsJson.ts
750
210
  import { join as joinPosix } from "path/posix";
751
211
 
@@ -1264,15 +724,36 @@ async function validateSingleModule(modulePath, absoluteRoot, viteServer) {
1264
724
  }
1265
725
  async function validateModuleFields(projectRoot, moduleName) {
1266
726
  const absoluteRoot = normalizePath2(path3.resolve(process.cwd(), projectRoot));
1267
- const viteServer = await createViteDevServer_default(
1268
- absoluteRoot,
1269
- 3e3,
1270
- false,
1271
- [],
1272
- [],
1273
- [],
1274
- "silent"
1275
- );
727
+ const require2 = createRequire(import.meta.url);
728
+ const viteServer = await createViteServer({
729
+ configFile: false,
730
+ logLevel: "silent",
731
+ appType: "custom",
732
+ root: absoluteRoot,
733
+ cacheDir: path3.join(absoluteRoot, "node_modules/.vite-validate-fields"),
734
+ server: { middlewareMode: true, hmr: false },
735
+ optimizeDeps: { noDiscovery: true, include: [] },
736
+ ssr: { noExternal: "@hubspot/cms-components" },
737
+ resolve: {
738
+ conditions: ["server"],
739
+ dedupe: ["react", "react-dom", "@hubspot/cms-components", "styled-jsx"]
740
+ },
741
+ plugins: [
742
+ react({
743
+ babel: {
744
+ plugins: [
745
+ require2.resolve("babel-plugin-styled-components"),
746
+ require2.resolve("styled-jsx/babel"),
747
+ require2.resolve("babel-plugin-macros")
748
+ ]
749
+ }
750
+ }),
751
+ clientIslandEntryPlugin(),
752
+ resolveIslandPlugin(),
753
+ viteCommonjs(),
754
+ noncePlaceholderPlugin()
755
+ ]
756
+ });
1276
757
  try {
1277
758
  if (moduleName) {
1278
759
  return [
@@ -1316,10 +797,10 @@ function parseCommandArgs() {
1316
797
  const hasErrors = results.some(
1317
798
  (r) => r.fieldErrors.length > 0 || r.metaErrors.length > 0
1318
799
  );
1319
- process.exit(hasErrors ? 1 : 0);
800
+ process.exitCode = hasErrors ? 1 : 0;
1320
801
  } catch (error) {
1321
802
  console.error("An error occurred:", error);
1322
- process.exit(1);
803
+ process.exitCode = 1;
1323
804
  }
1324
805
  })().catch((error) => {
1325
806
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hubspot/cms-dev-server",
3
- "version": "1.2.50",
3
+ "version": "1.2.60",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {
@@ -29,7 +29,7 @@
29
29
  "@babel/parser": "^7.25.3",
30
30
  "@babel/traverse": "^7.25.3",
31
31
  "@babel/types": "^7.25.2",
32
- "@hubspot/cms-components": "^1.2.50",
32
+ "@hubspot/cms-components": "^1.2.60",
33
33
  "@hubspot/local-dev-lib": "5.8.2",
34
34
  "@inquirer/select": "^2.0.0",
35
35
  "@originjs/vite-plugin-commonjs": "^1.0.3",
@@ -135,5 +135,5 @@
135
135
  "publishConfig": {
136
136
  "access": "public"
137
137
  },
138
- "gitHead": "718b360d01a8c5d30077af1ea07da28c1bb0d4f9"
138
+ "gitHead": "3f0de1da7da87dedafe63b9f96e10324de5a9e1a"
139
139
  }
@@ -0,0 +1 @@
1
+ export declare function extractRelevantCss(cssText: string): string;
@@ -6,4 +6,10 @@ export declare function renderRemoteModulePreview(modulePath: string, authedPort
6
6
  cssNeeded: string;
7
7
  }>;
8
8
  export declare function signUrl(authedPortalId: number, unsignedUrl: string, requestBody: any): Promise<string>;
9
- export declare function renderLocalProjectModulePreview(moduleName: string, authedPortalId: any, authedEnv: any, authedHublet: any, webRoot: any, viteServer: any, jsRenderingGates: any, projectName: any, projectComponentPath: any, fullOriginalUrl: any, cookieValue: any, fieldOverrides?: {}): Promise<import("./renderComponentWithCSS.js").RenderResult>;
9
+ export declare function renderLocalProjectModulePreview(moduleName: string, authedPortalId: any, authedEnv: any, authedHublet: any, webRoot: any, viteServer: any, jsRenderingGates: any, projectName: any, projectComponentPath: any, fullOriginalUrl: any, cookieValue: any, fieldOverrides?: {}): Promise<{
10
+ globalStylesCss: string;
11
+ html: string;
12
+ inlineAssets?: import("@hubspot/cms-js-internal").InlineAsset[];
13
+ cssNeeded: string;
14
+ renderContext: import("@hubspot/cms-components").ServerRenderContextValue;
15
+ }>;
package/dist/.DS_Store DELETED
Binary file
@@ -1,2 +0,0 @@
1
- export declare function debugAuthContext(authedPortalId: number, cookieValue: string): Promise<void>;
2
- export declare function compareUrls(originalUrl: string, signedUrl: string): void;
@@ -1,2 +0,0 @@
1
- export declare function getLocalComponentsPath(): string;
2
- export declare function shouldUseLocalComponents(): boolean;
@@ -1,15 +0,0 @@
1
- import { ViteDevServer } from 'vite';
2
- /**
3
- * Processes HTML to find remote assets and replace with Vite-managed URLs
4
- */
5
- export declare function processRemoteAssets(html: string, viteServer: ViteDevServer): Promise<string>;
6
- /**
7
- * Vite plugin to handle remote assets
8
- */
9
- export declare function remoteAssetsPlugin(): {
10
- name: string;
11
- apply: "serve";
12
- configResolved(config: any): void;
13
- resolveId(id: string): string;
14
- load(id: string): Promise<string>;
15
- };
@@ -1,2 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- export declare function hubspotStaticAssetsPlugin(): Plugin;
@@ -1,7 +0,0 @@
1
- import { ViteDevServer, Plugin } from 'vite';
2
- /**
3
- * Create a self-contained plugin with proper caching
4
- */
5
- export declare function remoteAssetsPlugin(): Plugin & {
6
- processRemoteAssets: (html: string, viteServer: ViteDevServer) => Promise<string>;
7
- };
@@ -1,6 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- /**
3
- * Plugin that provides URL signing capabilities
4
- * Uses internal signing mechanisms when available, with fallback for public environments
5
- */
6
- export default function requestSigningPlugin(): Plugin;
@@ -1,5 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
- export declare function handleGetModulePages(req: Request, res: Response, next: NextFunction): Promise<Response<any, Record<string, any>>>;
3
- export declare function handleOpenFile(req: Request, res: Response, next: NextFunction): Response<any, Record<string, any>>;
4
- export declare function createAppServerRoutes(): import("express-serve-static-core").Router;
5
- export default createAppServerRoutes;
@@ -1,3 +0,0 @@
1
- import { Request, Response } from 'express';
2
- declare const homeRouteHandler: (request: Request, response: Response, next: Function) => Promise<void>;
3
- export default homeRouteHandler;