@hubspot/cms-dev-server 0.16.18 → 0.18.0

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.
Files changed (75) hide show
  1. package/dist/generateJsonFromJsx.js +297 -172
  2. package/dist/index.js +4766 -176
  3. package/dist/internalSsr.js +260 -151
  4. package/dist/run.js +1989 -503
  5. package/dist/storybook-main/main.js +261 -152
  6. package/package.json +14 -10
  7. package/types/api/designmanager.d.ts +31 -0
  8. package/types/api/session.d.ts +2 -0
  9. package/types/components/HubLModulesList.d.ts +4 -0
  10. package/types/components/HubLTemplatesList.d.ts +4 -0
  11. package/types/components/ModulesList.d.ts +5 -0
  12. package/types/components/PartialsList.d.ts +4 -0
  13. package/types/createAppServer.d.ts +2 -0
  14. package/types/createDevServer.d.ts +5 -0
  15. package/types/createViteDevServer.d.ts +3 -0
  16. package/types/fileManager.d.ts +4 -0
  17. package/types/index.d.ts +1 -0
  18. package/types/lib/configHelpers.d.ts +2 -0
  19. package/types/lib/criticalDevErrorsToServerMessages.d.ts +4 -0
  20. package/types/lib/debug.d.ts +1 -0
  21. package/types/lib/errors.d.ts +6 -0
  22. package/types/lib/fetchModuleGraphQLData.d.ts +24 -0
  23. package/types/lib/fullOriginalUrlFromRequest.d.ts +2 -0
  24. package/types/lib/gates.d.ts +2 -0
  25. package/types/lib/getJSRenderingGates.d.ts +8 -0
  26. package/types/lib/httpsRedirectingServer.d.ts +11 -0
  27. package/types/lib/logColors.d.ts +6 -0
  28. package/types/lib/moduleGraph.d.ts +1 -0
  29. package/types/lib/packagePath.d.ts +1 -0
  30. package/types/lib/pathHelpers.d.ts +3 -0
  31. package/types/lib/previewUtils.d.ts +22 -0
  32. package/types/lib/proxyHelpers.d.ts +29 -0
  33. package/types/lib/renderComponentWithCSS.d.ts +14 -0
  34. package/types/lib/renderHelpers.d.ts +1 -0
  35. package/types/lib/renderModule.d.ts +11 -0
  36. package/types/lib/renderModulePreview.d.ts +5 -0
  37. package/types/lib/renderPartial.d.ts +5 -0
  38. package/types/lib/templates.d.ts +4 -0
  39. package/types/lib/trackUsage.d.ts +3 -0
  40. package/types/lib/validateHSPlatform.d.ts +3 -0
  41. package/types/lib/watchFieldsUpdates.d.ts +22 -0
  42. package/types/proxyPage/constants.d.ts +1 -0
  43. package/types/proxyPage/fetchContentMetadata.d.ts +7 -0
  44. package/types/proxyPage/fetchDomains.d.ts +9 -0
  45. package/types/proxyPage/fetchPreviewInfo.d.ts +6 -0
  46. package/types/proxyPage/proxyPage.d.ts +11 -0
  47. package/types/proxyPage/renderLocalError.d.ts +2 -0
  48. package/types/proxyPage/utils.d.ts +4 -0
  49. package/types/routes/createDevServerRoutes.d.ts +3 -0
  50. package/types/routes/homeRouteHandler.d.ts +3 -0
  51. package/types/routes/hublModuleRouteHandler.d.ts +2 -0
  52. package/types/routes/hublTemplateRouteHandler.d.ts +2 -0
  53. package/types/routes/linksToAllModulesRouteHandler.d.ts +2 -0
  54. package/types/routes/linksToAllPartialsRouteHandler.d.ts +2 -0
  55. package/types/routes/meta.d.ts +2 -0
  56. package/types/routes/module.d.ts +3 -0
  57. package/types/routes/modulePreviewRouteHandler.d.ts +3 -0
  58. package/types/routes/partial.d.ts +2 -0
  59. package/types/routes/proxyPageResourceRedirect.d.ts +2 -0
  60. package/types/routes/proxyPageRouteHandler.d.ts +2 -0
  61. package/types/routes/proxyPathPageResourceRedirect.d.ts +2 -0
  62. package/types/routes/proxyPathPageRouteHandler.d.ts +2 -0
  63. package/types/routes/proxyServerlessHandler.d.ts +2 -0
  64. package/types/routes/remoteFsDirtyHandler.d.ts +2 -0
  65. package/types/shadowDevServer/createShadowDevServerRoutes.d.ts +2 -0
  66. package/types/shadowDevServer/startShadowDevServer.d.ts +2 -0
  67. package/dist/generateJsonFromJsx.js.map +0 -7
  68. package/dist/index.js.map +0 -7
  69. package/dist/internalSsr.js.map +0 -7
  70. package/dist/island-runtime.js.map +0 -7
  71. package/dist/run.js.map +0 -7
  72. package/dist/storybook/index.js.map +0 -7
  73. package/dist/storybook-main/main.js.map +0 -7
  74. package/dist/storybook-main/preview.js.map +0 -7
  75. package/types/island-runtime.d.ts +0 -2
package/dist/run.js CHANGED
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/lib/cli.ts
4
- import { resolve } from "path";
4
+ import { resolve, join } from "path";
5
+ import { existsSync } from "fs";
5
6
 
6
7
  // src/lib/logColors.ts
7
8
  var CONTROL_CHARACTER = "\x1B";
@@ -20,6 +21,593 @@ function wrapMessageInColor(color, message) {
20
21
  return `${CONTROL_CHARACTER}[${ForeGroudANSIColorMap[color]}m${message}${CONTROL_CHARACTER}${DEFAULT_SCHEME}`;
21
22
  }
22
23
 
24
+ // src/lib/cli.ts
25
+ import cliProgress from "cli-progress";
26
+ import { FILE_UPLOAD_RESULT_TYPES } from "@hubspot/local-dev-lib/constants/files";
27
+
28
+ // src/lib/cliUtils.ts
29
+ import fs from "fs";
30
+ import path from "path";
31
+ import { walk } from "@hubspot/local-dev-lib/fs";
32
+ import { createIgnoreFilter } from "@hubspot/local-dev-lib/ignoreRules";
33
+ import { isAllowedExtension } from "@hubspot/local-dev-lib/path";
34
+ import { isConvertableFieldJs } from "@hubspot/local-dev-lib/cms/handleFieldsJS";
35
+ import { escapeRegExp } from "@hubspot/local-dev-lib/escapeRegExp";
36
+ import inquirer from "inquirer";
37
+ import { getThemeJSONPath } from "@hubspot/local-dev-lib/cms/themes";
38
+ import findup from "findup-sync";
39
+ import { getCwd, getAbsoluteFilePath } from "@hubspot/local-dev-lib/path";
40
+ import { logger } from "@hubspot/local-dev-lib/logger";
41
+ import {
42
+ isHubSpotHttpError,
43
+ isSystemError,
44
+ isFileSystemError,
45
+ isValidationError,
46
+ isMissingScopeError,
47
+ isSpecifiedError
48
+ } from "@hubspot/local-dev-lib/errors/index";
49
+ import { getAccountConfig } from "@hubspot/local-dev-lib/config";
50
+ import { HUBSPOT_ACCOUNT_TYPE_STRINGS } from "@hubspot/local-dev-lib/constants/config";
51
+ import util from "util";
52
+ import { isAxiosError } from "axios";
53
+ import chalk from "chalk";
54
+ import process2 from "process";
55
+ import os from "os";
56
+ import tty from "tty";
57
+ var COMPONENT_TYPES = Object.freeze({
58
+ privateApp: "private-app",
59
+ publicApp: "public-app",
60
+ hublTheme: "hubl-theme"
61
+ });
62
+ var CONFIG_FILES = {
63
+ [COMPONENT_TYPES.privateApp]: "app.json",
64
+ [COMPONENT_TYPES.publicApp]: "public-app.json",
65
+ [COMPONENT_TYPES.hublTheme]: "theme.json"
66
+ };
67
+ var PLATFORM_VERSION_ERROR_TYPES = {
68
+ PLATFORM_VERSION_NOT_SPECIFIED: "PlatformVersionErrorType.PLATFORM_VERSION_NOT_SPECIFIED",
69
+ PLATFORM_VERSION_RETIRED: "PlatformVersionErrorType.PLATFORM_VERSION_RETIRED",
70
+ PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST: "PlatformVersionErrorType.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST"
71
+ };
72
+ function previewProjectPrompt(themeComponents) {
73
+ return promptUser([
74
+ {
75
+ name: "themeComponentPath",
76
+ message: "[--theme] Select which theme to preview.",
77
+ type: "list",
78
+ choices: themeComponents.map((t2) => {
79
+ const themeName = path.basename(t2.path);
80
+ return {
81
+ name: themeName,
82
+ value: t2.path
83
+ };
84
+ })
85
+ }
86
+ ]);
87
+ }
88
+ var getProjectConfig = async (_dir) => {
89
+ const getProjectConfigPath = (__dir) => {
90
+ const projectDir = _dir ? getAbsoluteFilePath(_dir) : getCwd();
91
+ const PROJECT_CONFIG_FILE = "hsproject.json";
92
+ const configPath2 = findup(PROJECT_CONFIG_FILE, {
93
+ cwd: projectDir,
94
+ nocase: true
95
+ });
96
+ return configPath2;
97
+ };
98
+ const configPath = await getProjectConfigPath(_dir);
99
+ if (!configPath) {
100
+ return { projectConfig: null, projectDir: null };
101
+ }
102
+ try {
103
+ const config = fs.readFileSync(configPath);
104
+ const projectConfig = JSON.parse(config);
105
+ return {
106
+ projectDir: path.dirname(configPath),
107
+ projectConfig
108
+ };
109
+ } catch (e) {
110
+ console.error("Could not read from project config");
111
+ }
112
+ };
113
+ function loadConfigFile(configPath) {
114
+ if (configPath) {
115
+ try {
116
+ const source = fs.readFileSync(configPath);
117
+ const parsedConfig = JSON.parse(source);
118
+ return parsedConfig;
119
+ } catch (e) {
120
+ console.debug(e);
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+ function getTypeFromConfigFile(configFile) {
126
+ for (const key in CONFIG_FILES) {
127
+ if (CONFIG_FILES[key] === configFile) {
128
+ return key;
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ async function findProjectComponents(projectSourceDir) {
134
+ const components = [];
135
+ let projectFiles = [];
136
+ try {
137
+ projectFiles = await walk(projectSourceDir);
138
+ } catch (e) {
139
+ console.error(e);
140
+ }
141
+ projectFiles.forEach((projectFile) => {
142
+ const { base, dir } = path.parse(projectFile);
143
+ if (Object.values(CONFIG_FILES).includes(base)) {
144
+ const parsedAppConfig = loadConfigFile(projectFile);
145
+ if (parsedAppConfig) {
146
+ const isLegacy = getIsLegacyApp(parsedAppConfig, dir);
147
+ const isHublTheme = base === CONFIG_FILES[COMPONENT_TYPES.hublTheme];
148
+ components.push({
149
+ type: getTypeFromConfigFile(base),
150
+ config: parsedAppConfig,
151
+ runnable: !isLegacy && !isHublTheme,
152
+ path: dir
153
+ });
154
+ }
155
+ }
156
+ });
157
+ return components;
158
+ }
159
+ function getAppCardConfigs(appConfig, appPath) {
160
+ const cardConfigs = [];
161
+ let cards;
162
+ if (appConfig && appConfig.extensions && appConfig.extensions.crm) {
163
+ cards = appConfig.extensions.crm.cards;
164
+ }
165
+ if (cards) {
166
+ cards.forEach(({ file }) => {
167
+ if (typeof file === "string") {
168
+ const cardConfigPath = path.join(appPath, file);
169
+ const cardConfig = loadConfigFile(cardConfigPath);
170
+ if (cardConfig) {
171
+ cardConfigs.push(cardConfig);
172
+ }
173
+ }
174
+ });
175
+ }
176
+ return cardConfigs;
177
+ }
178
+ function getIsLegacyApp(appConfig, appPath) {
179
+ const cardConfigs = getAppCardConfigs(appConfig, appPath);
180
+ if (!cardConfigs.length) {
181
+ return false;
182
+ }
183
+ let hasAnyReactExtensions = false;
184
+ cardConfigs.forEach((cardConfig) => {
185
+ if (!hasAnyReactExtensions) {
186
+ const isReactExtension = cardConfig && !!cardConfig.data && !!cardConfig.data.module && !!cardConfig.data.module.file;
187
+ hasAnyReactExtensions = isReactExtension;
188
+ }
189
+ });
190
+ return !hasAnyReactExtensions;
191
+ }
192
+ async function determineSrcAndDest() {
193
+ let absoluteSrc;
194
+ let dest;
195
+ const { projectDir, projectConfig } = await getProjectConfig(void 0);
196
+ if (projectDir && projectConfig) {
197
+ let themeJsonPath = getThemeJSONPath(void 0);
198
+ if (!themeJsonPath) {
199
+ const projectComponents = await findProjectComponents(projectDir);
200
+ const themeComponents = projectComponents.filter(
201
+ (c) => c.type === COMPONENT_TYPES.hublTheme
202
+ );
203
+ if (themeComponents.length === 0) {
204
+ console.error(
205
+ "Your project has no theme components available to preview."
206
+ );
207
+ process2.exit(1);
208
+ }
209
+ const answer = await previewProjectPrompt(themeComponents);
210
+ themeJsonPath = `${answer.themeComponentPath}/theme.json`;
211
+ }
212
+ const { dir: themeDir } = path.parse(themeJsonPath);
213
+ absoluteSrc = themeDir;
214
+ const { base: themeName } = path.parse(themeDir);
215
+ dest = `@projects/${projectConfig.name}/${themeName}`;
216
+ } else {
217
+ console.error("Must be run inside a project directory");
218
+ process2.exit(1);
219
+ }
220
+ return { absoluteSrc, dest };
221
+ }
222
+ async function getUploadableFileList(src, convertFields) {
223
+ let filePaths = [];
224
+ try {
225
+ filePaths = await walk(src);
226
+ } catch (e) {
227
+ console.error(e);
228
+ }
229
+ const allowedFiles = filePaths.filter((file) => {
230
+ if (!isAllowedExtension(file)) {
231
+ return false;
232
+ }
233
+ return true;
234
+ }).filter(createIgnoreFilter(true));
235
+ if (!convertFields) {
236
+ return allowedFiles;
237
+ }
238
+ const uploadableFiles = [];
239
+ let skipFiles = [];
240
+ for (const filePath of allowedFiles) {
241
+ const fileName = path.basename(filePath);
242
+ if (skipFiles.includes(filePath))
243
+ continue;
244
+ const isConvertable = isConvertableFieldJs(src, filePath, convertFields);
245
+ if (isConvertable || fileName === "fields.json") {
246
+ const [choice, updatedSkipFiles] = await fieldsJsPrompt(
247
+ filePath,
248
+ src,
249
+ skipFiles
250
+ );
251
+ skipFiles = updatedSkipFiles;
252
+ if (choice !== filePath)
253
+ continue;
254
+ }
255
+ uploadableFiles.push(filePath);
256
+ }
257
+ return uploadableFiles;
258
+ }
259
+ function promptUser(promptConfig) {
260
+ const prompt = inquirer.createPromptModule();
261
+ return prompt(promptConfig);
262
+ }
263
+ async function fieldsJsPrompt(filePath, projectDir, skipFiles = []) {
264
+ const FIELDS_FILES = ["fields.json", "fields.js", "fields.cjs", "fields.mjs"];
265
+ const dirName = path.dirname(filePath);
266
+ const fileChoices = fs.readdirSync(dirName).filter((file) => FIELDS_FILES.includes(file)).map((file) => path.resolve(dirName, file)).filter((file) => !skipFiles.includes(file));
267
+ if (!fileChoices.length)
268
+ return [filePath, []];
269
+ if (fileChoices.length === 1)
270
+ return [fileChoices[0], []];
271
+ projectDir = projectDir.substring(0, projectDir.lastIndexOf("/"));
272
+ const projectDirRegex = new RegExp(`^${escapeRegExp(projectDir)}`);
273
+ const fileDir = path.dirname(fileChoices[0]).replace(projectDirRegex, "");
274
+ const selection = [];
275
+ fileChoices.forEach((fileChoice) => {
276
+ selection.push({
277
+ name: fileChoice.replace(projectDirRegex, ""),
278
+ value: fileChoice
279
+ });
280
+ });
281
+ const promptVal = await promptUser([
282
+ {
283
+ message: `Multiple fields files located in "${fileDir}". Please choose which to upload:`,
284
+ type: "list",
285
+ name: "filePathChoice",
286
+ choices: selection
287
+ }
288
+ ]);
289
+ const choice = promptVal.filePathChoice;
290
+ const notPicked = fileChoices.filter((item) => item !== choice);
291
+ skipFiles.push(...notPicked);
292
+ return [choice, skipFiles];
293
+ }
294
+ function logError(error, context = {}) {
295
+ debugError(error, context);
296
+ if (shouldSuppressError(error, context) || shouldSuppressError(error, error.context)) {
297
+ return;
298
+ }
299
+ if (isHubSpotHttpError(error) && context) {
300
+ error.updateContext(context);
301
+ }
302
+ if (isHubSpotHttpError(error) || isFileSystemError(error)) {
303
+ if (isValidationError(error) || isMissingScopeError(error)) {
304
+ logger.error(error.formattedValidationErrors());
305
+ } else {
306
+ logger.error(error.message);
307
+ }
308
+ } else if (isSystemError(error)) {
309
+ logger.error(error.message);
310
+ } else if (error.message || error.reason) {
311
+ const message = [];
312
+ [error.message, error.reason].forEach((msg) => {
313
+ if (msg) {
314
+ message.push(msg);
315
+ }
316
+ });
317
+ logger.error(message.join(" "));
318
+ } else {
319
+ logger.error("An unknown error has occurred.");
320
+ }
321
+ }
322
+ function debugError(error, context = {}) {
323
+ if (isHubSpotHttpError(error)) {
324
+ logger.debug(error.toString());
325
+ } else {
326
+ logger.debug(`Error: ${error}`);
327
+ }
328
+ if (error.cause) {
329
+ logger.debug(
330
+ `Cause: ${isAxiosError(error.cause) ? error.cause : util.inspect(error.cause, false, null, true)}`
331
+ );
332
+ }
333
+ if (context) {
334
+ logger.debug(`Context: ${util.inspect(context, false, null, true)}`);
335
+ }
336
+ }
337
+ var ApiErrorContext = class {
338
+ accountId;
339
+ request;
340
+ payload;
341
+ projectName;
342
+ constructor(props = {}) {
343
+ this.accountId = props.accountId;
344
+ this.request = props.request || "";
345
+ this.payload = props.payload || "";
346
+ this.projectName = props.projectName || "";
347
+ }
348
+ };
349
+ function createPlatformVersionError(err, subCategory) {
350
+ let translationKey = "unspecifiedPlatformVersion";
351
+ let platformVersion = "unspecified platformVersion";
352
+ const errorContext = err.response && err.response.data && err.response.data.context;
353
+ switch (subCategory) {
354
+ case PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED:
355
+ translationKey = "platformVersionRetired";
356
+ if (errorContext && errorContext[subCategory]) {
357
+ platformVersion = errorContext[subCategory];
358
+ }
359
+ break;
360
+ case PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST:
361
+ translationKey = "nonExistentPlatformVersion";
362
+ if (errorContext && errorContext[subCategory]) {
363
+ platformVersion = errorContext[subCategory];
364
+ }
365
+ break;
366
+ default:
367
+ break;
368
+ }
369
+ uiLine();
370
+ logger.error("Platform version update required");
371
+ const values = {
372
+ unspecifiedPlatformVersion: `Projects with an {{#bold}}${platformVersion}{{/bold}} are no longer supported.`,
373
+ platformVersionRetired: `Projects with {{#bold}}platformVersion ${platformVersion}{{/bold}} are no longer supported.`,
374
+ nonExistentPlatformVersion: `Projects with {{#bold}}platformVersion ${platformVersion}{{/bold}} are not supported.`
375
+ };
376
+ logger.log(values[translationKey]);
377
+ logger.log(`Please update your project to the latest version and try again.`);
378
+ logger.log(
379
+ `For more info, see ${uiLink(
380
+ `Projects platform versioning (BETA)`,
381
+ "https://developers.hubspot.com/docs/platform/platform-versioning"
382
+ )}.`
383
+ );
384
+ uiLine();
385
+ }
386
+ function shouldSuppressError(err, context = {}) {
387
+ if (isMissingScopeError(err)) {
388
+ logger.error(
389
+ `Couldn't execute the ${context.request || "request"} because the access key for ${context.accountId ? uiAccountDescription(context.accountId) : ""} is missing required scopes. To update scopes, run ${uiCommandReference(
390
+ "hs auth"
391
+ )}. Then deactivate the existing key and generate a new one that includes the missing scopes.`
392
+ );
393
+ return true;
394
+ }
395
+ if (isSpecifiedError(err, {
396
+ subCategory: PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_NOT_SPECIFIED
397
+ })) {
398
+ createPlatformVersionError(
399
+ err.data,
400
+ PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_NOT_SPECIFIED
401
+ );
402
+ return true;
403
+ }
404
+ if (isSpecifiedError(err, {
405
+ subCategory: PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED
406
+ })) {
407
+ createPlatformVersionError(
408
+ err.data,
409
+ PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED
410
+ );
411
+ return true;
412
+ }
413
+ if (isSpecifiedError(err, {
414
+ subCategory: PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST
415
+ })) {
416
+ createPlatformVersionError(
417
+ err.data,
418
+ PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST
419
+ );
420
+ return true;
421
+ }
422
+ return false;
423
+ }
424
+ function uiAccountDescription(accountId, bold = true) {
425
+ const account = getAccountConfig(accountId);
426
+ const message = `${account.name} [${HUBSPOT_ACCOUNT_TYPE_STRINGS[account.accountType]}] (${account.portalId})`;
427
+ return bold ? chalk.bold(message) : message;
428
+ }
429
+ var { env } = process2;
430
+ function translateLevel(level) {
431
+ if (level === 0) {
432
+ return {
433
+ level,
434
+ hasBasic: false,
435
+ has256: false,
436
+ has16m: false
437
+ };
438
+ }
439
+ return {
440
+ level,
441
+ hasBasic: true,
442
+ has256: level >= 2,
443
+ has16m: level >= 3
444
+ };
445
+ }
446
+ function _supportsColor(haveStream, { streamIsTTY } = {}) {
447
+ if (haveStream && !streamIsTTY) {
448
+ return 0;
449
+ }
450
+ const min = 0;
451
+ if (env.TERM === "dumb") {
452
+ return min;
453
+ }
454
+ if (hasFlag("noColor")) {
455
+ return 0;
456
+ }
457
+ if (process2.platform === "win32") {
458
+ const osRelease = os.release().split(".");
459
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
460
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
461
+ }
462
+ return 1;
463
+ }
464
+ if ("CI" in env) {
465
+ if ([
466
+ "TRAVIS",
467
+ "CIRCLECI",
468
+ "APPVEYOR",
469
+ "GITLAB_CI",
470
+ "GITHUB_ACTIONS",
471
+ "BUILDKITE",
472
+ "DRONE"
473
+ ].some((sign) => sign in env) || env.CI_NAME === "codeship") {
474
+ return 1;
475
+ }
476
+ return min;
477
+ }
478
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
479
+ return 1;
480
+ }
481
+ if (env.COLORTERM === "truecolor") {
482
+ return 3;
483
+ }
484
+ if ("TERM_PROGRAM" in env) {
485
+ const version = Number.parseInt(
486
+ (env.TERM_PROGRAM_VERSION || "").split(".")[0],
487
+ 10
488
+ );
489
+ switch (env.TERM_PROGRAM) {
490
+ case "iTerm.app":
491
+ return version >= 3 ? 3 : 2;
492
+ case "Apple_Terminal":
493
+ return 2;
494
+ }
495
+ }
496
+ if (/-256(color)?$/i.test(env.TERM)) {
497
+ return 2;
498
+ }
499
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
500
+ return 1;
501
+ }
502
+ if ("COLORTERM" in env) {
503
+ return 1;
504
+ }
505
+ return min;
506
+ }
507
+ function createSupportsColor(stream2, options = {}) {
508
+ const level = _supportsColor(stream2, {
509
+ streamIsTTY: stream2 && stream2.isTTY,
510
+ ...options
511
+ });
512
+ return translateLevel(level);
513
+ }
514
+ var supportsColor = {
515
+ createSupportsColor,
516
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
517
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
518
+ };
519
+ var UI_COLORS = {
520
+ SORBET: "#FF8F59",
521
+ MARIGOLD: "#f5c26b",
522
+ MARIGOLD_DARK: "#dbae60"
523
+ };
524
+ function getTerminalUISupport() {
525
+ return {
526
+ hyperlinks: supportsHyperlink(process2.stdout),
527
+ color: supportsColor.stdout.hasBasic
528
+ };
529
+ }
530
+ function uiLine() {
531
+ logger.log("-".repeat(50));
532
+ }
533
+ function uiLink(linkText, url4) {
534
+ const terminalUISupport = getTerminalUISupport();
535
+ const encodedUrl = encodeURI(url4);
536
+ if (terminalUISupport.hyperlinks) {
537
+ const CLOSE_SEQUENCE = "\x1B]8;;\x07";
538
+ const result = [
539
+ "\x1B]8;;",
540
+ encodedUrl,
541
+ "\x07",
542
+ linkText,
543
+ CLOSE_SEQUENCE
544
+ ].join("");
545
+ return terminalUISupport.color ? chalk.cyan(result) : result;
546
+ }
547
+ return terminalUISupport.color ? `${linkText}: ${chalk.reset.cyan(encodedUrl)}` : `${linkText}: ${encodedUrl}`;
548
+ }
549
+ function uiCommandReference(command) {
550
+ const terminalUISupport = getTerminalUISupport();
551
+ const commandReference = `\`${command}\``;
552
+ return chalk.bold(
553
+ terminalUISupport.color ? chalk.hex(UI_COLORS.MARIGOLD_DARK)(commandReference) : commandReference
554
+ );
555
+ }
556
+ function parseVersion(versionString) {
557
+ if (/^\d{3,4}$/.test(versionString)) {
558
+ const m = /(\d{1,2})(\d{2})/.exec(versionString);
559
+ return {
560
+ major: 0,
561
+ minor: parseInt(m[1], 10),
562
+ patch: parseInt(m[2], 10)
563
+ };
564
+ }
565
+ const versions = (versionString || "").split(".").map((n) => parseInt(n, 10));
566
+ return {
567
+ major: versions[0],
568
+ minor: versions[1],
569
+ patch: versions[2]
570
+ };
571
+ }
572
+ function supportsHyperlink(stream2) {
573
+ if (hasFlag("noHyperlinks")) {
574
+ return false;
575
+ }
576
+ if (stream2 && !stream2.isTTY) {
577
+ return false;
578
+ }
579
+ if (process2.platform === "win32") {
580
+ return false;
581
+ }
582
+ if ("CI" in env) {
583
+ return false;
584
+ }
585
+ if ("TERM_PROGRAM" in env) {
586
+ const version = parseVersion(env.TERM_PROGRAM_VERSION);
587
+ switch (env.TERM_PROGRAM) {
588
+ case "iTerm.app":
589
+ if (version.major === 3) {
590
+ return version.minor >= 1;
591
+ }
592
+ return version.major > 3;
593
+ }
594
+ }
595
+ if ("VTE_VERSION" in env) {
596
+ if (env.VTE_VERSION === "0.50.0") {
597
+ return false;
598
+ }
599
+ const version = parseVersion(env.VTE_VERSION);
600
+ return version.major > 0 || version.minor >= 50;
601
+ }
602
+ return false;
603
+ }
604
+ function hasFlag(flag, argv = process2.argv) {
605
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
606
+ const position = argv.indexOf(prefix + flag);
607
+ const terminatorPosition = argv.indexOf("--");
608
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
609
+ }
610
+
23
611
  // src/lib/cli.ts
24
612
  function printHelpMessage() {
25
613
  console.log(`
@@ -69,19 +657,92 @@ function getDevServerCommandLineOptions(argv) {
69
657
  const sslEnabledOption2 = args.includes("--ssl") && !args.includes("--no-ssl");
70
658
  const storybook2 = args.findIndex((arg) => arg === "--storybook") > 0;
71
659
  const fieldGenEnabledOption2 = args.includes("--generateFieldsTypes");
660
+ const resetSession2 = args.includes("--resetSession");
661
+ const showUI = args.includes("--showUI");
72
662
  return {
73
663
  hubspotCliConfigPathOption: hubspotCliConfigPathOption2,
74
664
  hubspotCliAccountNameOption: hubspotCliAccountNameOption2,
75
665
  sslEnabledOption: sslEnabledOption2,
76
666
  storybook: storybook2,
77
667
  fieldGenEnabledOption: fieldGenEnabledOption2,
78
- webRoot: webRoot2
668
+ webRoot: webRoot2,
669
+ showUI,
670
+ resetSession: resetSession2
671
+ };
672
+ }
673
+ async function buildThemePreviewOptions(webRoot2) {
674
+ const themeJsonPath = join(webRoot2, "theme.json");
675
+ if (!existsSync(themeJsonPath)) {
676
+ return void 0;
677
+ }
678
+ const filePaths = await getUploadableFileList(webRoot2, false);
679
+ const { dest } = await determineSrcAndDest();
680
+ const startProgressBar = (numFiles) => {
681
+ const initialUploadProgressBar = new cliProgress.SingleBar(
682
+ {
683
+ gracefulExit: true,
684
+ format: "[{bar}] {percentage}% | {value}/{total} | {label}",
685
+ hideCursor: true
686
+ },
687
+ cliProgress.Presets.rect
688
+ );
689
+ initialUploadProgressBar.start(numFiles, 0, {
690
+ label: "Starting..."
691
+ });
692
+ let uploadsHaveStarted = false;
693
+ const uploadOptions = {
694
+ onAttemptCallback: () => {
695
+ },
696
+ onSuccessCallback: () => {
697
+ initialUploadProgressBar.increment();
698
+ if (!uploadsHaveStarted) {
699
+ uploadsHaveStarted = true;
700
+ initialUploadProgressBar.update(0, {
701
+ label: "Uploading..."
702
+ });
703
+ }
704
+ },
705
+ onFirstErrorCallback: () => {
706
+ },
707
+ onRetryCallback: () => {
708
+ },
709
+ onFinalErrorCallback: () => initialUploadProgressBar.increment(),
710
+ onFinishCallback: (results) => {
711
+ initialUploadProgressBar.update(numFiles, {
712
+ label: "Complete!"
713
+ });
714
+ initialUploadProgressBar.stop();
715
+ results.forEach((result) => {
716
+ if (result.resultType === FILE_UPLOAD_RESULT_TYPES.FAILURE) {
717
+ console.error(
718
+ 'Uploading file "%s" to "%s" failed',
719
+ result.file,
720
+ dest
721
+ );
722
+ logError(
723
+ result.error,
724
+ new ApiErrorContext({
725
+ accountId: null,
726
+ request: dest,
727
+ payload: result.file
728
+ })
729
+ );
730
+ }
731
+ });
732
+ }
733
+ };
734
+ return uploadOptions;
735
+ };
736
+ return {
737
+ filePaths,
738
+ startProgressBar,
739
+ dest
79
740
  };
80
741
  }
81
742
 
82
743
  // src/createDevServer.ts
83
- import path10 from "path";
84
- import url2 from "url";
744
+ import path14 from "path";
745
+ import url3 from "url";
85
746
  import express2 from "express";
86
747
  import http3 from "http";
87
748
  import bodyParser from "body-parser";
@@ -94,7 +755,7 @@ import { Router } from "express";
94
755
  import { createProxyMiddleware } from "http-proxy-middleware";
95
756
 
96
757
  // src/routes/partial.ts
97
- import path5 from "path";
758
+ import path8 from "path";
98
759
  import { normalizePath as normalizePath4 } from "vite";
99
760
 
100
761
  // src/lib/fullOriginalUrlFromRequest.ts
@@ -111,29 +772,29 @@ import {
111
772
  } from "react-dom/server";
112
773
 
113
774
  // src/lib/packagePath.ts
114
- import path from "path";
775
+ import path2 from "path";
115
776
  import url from "url";
116
777
  import { normalizePath } from "vite";
117
778
  function packagePath(metaUrl, projectPath) {
118
779
  if (true) {
119
780
  return normalizePath(
120
- path.resolve(path.dirname(url.fileURLToPath(metaUrl)), projectPath)
781
+ path2.resolve(path2.dirname(url.fileURLToPath(metaUrl)), projectPath)
121
782
  );
122
783
  }
123
- const parentDirPath = normalizePath(path.dirname(url.fileURLToPath(metaUrl)));
784
+ const parentDirPath = normalizePath(path2.dirname(url.fileURLToPath(metaUrl)));
124
785
  const subPath = parentDirPath.replace(/^.+cms-dev-server\/src\//, "");
125
786
  const subPathParentDirs = subPath.split("/").map(() => "..");
126
- return path.resolve(
127
- path.dirname(url.fileURLToPath(metaUrl)),
128
- path.join(...subPathParentDirs, projectPath)
787
+ return path2.resolve(
788
+ path2.dirname(url.fileURLToPath(metaUrl)),
789
+ path2.join(...subPathParentDirs, projectPath)
129
790
  );
130
791
  }
131
792
 
132
793
  // ../cms-js-internal/dist/basicUtils.js
133
- import path2 from "path";
794
+ import path3 from "path";
134
795
  import { createHash } from "crypto";
135
- import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
136
- import { join } from "path/posix";
796
+ import fs2, { readFileSync, existsSync as existsSync2, readdirSync, lstatSync } from "fs";
797
+ import { join as join2 } from "path/posix";
137
798
  var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
138
799
  var ENTRY_POINTS_PATH = "components/partials/";
139
800
  var MODULE_FOLDER_PATH = "components/modules/";
@@ -174,8 +835,8 @@ function resolveIslandPlugin(islandsSet) {
174
835
  if (id.endsWith("?island") || id.endsWith("?client")) {
175
836
  const [idWithNoParam] = id.split("?");
176
837
  const islandModuleImportPath = `${idWithNoParam}?client-entry`;
177
- const componentExtension = path2.extname(idWithNoParam);
178
- const componentFilenameWithNoExtension = path2.basename(
838
+ const componentExtension = path3.extname(idWithNoParam);
839
+ const componentFilenameWithNoExtension = path3.basename(
179
840
  idWithNoParam,
180
841
  componentExtension
181
842
  );
@@ -273,7 +934,7 @@ var hasComponentExtension = (componentPath) => {
273
934
  return !!getComponentExtension(componentPath);
274
935
  };
275
936
  var isStorybookStory = (componentPath) => {
276
- return !!path2.basename(componentPath, path2.extname(componentPath)).endsWith(".stories");
937
+ return !!path3.basename(componentPath, path3.extname(componentPath)).endsWith(".stories");
277
938
  };
278
939
  var removeComponentExtension = (componentPath) => {
279
940
  const ext = getComponentExtension(componentPath);
@@ -290,46 +951,48 @@ function getEntryPointHashWithIndexSuffix(entryPoint, index) {
290
951
  return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
291
952
  }
292
953
  function getCMSAssetConfig(webRoot2) {
293
- const cmsAssetsPath = path2.join(webRoot2, "cms-assets.json");
294
- const cmsThemePath = path2.join(webRoot2, "theme.json");
295
- const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;
954
+ const cmsAssetsPath = path3.join(webRoot2, "cms-assets.json");
955
+ const cmsThemePath = path3.join(webRoot2, "theme.json");
956
+ const configPathToUse = fs2.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;
296
957
  const parsedConfig = JSON.parse(
297
- fs.readFileSync(configPathToUse).toString()
958
+ fs2.readFileSync(configPathToUse).toString()
298
959
  );
299
960
  return parsedConfig;
300
961
  }
301
962
  var ENABLED_FEATURES_GATE_MAP = {
302
963
  "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
303
964
  "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
304
- "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
965
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules",
966
+ "cms:jsr:clientOnlySupplementalFieldSerialization": "CMS:JSRenderer:ClientOnlySupplementalFieldSerialization",
967
+ "cms:react:unifiedThemePreview": "CMS:React:UnifiedThemePreview"
305
968
  };
306
969
  function isUngatedFor(gates, gate) {
307
970
  return gates.includes(gate);
308
971
  }
309
972
  var findAllComponentsIn = (webRoot2, componentsFolder) => {
310
- const fullComponentsFolderPath = join(webRoot2, componentsFolder);
973
+ const fullComponentsFolderPath = join2(webRoot2, componentsFolder);
311
974
  const componentsByName = {};
312
- if (!existsSync(fullComponentsFolderPath)) {
975
+ if (!existsSync2(fullComponentsFolderPath)) {
313
976
  return componentsByName;
314
977
  }
315
978
  readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
316
- const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
317
- const subdirPath = join(componentsFolder, fileOrFolderName);
979
+ const fullPath = join2(fullComponentsFolderPath, fileOrFolderName);
980
+ const subdirPath = join2(componentsFolder, fileOrFolderName);
318
981
  const isDirectory = lstatSync(fullPath).isDirectory();
319
982
  if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
320
983
  const subdirPathNoExtension = removeComponentExtension(subdirPath);
321
984
  componentsByName[subdirPathNoExtension] = subdirPath;
322
985
  } else if (isDirectory) {
323
986
  for (const potentialExtension of COMPONENT_EXTENSIONS) {
324
- const potentialIndexModule = join(
987
+ const potentialIndexModule = join2(
325
988
  subdirPath,
326
989
  `index${potentialExtension}`
327
990
  );
328
- const fullPotentialPath = join(
991
+ const fullPotentialPath = join2(
329
992
  fullPath,
330
993
  `index${potentialExtension}`
331
994
  );
332
- if (existsSync(fullPotentialPath)) {
995
+ if (existsSync2(fullPotentialPath)) {
333
996
  const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
334
997
  componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
335
998
  break;
@@ -422,7 +1085,7 @@ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
422
1085
  import * as cmsComponents from "@hubspot/cms-components";
423
1086
  import { ServerRenderContext } from "@hubspot/cms-components";
424
1087
  var { setProperty, getProperty, hasProperty } = dotProp;
425
- var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
1088
+ var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {
426
1089
  const islandsArrayToSerialize = tweakedIslandsArray.map(
427
1090
  ({
428
1091
  id,
@@ -432,7 +1095,7 @@ var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestD
432
1095
  hydrateOn,
433
1096
  clientOnly,
434
1097
  priority,
435
- url: url3,
1098
+ url: url4,
436
1099
  sharedStateID,
437
1100
  supplementalFieldValues,
438
1101
  wrapperModuleId,
@@ -446,7 +1109,7 @@ var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestD
446
1109
  clientOnly,
447
1110
  priority,
448
1111
  props,
449
- url: url3
1112
+ url: url4
450
1113
  };
451
1114
  if (sharedStateID) {
452
1115
  output.sharedStateID = sharedStateID;
@@ -464,6 +1127,9 @@ var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestD
464
1127
  if (filteredSupplementalFieldValues) {
465
1128
  output.supplementalFieldValues = filteredSupplementalFieldValues;
466
1129
  }
1130
+ if (isUngatedForClientOnlySupplementalFieldSerialization && output.clientOnly) {
1131
+ output.supplementalFieldValues = supplementalFieldValues;
1132
+ }
467
1133
  return output;
468
1134
  }
469
1135
  );
@@ -559,7 +1225,7 @@ function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
559
1225
  });
560
1226
  return perServerRequestDataWithUrls;
561
1227
  }
562
- var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
1228
+ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {
563
1229
  const islands = getIslandUrls(roots, viteDevServer);
564
1230
  const perServerRequestDataWithUrls = getPerServerRequestUrls(
565
1231
  perServerRequestData,
@@ -571,7 +1237,8 @@ var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevS
571
1237
  islands,
572
1238
  perServerRequestData,
573
1239
  indent,
574
- prettyPrint
1240
+ prettyPrint,
1241
+ isUngatedForClientOnlySupplementalFieldSerialization
575
1242
  )}${writeSharedStateToJsGlobal(
576
1243
  islands,
577
1244
  perServerRequestDataWithUrls,
@@ -603,6 +1270,7 @@ function noncePlaceholderPlugin() {
603
1270
  }
604
1271
  var traverse = _traverse.default;
605
1272
  var CMS_MODULE_COMPONENT_NAME = "Module";
1273
+ var PLUGIN_NAME = "findCmsModules";
606
1274
  function findCmsModules(cmsModules = {}) {
607
1275
  let config;
608
1276
  return {
@@ -613,80 +1281,14 @@ function findCmsModules(cmsModules = {}) {
613
1281
  },
614
1282
  transform(code, id) {
615
1283
  const moduleInfo = this.getModuleInfo(id);
616
- const isExternal = config.command === "serve" ? false : moduleInfo.isExternal;
617
- if (isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME)) {
1284
+ if (shouldSkipModule(config, moduleInfo, code))
618
1285
  return null;
619
- }
620
- const localCmsModules = {};
621
- const sourceAst = parser.parse(code, {
622
- sourceType: "module",
623
- plugins: ["jsx", "typescript"]
624
- });
625
- let moduleLocalImportName = CMS_MODULE_COMPONENT_NAME;
626
- let moduleUsed = false;
627
- const pluginError = this.error.bind(this);
628
- traverse(sourceAst, {
629
- ImportDeclaration(path11) {
630
- if (!t.isStringLiteral(path11.node.source, {
631
- value: "@hubspot/cms-components"
632
- })) {
633
- return null;
634
- }
635
- for (const specifier of path11.node.specifiers) {
636
- if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
637
- name: CMS_MODULE_COMPONENT_NAME
638
- })) {
639
- moduleLocalImportName = specifier.local.name;
640
- }
641
- }
642
- },
643
- JSXOpeningElement(path11) {
644
- if (!t.isJSXIdentifier(path11.node.name, {
645
- name: moduleLocalImportName
646
- })) {
647
- return null;
648
- }
649
- moduleUsed = true;
650
- let cmsModuleName;
651
- let cmsModulePath;
652
- let cmsModuleLabel;
653
- for (const prop of path11.node.attributes) {
654
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
655
- cmsModuleName = prop.value.value;
656
- continue;
657
- }
658
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
659
- cmsModulePath = prop.value.value;
660
- continue;
661
- }
662
- if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
663
- cmsModuleLabel = prop.value.value;
664
- continue;
665
- }
666
- pluginError(
667
- new Error(
668
- `Error: ${id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
669
- )
670
- );
671
- return null;
672
- }
673
- const cmsModuleProps = {
674
- name: cmsModuleName,
675
- path: cmsModulePath
676
- };
677
- if (cmsModuleLabel) {
678
- cmsModuleProps.label = cmsModuleLabel;
679
- }
680
- if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {
681
- pluginError(
682
- new Error(
683
- `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
684
- )
685
- );
686
- }
687
- localCmsModules[cmsModuleProps.name] = cmsModuleProps;
688
- }
689
- });
1286
+ const { localCmsModules, moduleUsed } = analyzeSourceCodeUsages(
1287
+ this,
1288
+ moduleInfo,
1289
+ config,
1290
+ code
1291
+ );
690
1292
  if (!moduleUsed) {
691
1293
  return null;
692
1294
  }
@@ -699,95 +1301,261 @@ function findCmsModules(cmsModules = {}) {
699
1301
  buildEnd(error) {
700
1302
  if (error)
701
1303
  throw error;
702
- const modulesWithCmsModuleUsage = Array.of(
703
- ...this.getModuleIds()
704
- ).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => this.getModuleInfo(moduleId)).filter(
705
- (moduleInfo) => Object.hasOwn(moduleInfo.meta, "findCmsModules")
1304
+ const entryPoints = getEntryPoints(this, config);
1305
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
1306
+ this,
1307
+ entryPoints
706
1308
  );
707
- const moduleToEntryPoints = {};
708
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
709
- moduleToEntryPoints[moduleWithCmsModuleUsage.id] = findEntryPoints(
710
- this,
711
- moduleWithCmsModuleUsage
712
- );
713
- }
714
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
715
- const usageInModuleEntryPoint = moduleToEntryPoints[moduleWithCmsModuleUsage.id].find((entryPoint) => entryPoint.id.includes("/components/modules"));
716
- if (usageInModuleEntryPoint) {
717
- this.error(`
718
- Error: <${CMS_MODULE_COMPONENT_NAME} /> can only be used in Partials.
719
- Module: ${usageInModuleEntryPoint.id === moduleWithCmsModuleUsage.id ? usageInModuleEntryPoint.id.replace(config.root, "") : `imports: ${moduleWithCmsModuleUsage.id.replace(
720
- config.root,
721
- ""
722
- )}, which`} contains a <${CMS_MODULE_COMPONENT_NAME} />
1309
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
1310
+ config,
1311
+ entryPointCmsModuleMap
1312
+ );
1313
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
1314
+ this,
1315
+ entryPoints
1316
+ );
1317
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
1318
+ config,
1319
+ entryPointIslandCmsModuleMap
1320
+ );
1321
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
1322
+ this.error(`
1323
+ Error: <Module /> cannot be used within <Island />
1324
+ Found invalid usages:
1325
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
723
1326
  `);
724
- }
725
1327
  }
726
- const root = config.root;
727
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
728
- const islandsContainingCmsModuleUsage = checkModuleTreeForIslands(
729
- this,
730
- moduleWithCmsModuleUsage
731
- );
732
- if (islandsContainingCmsModuleUsage.length > 0) {
733
- throw new Error(`
734
- <${CMS_MODULE_COMPONENT_NAME} /> cannot be used within islands.
735
- ${formatIslandImporter(
736
- moduleWithCmsModuleUsage.id,
737
- root
738
- )} uses <${CMS_MODULE_COMPONENT_NAME} /> and is used by islands:
739
- ${islandsContainingCmsModuleUsage.map(
740
- (islandModuleInfo) => formatIslandImporter(islandModuleInfo.id, root)
741
- ).join(", ")}
742
- `);
743
- }
1328
+ const modulesWithinModules = filterEntryPointsToModules(
1329
+ relativeEntryPointCmsModuleMap
1330
+ );
1331
+ if (Object.keys(modulesWithinModules).length > 0) {
1332
+ this.error(`
1333
+ Error: <Module /> can only be used in React Partials
1334
+ Found invalid usages:
1335
+ ${JSON.stringify(modulesWithinModules, null, 2)}
1336
+ `);
744
1337
  }
745
- for (const moduleWithCmsModuleUsage of modulesWithCmsModuleUsage) {
746
- const entryPoints = moduleToEntryPoints[moduleWithCmsModuleUsage.id];
747
- for (const entryPoint of entryPoints) {
748
- const relativeEntryPoint = entryPoint.id.replace(root, "");
749
- if (!Object.hasOwn(cmsModules, relativeEntryPoint)) {
750
- cmsModules[relativeEntryPoint] = {};
751
- }
752
- for (const [cmsModuleName, cmsModuleValue] of Object.entries(
753
- moduleWithCmsModuleUsage.meta.findCmsModules
754
- )) {
755
- if (Object.hasOwn(cmsModules[relativeEntryPoint], cmsModuleName)) {
756
- this.error(`Error: duplicate module name: ${cmsModuleName}`);
757
- }
758
- cmsModules[relativeEntryPoint][cmsModuleName] = cmsModuleValue;
1338
+ Object.assign(cmsModules, relativeEntryPointCmsModuleMap);
1339
+ }
1340
+ };
1341
+ }
1342
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
1343
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
1344
+ ([entryPointPath, cmsModules]) => {
1345
+ return [toRelativePath(config, entryPointPath), cmsModules];
1346
+ }
1347
+ );
1348
+ return Object.fromEntries(relativeEntries);
1349
+ }
1350
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
1351
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
1352
+ ([entryPointPath, islandCmsModules]) => {
1353
+ const islandCmsModuleUsage = Object.fromEntries(
1354
+ Object.entries(islandCmsModules).map(([islandPath, cmsModule]) => {
1355
+ return [
1356
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
1357
+ cmsModule
1358
+ ];
1359
+ })
1360
+ );
1361
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
1362
+ }
1363
+ );
1364
+ return Object.fromEntries(relativeEntries);
1365
+ }
1366
+ function toRelativePath(config, path15) {
1367
+ return path15.replace(config.root, "");
1368
+ }
1369
+ function shouldSkipModule(config, moduleInfo, code) {
1370
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
1371
+ return isExternal || !moduleInfo.id.startsWith(config.root) || !code.includes(CMS_MODULE_COMPONENT_NAME);
1372
+ }
1373
+ function getEntryPoints(ctx, config) {
1374
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
1375
+ }
1376
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
1377
+ const entryPointCmsModuleUsage = {};
1378
+ for (const entryPoint of entryPoints) {
1379
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
1380
+ if (result) {
1381
+ entryPointCmsModuleUsage[entryPoint.id] = result;
1382
+ }
1383
+ }
1384
+ return entryPointCmsModuleUsage;
1385
+ }
1386
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
1387
+ const entryPointIslandsCmsModuleMap = {};
1388
+ for (const entryPoint of entryPoints) {
1389
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
1390
+ if (result) {
1391
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
1392
+ }
1393
+ }
1394
+ return entryPointIslandsCmsModuleMap;
1395
+ }
1396
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
1397
+ const sourceAst = parser.parse(code, {
1398
+ sourceType: "module",
1399
+ plugins: ["jsx", "typescript"]
1400
+ });
1401
+ const localCmsModules = {};
1402
+ let moduleUsed = false;
1403
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
1404
+ traverse(sourceAst, {
1405
+ ImportDeclaration(path15) {
1406
+ if (t.isStringLiteral(path15.node.source, {
1407
+ value: "@hubspot/cms-components"
1408
+ })) {
1409
+ for (const specifier of path15.node.specifiers) {
1410
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
1411
+ name: CMS_MODULE_COMPONENT_NAME
1412
+ })) {
1413
+ moduleComponentLocalImportName = specifier.local.name;
759
1414
  }
760
1415
  }
761
1416
  }
1417
+ },
1418
+ JSXOpeningElement(path15) {
1419
+ if (!t.isJSXIdentifier(path15.node.name, {
1420
+ name: moduleComponentLocalImportName
1421
+ })) {
1422
+ return null;
1423
+ }
1424
+ moduleUsed = true;
1425
+ let cmsModuleName;
1426
+ let cmsModulePath;
1427
+ let cmsModuleLabel;
1428
+ for (const prop of path15.node.attributes) {
1429
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
1430
+ cmsModuleName = prop.value.value;
1431
+ continue;
1432
+ }
1433
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
1434
+ cmsModulePath = prop.value.value;
1435
+ continue;
1436
+ }
1437
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
1438
+ cmsModuleLabel = prop.value.value;
1439
+ continue;
1440
+ }
1441
+ ctx.error(
1442
+ new Error(
1443
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
1444
+ )
1445
+ );
1446
+ }
1447
+ const cmsModuleProps = {
1448
+ name: cmsModuleName,
1449
+ path: cmsModulePath
1450
+ };
1451
+ if (cmsModuleLabel) {
1452
+ cmsModuleProps.label = cmsModuleLabel;
1453
+ }
1454
+ if (Object.hasOwn(localCmsModules, cmsModuleProps.name)) {
1455
+ ctx.error(
1456
+ new Error(
1457
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
1458
+ )
1459
+ );
1460
+ }
1461
+ localCmsModules[cmsModuleProps.name] = cmsModuleProps;
762
1462
  }
1463
+ });
1464
+ return {
1465
+ moduleUsed,
1466
+ localCmsModules
763
1467
  };
764
1468
  }
765
- function findEntryPoints(ctx, moduleInfo) {
766
- if (moduleInfo.isEntry) {
767
- return [moduleInfo];
1469
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
1470
+ if (Object.hasOwn(result, moduleId)) {
1471
+ return result[moduleId];
1472
+ }
1473
+ const moduleInfo = ctx.getModuleInfo(moduleId);
1474
+ let entryPointModules = null;
1475
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
1476
+ entryPointModules = {
1477
+ ...entryPointModules,
1478
+ ...moduleInfo.meta[PLUGIN_NAME]
1479
+ };
768
1480
  }
769
- const result = [];
770
- for (const importer of moduleInfo.importers) {
771
- const importerModuleInfo = ctx.getModuleInfo(importer);
772
- const entryPoints = findEntryPoints(ctx, importerModuleInfo);
773
- result.push(...entryPoints);
1481
+ for (const importedId of [
1482
+ ...moduleInfo.importedIds,
1483
+ ...moduleInfo.dynamicallyImportedIds
1484
+ ]) {
1485
+ if (processed.has(importedId)) {
1486
+ continue;
1487
+ }
1488
+ const importedResult = findCmsModuleUsages(
1489
+ ctx,
1490
+ importedId,
1491
+ processed,
1492
+ result
1493
+ );
1494
+ if (importedResult) {
1495
+ entryPointModules = {
1496
+ ...entryPointModules,
1497
+ ...importedResult
1498
+ };
1499
+ }
774
1500
  }
775
- return result;
1501
+ if (entryPointModules) {
1502
+ result[moduleId] = entryPointModules;
1503
+ }
1504
+ processed.add(moduleId);
1505
+ return entryPointModules;
776
1506
  }
777
- function checkModuleTreeForIslands(ctx, module) {
778
- if (module.id.endsWith("?client-entry")) {
779
- return [module];
1507
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
1508
+ processedIslands.add(moduleId);
1509
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
1510
+ return islandModuleResults[moduleId];
1511
+ }
1512
+ const moduleInfo = ctx.getModuleInfo(moduleId);
1513
+ let resultForModuleId = {};
1514
+ if (moduleInfo.id.endsWith("?client-entry")) {
1515
+ const mergedDataDependencies = findCmsModuleUsages(
1516
+ ctx,
1517
+ moduleInfo.id,
1518
+ processed,
1519
+ results
1520
+ );
1521
+ if (mergedDataDependencies) {
1522
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
1523
+ }
780
1524
  }
781
- const importerResults = [];
782
- for (const importer of module.importers) {
783
- const importerInfo = ctx.getModuleInfo(importer);
784
- const importerResult = checkModuleTreeForIslands(ctx, importerInfo);
785
- importerResults.push(importerResult);
1525
+ for (const importedId of [
1526
+ ...moduleInfo.importedIds,
1527
+ ...moduleInfo.dynamicallyImportedIds
1528
+ ]) {
1529
+ if (processedIslands.has(importedId)) {
1530
+ continue;
1531
+ }
1532
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
1533
+ ctx,
1534
+ importedId,
1535
+ processedIslands,
1536
+ islandModuleResults,
1537
+ processed,
1538
+ results
1539
+ );
1540
+ if (importerCmsModuleUsageResult) {
1541
+ resultForModuleId = {
1542
+ ...resultForModuleId,
1543
+ ...importerCmsModuleUsageResult
1544
+ };
1545
+ }
786
1546
  }
787
- return importerResults.flat();
1547
+ if (Object.keys(resultForModuleId).length > 0) {
1548
+ islandModuleResults[moduleId] = resultForModuleId;
1549
+ return resultForModuleId;
1550
+ }
1551
+ return null;
788
1552
  }
789
- function formatIslandImporter(id, root) {
790
- return id.replace(root, "").replace("?client-entry", "");
1553
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
1554
+ return Object.fromEntries(
1555
+ Object.entries(entryPointCmsModuleMap).filter(
1556
+ ([entryPoint]) => entryPoint.startsWith("/components/modules/")
1557
+ )
1558
+ );
791
1559
  }
792
1560
  var promiseForNewWritableStream = () => {
793
1561
  const chunks = [];
@@ -1097,6 +1865,11 @@ var criticalDevErrorsToServerMessages_default = criticalDevErrorsToServerMessage
1097
1865
 
1098
1866
  // src/lib/templates.ts
1099
1867
  var { readFile } = fsPromises;
1868
+ var getIsUngatedForClientOnlySupplementalFieldSerialization = (gates) => {
1869
+ return gates.includes(
1870
+ "CMS:JSRenderer:ClientOnlySupplementalFieldSerialization"
1871
+ );
1872
+ };
1100
1873
  var generateIslandSetupScriptBlock = () => {
1101
1874
  return `
1102
1875
  <script type="module">
@@ -1137,9 +1910,9 @@ var createIslandHtmlTemplate = async (baseTemplatePath, title, globalScriptBlock
1137
1910
  );
1138
1911
  return htmlTemplate;
1139
1912
  };
1140
- var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, title, renderContext, viteServer, __jsRenderingGates) => {
1913
+ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url4, title, renderContext, viteServer, jsRenderingGates) => {
1141
1914
  let htmlTemplate;
1142
- const prettyPrint = isDebugUrlString2(url3);
1915
+ const prettyPrint = isDebugUrlString2(url4);
1143
1916
  const serverMessages = criticalDevErrorsToServerMessages_default(
1144
1917
  renderContext.criticalDevErrors
1145
1918
  );
@@ -1160,6 +1933,7 @@ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, tit
1160
1933
  title,
1161
1934
  `${globalScriptBlock}${serverLogScript}`
1162
1935
  );
1936
+ const isUngatedForClientOnlySupplementalFieldSerialization = getIsUngatedForClientOnlySupplementalFieldSerialization(jsRenderingGates);
1163
1937
  htmlTemplate = htmlTemplate.replace(
1164
1938
  "<!--islandsglobal-->",
1165
1939
  `<script>
@@ -1168,7 +1942,8 @@ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, tit
1168
1942
  renderContext.perServerRequestData,
1169
1943
  viteServer,
1170
1944
  6,
1171
- prettyPrint
1945
+ prettyPrint,
1946
+ isUngatedForClientOnlySupplementalFieldSerialization
1172
1947
  )}
1173
1948
  </script>
1174
1949
  `
@@ -1187,22 +1962,24 @@ var createHtmlShellDependingOnRenderContext = async (baseTemplatePath, url3, tit
1187
1962
  `${globalScriptBlock}${serverLogScript}`
1188
1963
  );
1189
1964
  }
1190
- return viteServer.transformIndexHtml(url3, htmlTemplate);
1965
+ return viteServer.transformIndexHtml(url4, htmlTemplate);
1191
1966
  };
1192
- var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, perServerRequestData, viteServer, __gates, prettyPrint) => {
1967
+ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, perServerRequestData, viteServer, gates, prettyPrint) => {
1193
1968
  const internalSsrPath = packagePath(import.meta.url, "internalSsr");
1194
1969
  const { createIslandsGlobalJsForClientInDev: createIslandsGlobalJsForClientInDev2 } = await viteServer.ssrLoadModule(internalSsrPath);
1195
1970
  const islandRuntimeScript = await viteServer.transformIndexHtml(
1196
1971
  "/",
1197
1972
  generateIslandSetupScriptBlock()
1198
1973
  );
1974
+ const isUngatedForClientOnlySupplementalFieldSerialization = getIsUngatedForClientOnlySupplementalFieldSerialization(gates);
1199
1975
  return `${islandRuntimeScript}
1200
1976
  <script>${createIslandsGlobalJsForClientInDev2(
1201
1977
  sortedIslandRoots,
1202
1978
  perServerRequestData,
1203
1979
  viteServer,
1204
1980
  4,
1205
- prettyPrint
1981
+ prettyPrint,
1982
+ isUngatedForClientOnlySupplementalFieldSerialization
1206
1983
  )}</script>
1207
1984
  `;
1208
1985
  };
@@ -1211,8 +1988,8 @@ var getIslandRuntimeAndGlobalToInject = async (sortedIslandRoots, perServerReque
1211
1988
  import { buildStaticEnvConfig as buildStaticEnvConfig3 } from "@hubspot/cms-components";
1212
1989
 
1213
1990
  // src/lib/trackUsage.ts
1214
- import localDevHttpImport from "@hubspot/local-dev-lib/http";
1215
- import { getAccountConfig } from "@hubspot/local-dev-lib/config";
1991
+ import { http as hsCliHttp } from "@hubspot/local-dev-lib/http";
1992
+ import { getAccountConfig as getAccountConfig2 } from "@hubspot/local-dev-lib/config";
1216
1993
  import axios from "axios";
1217
1994
  import { getAxiosConfig } from "@hubspot/local-dev-lib/http/getAxiosConfig";
1218
1995
 
@@ -1221,7 +1998,6 @@ import { default as debugFactory } from "debug";
1221
1998
  var debug = debugFactory("cms-dev-server");
1222
1999
 
1223
2000
  // src/lib/trackUsage.ts
1224
- var { default: hsCliHttp } = localDevHttpImport;
1225
2001
  var DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED = "/cms-dev-server-usage/v1/authenticated";
1226
2002
  var DEV_SERVER_USAGE_ENDPOINT = "/cms-dev-server-usage/v1";
1227
2003
  var EVENT_NAME = "dev-server-interaction";
@@ -1239,7 +2015,7 @@ var getPlatform = () => {
1239
2015
  };
1240
2016
  var getNodeVersionData = () => process.version;
1241
2017
  function trackUsage(action) {
1242
- const accountConfig = trackingAccountId && getAccountConfig(trackingAccountId);
2018
+ const accountConfig = trackingAccountId && getAccountConfig2(trackingAccountId);
1243
2019
  const isAuthedWithPersonalAccessKey = accountConfig && accountConfig.authType === "personalaccesskey";
1244
2020
  const usageEvent = {
1245
2021
  portalId: trackingAccountId,
@@ -1247,12 +2023,12 @@ function trackUsage(action) {
1247
2023
  eventName: EVENT_NAME,
1248
2024
  action,
1249
2025
  nodeVersion: getNodeVersionData(),
1250
- version: "0.16.18",
2026
+ version: "0.18.0",
1251
2027
  os: getPlatform()
1252
2028
  };
1253
- const url3 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
2029
+ const url4 = isAuthedWithPersonalAccessKey ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED : DEV_SERVER_USAGE_ENDPOINT;
1254
2030
  const baseRequestOptions = {
1255
- url: url3,
2031
+ url: url4,
1256
2032
  data: usageEvent
1257
2033
  };
1258
2034
  if (isAuthedWithPersonalAccessKey) {
@@ -1265,9 +2041,9 @@ function trackUsage(action) {
1265
2041
  });
1266
2042
  return axios(config);
1267
2043
  }
1268
- var setTrackingInfo = (accountId, env) => {
2044
+ var setTrackingInfo = (accountId, env2) => {
1269
2045
  trackingAccountId = accountId;
1270
- trackingEnv = env;
2046
+ trackingEnv = env2;
1271
2047
  };
1272
2048
  function sendTrackingRequest(action) {
1273
2049
  setImmediate(async () => {
@@ -1287,11 +2063,11 @@ function sendTrackingRequest(action) {
1287
2063
 
1288
2064
  // src/lib/renderModulePreview.ts
1289
2065
  import { buildStaticEnvConfig as buildStaticEnvConfig2 } from "@hubspot/cms-components";
1290
- import path4 from "path";
2066
+ import path7 from "path";
1291
2067
  import { normalizePath as normalizePath3 } from "vite";
1292
2068
 
1293
2069
  // src/lib/proxyHelpers.ts
1294
- import fs2 from "fs";
2070
+ import fs3 from "fs";
1295
2071
  import { resolve as resolve2 } from "path";
1296
2072
  import { unescape } from "html-escaper";
1297
2073
  var localJsRenderStartString = '<!-- proxy local render of "';
@@ -1320,12 +2096,12 @@ var findLocalRenderPlaceholders = (body) => {
1320
2096
  );
1321
2097
  offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;
1322
2098
  if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {
1323
- const path11 = body.substring(
2099
+ const path15 = body.substring(
1324
2100
  startOffset + localJsRenderStartString.length,
1325
2101
  pathEndOffset
1326
2102
  );
1327
2103
  offsetSoFar = pathEndOffset + 1;
1328
- if (startOffset >= 0 && path11) {
2104
+ if (startOffset >= 0 && path15) {
1329
2105
  const nextCommentEndOffset = body.indexOf("-->", pathEndOffset);
1330
2106
  const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);
1331
2107
  offsetSoFar = Math.min(nextCommentEndOffset, endOffset);
@@ -1350,7 +2126,7 @@ var findLocalRenderPlaceholders = (body) => {
1350
2126
  result.push({
1351
2127
  startOffset,
1352
2128
  endOffset: endOffset + localJsRenderEndString.length,
1353
- path: path11,
2129
+ path: path15,
1354
2130
  json
1355
2131
  });
1356
2132
  }
@@ -1370,7 +2146,7 @@ var findLocalRenderPlaceholders = (body) => {
1370
2146
  };
1371
2147
  var getHSProjectConfig = (hsProjectConfigPath) => {
1372
2148
  try {
1373
- return JSON.parse(fs2.readFileSync(hsProjectConfigPath, "utf8"));
2149
+ return JSON.parse(fs3.readFileSync(hsProjectConfigPath, "utf8"));
1374
2150
  } catch (e) {
1375
2151
  console.warn(
1376
2152
  `Missing hsproject.json file (${resolve2(hsProjectConfigPath)}): `,
@@ -1384,24 +2160,23 @@ var getProjectNameFromHSConfig = (hsProjectConfigPath) => {
1384
2160
  if (hsProjectConfig) {
1385
2161
  return hsProjectConfig.name;
1386
2162
  }
1387
- throw new Error("hsproject.json file not found");
2163
+ return null;
1388
2164
  };
1389
2165
 
1390
2166
  // src/proxyPage/proxyPage.ts
1391
- import path3 from "path";
2167
+ import path6 from "path";
1392
2168
  import { normalizePath as normalizePath2 } from "vite";
1393
2169
  import { getAccountId, getEnv } from "@hubspot/local-dev-lib/config";
1394
- import localDevHttpImport5 from "@hubspot/local-dev-lib/http";
2170
+ import { http as hsCliHttp6 } from "@hubspot/local-dev-lib/http";
1395
2171
 
1396
2172
  // src/lib/renderModule.ts
1397
2173
  import { join as joinPosix2 } from "path/posix";
1398
2174
  import { traverseFieldsJSON } from "@hubspot/cms-components/fields";
1399
2175
  import * as cmsComponents2 from "@hubspot/cms-components";
1400
- import localDevHttpImport3 from "@hubspot/local-dev-lib/http";
2176
+ import { http as hsCliHttp3 } from "@hubspot/local-dev-lib/http";
1401
2177
 
1402
2178
  // src/lib/fetchModuleGraphQLData.ts
1403
- import localDevHttpImport2 from "@hubspot/local-dev-lib/http";
1404
- var { default: hsCliHttp2 } = localDevHttpImport2;
2179
+ import { http as hsCliHttp2 } from "@hubspot/local-dev-lib/http";
1405
2180
  var graphQLCache = /* @__PURE__ */ new Map();
1406
2181
  async function fetchModuleGraphQLData(accountId, query, requestedModulePath, pageUrl) {
1407
2182
  const { searchParams } = new URL(pageUrl);
@@ -1413,12 +2188,12 @@ async function fetchModuleGraphQLData(accountId, query, requestedModulePath, pag
1413
2188
  return Promise.resolve(graphQLCache.get(compositeQueryKey));
1414
2189
  }
1415
2190
  try {
1416
- dataQueryResult = await hsCliHttp2.post(accountId, {
2191
+ dataQueryResult = (await hsCliHttp2.post(accountId, {
1417
2192
  url: "/collector/v3/graphql",
1418
2193
  data: {
1419
2194
  query
1420
2195
  }
1421
- });
2196
+ })).data;
1422
2197
  } catch (e) {
1423
2198
  throw new Error(e);
1424
2199
  }
@@ -1429,7 +2204,6 @@ async function fetchModuleGraphQLData(accountId, query, requestedModulePath, pag
1429
2204
  // src/lib/renderModule.ts
1430
2205
  var VALIDATE_FIELDS_ENDPOINT = "/designmanager/v1/modules/validate-fields";
1431
2206
  var VALIDATE_META_ENDPOINT = "/designmanager/v1/modules/validate-meta";
1432
- var { default: hsCliHttp3 } = localDevHttpImport3;
1433
2207
  var { filterToModuleDataDepsIncludedIn, getModuleDataDependecyTypeFrom } = cmsComponents2;
1434
2208
  var handleValidationApiError = (result, type, renderContext, requestedModulePath) => {
1435
2209
  if (result.status === "rejected") {
@@ -1729,14 +2503,13 @@ var customColors = [
1729
2503
  ];
1730
2504
  var Converter = new AnsiToHtmlConverter({ colors: customColors });
1731
2505
  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;`;
1732
- var renderLocalError_default = (path11, error) => {
2506
+ var renderLocalError_default = (path15, error) => {
1733
2507
  const stackWithColorClasses = Converter.toHtml(error.stack);
1734
- return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path11}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
2508
+ return `<div data-js-rendered="error" style="${darkErrorStyles}">Error rendering ${path15}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;
1735
2509
  };
1736
2510
 
1737
2511
  // src/proxyPage/fetchPreviewInfo.ts
1738
- import localDevHttpImport4 from "@hubspot/local-dev-lib/http";
1739
- var { default: hsCliHttp4 } = localDevHttpImport4;
2512
+ import { http as hsCliHttp4 } from "@hubspot/local-dev-lib/http";
1740
2513
  var fetchPreviewInfo_default = async (accountId, portalId, contentId) => {
1741
2514
  if (!contentId) {
1742
2515
  throw new Error(
@@ -1744,11 +2517,11 @@ var fetchPreviewInfo_default = async (accountId, portalId, contentId) => {
1744
2517
  );
1745
2518
  }
1746
2519
  try {
1747
- const content = await hsCliHttp4.get(accountId, {
2520
+ const content = (await hsCliHttp4.get(accountId, {
1748
2521
  url: `/content/api/v4/contents/${contentId}`,
1749
2522
  params: { portalId },
1750
2523
  responseType: "json"
1751
- });
2524
+ })).data;
1752
2525
  return {
1753
2526
  previewDomain: content.previewDomain ?? content.resolvedDomain,
1754
2527
  previewKey: content.previewKey
@@ -1783,7 +2556,341 @@ import {
1783
2556
  isDebugUrlString as isDebugUrlString3,
1784
2557
  mergeServerRequestData_internal
1785
2558
  } from "@hubspot/cms-components";
1786
- var { default: hsCliHttp5 } = localDevHttpImport5;
2559
+
2560
+ // src/lib/previewUtils.ts
2561
+ import { stringify } from "querystring";
2562
+ import { readFileSync as readFileSync2 } from "fs";
2563
+ import crypto from "crypto";
2564
+ import { relative, join as join3 } from "path";
2565
+
2566
+ // src/api/session.ts
2567
+ import { http as hsCliHttp5 } from "@hubspot/local-dev-lib/http";
2568
+ var PREVIEW_API_PATH = `local-preview/v1`;
2569
+ function initiateSession(accountId, resetSession2 = false) {
2570
+ return hsCliHttp5.post(accountId, {
2571
+ url: `${PREVIEW_API_PATH}/session/create`,
2572
+ headers: {
2573
+ "Content-Type": "application/json"
2574
+ },
2575
+ data: {
2576
+ resetSession: resetSession2
2577
+ }
2578
+ });
2579
+ }
2580
+ function diffDeveloperFileHashes(accountId, token, fileHashes) {
2581
+ return hsCliHttp5.post(accountId, {
2582
+ url: `${PREVIEW_API_PATH}/developer-file-hashes/diff`,
2583
+ headers: {
2584
+ "Content-Type": "application/json"
2585
+ },
2586
+ data: {
2587
+ token,
2588
+ fileHashes
2589
+ }
2590
+ });
2591
+ }
2592
+
2593
+ // src/fileManager.ts
2594
+ import { uploadFolder } from "@hubspot/local-dev-lib/cms/uploadFolder";
2595
+ import chokidar from "chokidar";
2596
+ import path4 from "path";
2597
+ import { shouldIgnoreFile } from "@hubspot/local-dev-lib/ignoreRules";
2598
+ import {
2599
+ convertToUnixPath,
2600
+ isAllowedExtension as isAllowedExtension2
2601
+ } from "@hubspot/local-dev-lib/path";
2602
+ import { getExt, splitLocalPath } from "@hubspot/local-dev-lib/path";
2603
+ import { upload, deleteFile } from "@hubspot/local-dev-lib/api/fileMapper";
2604
+ import { MODULE_EXTENSION } from "@hubspot/local-dev-lib/constants/extensions";
2605
+ import { escapeRegExp as escapeRegExp2 } from "@hubspot/local-dev-lib/escapeRegExp";
2606
+
2607
+ // src/routes/remoteFsDirtyHandler.ts
2608
+ var REMOTE_FS_IS_DIRTY = false;
2609
+ var remoteFsDirtyHandler = (req, res) => {
2610
+ res.json({ REMOTE_FS_IS_DIRTY });
2611
+ REMOTE_FS_IS_DIRTY = false;
2612
+ };
2613
+ var markRemoteFsDirty = () => {
2614
+ REMOTE_FS_IS_DIRTY = true;
2615
+ };
2616
+
2617
+ // src/fileManager.ts
2618
+ async function initialPreviewBufferUpload(accountId, src, dest, filePaths, uploadOptions) {
2619
+ const { onFinishCallback, ...rest } = uploadOptions;
2620
+ const results = await uploadFolder(accountId, src, dest, {}, rest, filePaths);
2621
+ onFinishCallback(results);
2622
+ }
2623
+ var startPreviewWatcher = async (accountId, src, dest) => {
2624
+ let watcherIsReady = false;
2625
+ const watcher = chokidar.watch(src, {
2626
+ ignoreInitial: true,
2627
+ // makes initial addition of files not trigger the watcher
2628
+ ignored: (file) => shouldIgnoreFile(file)
2629
+ });
2630
+ const addFileCallback = buildUploadFileToPreviewBufferCallback(
2631
+ accountId,
2632
+ src,
2633
+ dest
2634
+ );
2635
+ const changeFileCallback = buildUploadFileToPreviewBufferCallback(
2636
+ accountId,
2637
+ src,
2638
+ dest
2639
+ );
2640
+ const deleteFileCallback = buildDeleteFileFromPreviewBufferCallback(
2641
+ accountId,
2642
+ src,
2643
+ dest,
2644
+ "file"
2645
+ );
2646
+ const deleteFolderCallback = buildDeleteFileFromPreviewBufferCallback(
2647
+ accountId,
2648
+ src,
2649
+ dest,
2650
+ "folder"
2651
+ );
2652
+ watcher.on("ready", () => {
2653
+ watcherIsReady = true;
2654
+ });
2655
+ watcher.on("add", addFileCallback);
2656
+ watcher.on("change", changeFileCallback);
2657
+ watcher.on(
2658
+ "error",
2659
+ (error) => console.error(`An error occurred while watching files: ${error}`)
2660
+ );
2661
+ watcher.on("unlink", deleteFileCallback);
2662
+ watcher.on("unlinkDir", deleteFolderCallback);
2663
+ function sleep(ms) {
2664
+ return new Promise((resolve3) => {
2665
+ setTimeout(resolve3, ms);
2666
+ });
2667
+ }
2668
+ while (!watcherIsReady) {
2669
+ await sleep(1);
2670
+ }
2671
+ return watcher;
2672
+ };
2673
+ function buildUploadFileToPreviewBufferCallback(accountId, src, dest) {
2674
+ return (filePath) => {
2675
+ if (!isAllowedExtension2(filePath)) {
2676
+ console.debug(`Skipping ${filePath} due to unsupported extension`);
2677
+ return;
2678
+ }
2679
+ if (shouldIgnoreFile(filePath)) {
2680
+ console.debug(`Skipping ${filePath} due to an ignore rule`);
2681
+ return;
2682
+ }
2683
+ if (path4.dirname(filePath) === src && ["theme.json", "fields.json"].includes(path4.basename(filePath))) {
2684
+ console.warn(`Editing of theme fields or meta is not yet supported.`);
2685
+ return;
2686
+ }
2687
+ const destPath = getDesignManagerPath(src, dest, filePath);
2688
+ return uploadFile(accountId, filePath, destPath);
2689
+ };
2690
+ }
2691
+ function buildDeleteFileFromPreviewBufferCallback(accountId, src, dest, type) {
2692
+ return (filePath) => {
2693
+ if (shouldIgnoreFile(filePath)) {
2694
+ console.debug(`Skipping ${filePath} due to an ignore rule`);
2695
+ return;
2696
+ }
2697
+ if (type === "file") {
2698
+ const moduleChild = isModuleFolderChild(filePath);
2699
+ const filename = path4.basename(filePath);
2700
+ if (moduleChild && filename === "meta.json") {
2701
+ return;
2702
+ }
2703
+ }
2704
+ const remotePath = getDesignManagerPath(src, dest, filePath);
2705
+ return deleteRemoteFile(accountId, remotePath);
2706
+ };
2707
+ }
2708
+ function getDesignManagerPath(src, dest, file) {
2709
+ const regex = new RegExp(`^${escapeRegExp2(src)}`);
2710
+ const relativePath = file.replace(regex, "");
2711
+ return convertToUnixPath(path4.join(dest, relativePath));
2712
+ }
2713
+ async function uploadFile(accountId, src, dest) {
2714
+ console.debug(`Attempting to upload file "${src}" to "${dest}"`);
2715
+ try {
2716
+ await upload(accountId, src, dest);
2717
+ console.log(`Uploaded file ${src} to ${dest}`);
2718
+ markRemoteFsDirty();
2719
+ } catch {
2720
+ const uploadFailureMessage = `Uploading file ${src} to ${dest} failed`;
2721
+ console.debug(uploadFailureMessage);
2722
+ console.debug(`Retrying to upload file "${src}" to "${dest}"`);
2723
+ try {
2724
+ await upload(accountId, src, dest);
2725
+ markRemoteFsDirty();
2726
+ } catch (error) {
2727
+ console.error(uploadFailureMessage);
2728
+ }
2729
+ }
2730
+ }
2731
+ async function deleteRemoteFile(accountId, remoteFilePath) {
2732
+ console.debug(`Attempting to delete file "${remoteFilePath}"`);
2733
+ try {
2734
+ await deleteFile(accountId, remoteFilePath);
2735
+ console.log(`Deleted file ${remoteFilePath}`);
2736
+ markRemoteFsDirty();
2737
+ } catch (error) {
2738
+ console.error(`Deleting file ${remoteFilePath} failed`);
2739
+ console.debug(`Retrying deletion of file ${remoteFilePath}`);
2740
+ try {
2741
+ await deleteFile(accountId, remoteFilePath);
2742
+ markRemoteFsDirty();
2743
+ } catch (err) {
2744
+ console.error(`Deleting file ${remoteFilePath} failed`);
2745
+ }
2746
+ }
2747
+ }
2748
+ function isModuleFolderChild(filePath) {
2749
+ const pathParts = splitLocalPath(filePath);
2750
+ if (pathParts.length <= 1)
2751
+ return false;
2752
+ return pathParts.slice(0, pathParts.length - 1).some((part) => getExt(path4.normalize(part)) === MODULE_EXTENSION);
2753
+ }
2754
+
2755
+ // src/lib/previewUtils.ts
2756
+ import path5 from "path";
2757
+ var removePreviewPrefix = (t2) => t2.split("/").slice(2).join("/");
2758
+ var getPreviewUrl = (request2, queryParams) => {
2759
+ const { authedPortalId, authedEnv, authedHublet } = request2.app.locals;
2760
+ return `http://${authedPortalId}.hubspotpreview${authedEnv === "qa" ? "qa" : ""}-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;
2761
+ };
2762
+ var buildHTMLResponse = (content) => {
2763
+ return `
2764
+ <!DOCTYPE html>
2765
+ <head>
2766
+ </head>
2767
+ <body>
2768
+ ${content}
2769
+ </body>
2770
+ `;
2771
+ };
2772
+ var insertAtEndOfBody = (html, script) => {
2773
+ const insertAt = (baseStr, index, insertStr) => {
2774
+ return `${baseStr.slice(0, index)}${insertStr}${baseStr.slice(index)}`;
2775
+ };
2776
+ const endOfBodyIndex = html.lastIndexOf("</body>");
2777
+ return insertAt(html, endOfBodyIndex, script);
2778
+ };
2779
+ var addRefreshScript = (html) => {
2780
+ const refreshScript = `
2781
+ <script>
2782
+ (() => {
2783
+ const MAX_WAIT = 16000;
2784
+ const NORMAL_WAIT_MS = 1000;
2785
+ const BACKOFF_RATIO = 2;
2786
+ let nextWait = NORMAL_WAIT_MS;
2787
+ let timeWaited = 0;
2788
+
2789
+ setInterval(() => {
2790
+ timeWaited += NORMAL_WAIT_MS;
2791
+ if (timeWaited !== nextWait) return;
2792
+ timeWaited = 0;
2793
+ const res = fetch(window.location.origin + '/remote-fs-dirty')
2794
+ .then(async (res) => {
2795
+ const hsServerState = await res.json();
2796
+ if (hsServerState["REMOTE_FS_IS_DIRTY"]) {
2797
+ location.reload();
2798
+ }
2799
+ nextWait = NORMAL_WAIT_MS;
2800
+ })
2801
+ .catch(err => {
2802
+ if (nextWait * BACKOFF_RATIO <= MAX_WAIT) {
2803
+ nextWait *= BACKOFF_RATIO;
2804
+ }
2805
+ console.log('Disconnected from local server... (retrying in ' + nextWait / 1000 + 's)');
2806
+ });
2807
+ }, NORMAL_WAIT_MS);
2808
+ })();
2809
+ </script>
2810
+ `;
2811
+ return insertAtEndOfBody(html, refreshScript);
2812
+ };
2813
+ function buildDevFileHashTable(src, dest, filePaths) {
2814
+ return filePaths.reduce((acc, filePath) => {
2815
+ const relativePath = relative(src, filePath);
2816
+ const destPath = join3(dest, relativePath);
2817
+ acc[`/${destPath}`] = getMd5Hash(filePath);
2818
+ return acc;
2819
+ }, {});
2820
+ }
2821
+ function getMd5Hash(filePath) {
2822
+ const fileContent = readFileSync2(filePath);
2823
+ const hash = crypto.createHash("md5");
2824
+ hash.update(fileContent);
2825
+ return hash.digest("hex");
2826
+ }
2827
+ async function initiatePreviewSession(authedPortalId, absoluteWebRoot, themePreviewOptions2) {
2828
+ let res;
2829
+ try {
2830
+ res = (await initiateSession(authedPortalId, themePreviewOptions2.resetSession)).data;
2831
+ } catch (err) {
2832
+ console.error(`Failed to initiate session: ${err}`);
2833
+ return;
2834
+ }
2835
+ const { token, tokenStatus } = res;
2836
+ if (token) {
2837
+ const { dest, filePaths, startProgressBar } = themePreviewOptions2;
2838
+ const absoluteDest = `@preview/${token}/${dest}`;
2839
+ const nonJSRFilePaths = filePaths.filter(
2840
+ (filePath) => !filePath.startsWith(path5.join(absoluteWebRoot, "components"))
2841
+ );
2842
+ if (tokenStatus === "NEW") {
2843
+ console.log("Uploading for a new session...");
2844
+ const uploadOptions = startProgressBar(nonJSRFilePaths.length);
2845
+ await initialPreviewBufferUpload(
2846
+ authedPortalId,
2847
+ absoluteWebRoot,
2848
+ absoluteDest,
2849
+ nonJSRFilePaths,
2850
+ uploadOptions
2851
+ );
2852
+ } else if (tokenStatus === "REFRESHED") {
2853
+ console.log("Comparing files for refreshed session...");
2854
+ const hashes = await buildDevFileHashTable(
2855
+ absoluteWebRoot,
2856
+ absoluteDest,
2857
+ nonJSRFilePaths
2858
+ );
2859
+ let diffRes;
2860
+ try {
2861
+ diffRes = (await diffDeveloperFileHashes(authedPortalId, token, hashes)).data;
2862
+ } catch (err) {
2863
+ console.error(
2864
+ `Failed to diff developer file hashes: ${JSON.stringify(err)}`
2865
+ );
2866
+ return;
2867
+ }
2868
+ const {
2869
+ changedFiles,
2870
+ addedFiles
2871
+ /*, deletedFiles */
2872
+ } = diffRes;
2873
+ const filesToUpload = [...changedFiles, ...addedFiles].map((filePath) => {
2874
+ const relPath = path5.relative(absoluteDest, filePath.substring(1));
2875
+ return path5.join(absoluteWebRoot, relPath);
2876
+ });
2877
+ if (filesToUpload.length) {
2878
+ const uploadOptions = startProgressBar(filesToUpload.length);
2879
+ await initialPreviewBufferUpload(
2880
+ authedPortalId,
2881
+ absoluteWebRoot,
2882
+ absoluteDest,
2883
+ filesToUpload,
2884
+ uploadOptions
2885
+ );
2886
+ }
2887
+ }
2888
+ await startPreviewWatcher(authedPortalId, absoluteWebRoot, absoluteDest);
2889
+ }
2890
+ return { localPreviewToken: token, tokenStatus };
2891
+ }
2892
+
2893
+ // src/proxyPage/proxyPage.ts
1787
2894
  var getEntryPointBasePathFromProxyRequest = (request2) => {
1788
2895
  if (!request2) {
1789
2896
  return "";
@@ -1806,18 +2913,18 @@ function resolvePlaceholderPath(placeholderPath, projectName, projectComponent)
1806
2913
  }
1807
2914
  return placeholderPath;
1808
2915
  }
1809
- var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, projectName, environmentConfig, __jsRenderingGates, cookieHeader) => {
1810
- const url3 = new URL(urlToProxy);
1811
- const renderPreviewLocally = url3.searchParams.has("renderPreviewLocally");
2916
+ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, projectName, environmentConfig, __jsRenderingGates, cookieHeader, localPreviewToken) => {
2917
+ const url4 = new URL(urlToProxy);
2918
+ const renderPreviewLocally = url4.searchParams.has("renderPreviewLocally");
1812
2919
  let proxiedQueryParams = {};
1813
- let baseURL = url3.origin;
1814
- let pathname = url3.pathname;
2920
+ let baseURL = url4.origin;
2921
+ let pathname = url4.pathname;
1815
2922
  const PARAMS_TO_IGNORE = ["renderPreviewLocally"];
1816
- const queryKeys = Array.from(url3.searchParams.keys()).filter(
2923
+ const queryKeys = Array.from(url4.searchParams.keys()).filter(
1817
2924
  (queryKey) => !PARAMS_TO_IGNORE.includes(queryKey)
1818
2925
  );
1819
2926
  for (const queryKey of queryKeys) {
1820
- const values = url3.searchParams.getAll(queryKey);
2927
+ const values = url4.searchParams.getAll(queryKey);
1821
2928
  if (values.length > 1) {
1822
2929
  proxiedQueryParams[queryKey] = values;
1823
2930
  } else {
@@ -1833,33 +2940,43 @@ var makeProxyPreviewRequest = (accountId, urlToProxy, previewKey, contentId, pro
1833
2940
  hsLoginVerifyDisabled: `${true}`
1834
2941
  };
1835
2942
  if (renderPreviewLocally) {
1836
- proxiedQueryParams.hsDebugOverridePublicHost = url3.host;
2943
+ proxiedQueryParams.hsDebugOverridePublicHost = url4.host;
1837
2944
  baseURL = `http://local.hubspot${environmentConfig.getInternalHSEnv() === "qa" ? "qa" : ""}.com`;
1838
- pathname = `/cos-rendering/v1/public${url3.pathname}`;
2945
+ pathname = `/cos-rendering/v1/public${url4.pathname}`;
2946
+ }
2947
+ if (localPreviewToken) {
2948
+ proxiedQueryParams = {
2949
+ ...proxiedQueryParams,
2950
+ localPreviewToken,
2951
+ hsCacheBuster: Date.now().toString()
2952
+ };
2953
+ delete proxiedQueryParams["hs_preview"];
1839
2954
  }
1840
2955
  console.log(
1841
2956
  `Proxying request to ${baseURL}${pathname}?${new URLSearchParams({
1842
2957
  ...proxiedQueryParams,
1843
2958
  previewKey,
1844
2959
  contentId
1845
- }).toString()}`
1846
- );
1847
- const result = hsCliHttp5.get(accountId, {
1848
- baseURL,
1849
- url: pathname,
1850
- params: proxiedQueryParams,
1851
- responseType: "text",
1852
- headers: {
1853
- COOKIE: cookieHeader
1854
- }
1855
- });
1856
- return result.catch((error) => {
2960
+ }).toString()}`
2961
+ );
2962
+ try {
2963
+ const result = hsCliHttp6.get(accountId, {
2964
+ baseURL,
2965
+ url: pathname,
2966
+ params: proxiedQueryParams,
2967
+ responseType: "text",
2968
+ headers: {
2969
+ COOKIE: cookieHeader
2970
+ }
2971
+ });
2972
+ return result;
2973
+ } catch (error) {
1857
2974
  if (error.status >= 400 && error.status < 500 && !!error.response.data) {
1858
2975
  return error.response.data;
1859
2976
  } else {
1860
2977
  throw error;
1861
2978
  }
1862
- });
2979
+ }
1863
2980
  };
1864
2981
  function isRecord2(value) {
1865
2982
  return typeof value === "object" && value !== null;
@@ -1893,7 +3010,7 @@ var renderComponentForPlaceholder = (indexForThisRender, localRenderPlaceholder,
1893
3010
  );
1894
3011
  }
1895
3012
  const resolvedPath = normalizePath2(
1896
- path3.resolve(webRoot2, partialPath, componentFileName)
3013
+ path6.resolve(webRoot2, partialPath, componentFileName)
1897
3014
  );
1898
3015
  const entryPointPath = [
1899
3016
  "@projects",
@@ -2003,7 +3120,7 @@ async function proxySpecificPage(request2, response, portalId, hublet, contentId
2003
3120
  false,
2004
3121
  jsRenderingGates
2005
3122
  );
2006
- const pageHtml = await makeProxyPreviewRequest(
3123
+ let pageHtml = (await makeProxyPreviewRequest(
2007
3124
  accountId,
2008
3125
  urlToProxy,
2009
3126
  previewKey,
@@ -2011,148 +3128,163 @@ async function proxySpecificPage(request2, response, portalId, hublet, contentId
2011
3128
  projectName,
2012
3129
  environmentConfig,
2013
3130
  jsRenderingGates,
2014
- request2.get("COOKIE")
2015
- );
2016
- const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule(
2017
- "@hubspot/cms-components"
3131
+ request2.get("COOKIE"),
3132
+ request2.app.locals.localPreviewToken
3133
+ )).data;
3134
+ pageHtml = addRefreshScript(pageHtml);
3135
+ await infillReactModulesAndWriteResponse(
3136
+ response,
3137
+ pageHtml,
3138
+ webRoot2,
3139
+ fullOriginalUrl,
3140
+ environmentConfig,
3141
+ viteServer,
3142
+ projectName,
3143
+ projectComponentPath,
3144
+ jsRenderingGates,
3145
+ prettyPrint
2018
3146
  );
2019
- const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
2020
- const numPlaceholders = localRenderPlaceholders.length;
2021
- let numJsRenderFailures = 0;
2022
- let islands = [];
2023
- let mergedPerRequestState = /* @__PURE__ */ new Map();
2024
- let basePath;
2025
- const criticalDevErrors = [];
2026
- const renderPromisesByChunkIndex = new Array(
2027
- numPlaceholders
3147
+ } catch (error) {
3148
+ response.status(500).end(
3149
+ `Failed proxy render of page id = ${contentId} hub id = ${portalId}
3150
+
3151
+ ${error.stack}`
2028
3152
  );
2029
- if (localRenderPlaceholders.length > 0) {
2030
- let offsetSoFar = 0;
2031
- const pageChunks = new Array(numPlaceholders + 1);
2032
- for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
2033
- const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
2034
- pageChunks[indexForThisRender] = pageHtml.slice(
2035
- offsetSoFar,
2036
- localRenderPlaceholder.startOffset
3153
+ return;
3154
+ }
3155
+ }
3156
+ async function infillReactModulesAndWriteResponse(response, pageHtml, webRoot2, fullOriginalUrl, environmentConfig, viteServer, projectName, projectComponentPath, jsRenderingGates, prettyPrint) {
3157
+ const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule(
3158
+ "@hubspot/cms-components"
3159
+ );
3160
+ const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);
3161
+ const numPlaceholders = localRenderPlaceholders.length;
3162
+ let numJsRenderFailures = 0;
3163
+ let islands = [];
3164
+ let mergedPerRequestState = /* @__PURE__ */ new Map();
3165
+ let basePath;
3166
+ const criticalDevErrors = [];
3167
+ const renderPromisesByChunkIndex = new Array(
3168
+ numPlaceholders
3169
+ );
3170
+ if (localRenderPlaceholders.length > 0) {
3171
+ let offsetSoFar = 0;
3172
+ const pageChunks = new Array(numPlaceholders + 1);
3173
+ for (let indexForThisRender = 0; indexForThisRender < numPlaceholders; indexForThisRender++) {
3174
+ const localRenderPlaceholder = localRenderPlaceholders[indexForThisRender];
3175
+ pageChunks[indexForThisRender] = pageHtml.slice(
3176
+ offsetSoFar,
3177
+ localRenderPlaceholder.startOffset
3178
+ );
3179
+ if (basePath === void 0) {
3180
+ basePath = getEntryPointBasePathFromProxyRequest(
3181
+ localRenderPlaceholder.json.request
2037
3182
  );
2038
- if (basePath === void 0) {
2039
- basePath = getEntryPointBasePathFromProxyRequest(
2040
- localRenderPlaceholder.json.request
2041
- );
3183
+ }
3184
+ const renderPromise = renderComponentForPlaceholder(
3185
+ indexForThisRender,
3186
+ localRenderPlaceholder,
3187
+ webRoot2,
3188
+ viteServer,
3189
+ fullOriginalUrl,
3190
+ basePath,
3191
+ environmentConfig,
3192
+ projectName,
3193
+ projectComponentPath
3194
+ );
3195
+ renderPromisesByChunkIndex[indexForThisRender] = renderPromise.then((promiseResult) => {
3196
+ var _a;
3197
+ let { html, cssNeeded, inlineAssets, renderContext } = promiseResult;
3198
+ console.log(
3199
+ `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`
3200
+ );
3201
+ if ((_a = renderContext.criticalDevErrors) == null ? void 0 : _a.length) {
3202
+ criticalDevErrors.push(...renderContext.criticalDevErrors);
2042
3203
  }
2043
- const renderPromise = renderComponentForPlaceholder(
2044
- indexForThisRender,
2045
- localRenderPlaceholder,
2046
- webRoot2,
2047
- viteServer,
2048
- fullOriginalUrl,
2049
- basePath,
2050
- environmentConfig,
2051
- projectName,
2052
- projectComponentPath
3204
+ if (renderContext.islands.length > 0) {
3205
+ islands = islands.concat(renderContext.islands);
3206
+ }
3207
+ mergedPerRequestState = mergeServerRequestData_internal(
3208
+ mergedPerRequestState,
3209
+ renderContext.perServerRequestData
2053
3210
  );
2054
- renderPromisesByChunkIndex[indexForThisRender] = renderPromise.then((promiseResult) => {
2055
- var _a;
2056
- let { html, cssNeeded, inlineAssets, renderContext } = promiseResult;
2057
- console.log(
2058
- `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`
2059
- );
2060
- if ((_a = renderContext.criticalDevErrors) == null ? void 0 : _a.length) {
2061
- criticalDevErrors.push(...renderContext.criticalDevErrors);
2062
- }
2063
- if (renderContext.islands.length > 0) {
2064
- islands = islands.concat(renderContext.islands);
2065
- }
2066
- mergedPerRequestState = mergeServerRequestData_internal(
2067
- mergedPerRequestState,
2068
- renderContext.perServerRequestData
2069
- );
2070
- let result = html;
2071
- if (inlineAssets) {
2072
- result = `${inlineAssets.map((inlineAsset) => inlineAsset.html).join("\n")}
3211
+ let result = html;
3212
+ if (inlineAssets) {
3213
+ result = `${inlineAssets.map((inlineAsset) => inlineAsset.html).join("\n")}
2073
3214
  ${result}`;
2074
- }
2075
- if (cssNeeded) {
2076
- result = `${cssNeeded}
3215
+ }
3216
+ if (cssNeeded) {
3217
+ result = `${cssNeeded}
2077
3218
  ${result}`;
2078
- }
2079
- return result;
2080
- }).catch((e) => {
2081
- numJsRenderFailures += 1;
2082
- console.log(
2083
- "Attempted to render",
2084
- localRenderPlaceholder.path,
2085
- "with props",
2086
- localRenderPlaceholder.json
2087
- );
2088
- console.error(e);
2089
- return renderLocalError_default(localRenderPlaceholder.path, e);
2090
- });
2091
- offsetSoFar = localRenderPlaceholder.endOffset;
2092
- }
2093
- pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
2094
- response.writeHead(200);
2095
- for (let i = 0; i < localRenderPlaceholders.length; i++) {
2096
- const chunk = pageChunks[i];
2097
- response.write(chunk);
2098
- const foobar = await renderPromisesByChunkIndex[i];
2099
- response.write(foobar);
2100
- }
3219
+ }
3220
+ return result;
3221
+ }).catch((e) => {
3222
+ numJsRenderFailures += 1;
3223
+ console.log(
3224
+ "Attempted to render",
3225
+ localRenderPlaceholder.path,
3226
+ "with props",
3227
+ localRenderPlaceholder.json
3228
+ );
3229
+ console.error(e);
3230
+ return renderLocalError_default(localRenderPlaceholder.path, e);
3231
+ });
3232
+ offsetSoFar = localRenderPlaceholder.endOffset;
3233
+ }
3234
+ pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);
3235
+ response.writeHead(200);
3236
+ for (let i = 0; i < localRenderPlaceholders.length; i++) {
3237
+ const chunk = pageChunks[i];
3238
+ response.write(chunk);
3239
+ const foobar = await renderPromisesByChunkIndex[i];
3240
+ response.write(foobar);
3241
+ }
3242
+ response.write(
3243
+ getServerGlobalsToInject(
3244
+ environmentConfig,
3245
+ fullOriginalUrl,
3246
+ basePath,
3247
+ void 0,
3248
+ criticalDevErrors
3249
+ )
3250
+ );
3251
+ if (criticalDevErrors.length) {
2101
3252
  response.write(
2102
- getServerGlobalsToInject(
2103
- environmentConfig,
2104
- fullOriginalUrl,
2105
- basePath,
2106
- void 0,
2107
- criticalDevErrors
3253
+ scriptTagToLogServerMessages(
3254
+ criticalDevErrorsToServerMessages_default(criticalDevErrors),
3255
+ "@hubspot/cms-dev-server messages"
2108
3256
  )
2109
3257
  );
2110
- if (criticalDevErrors.length) {
2111
- response.write(
2112
- scriptTagToLogServerMessages(
2113
- criticalDevErrorsToServerMessages_default(criticalDevErrors),
2114
- "@hubspot/cms-dev-server messages"
2115
- )
2116
- );
2117
- }
2118
- if (islands.length > 0) {
2119
- const sortedIslandRoots = sortIslandRootsByPriority(islands);
2120
- const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
2121
- sortedIslandRoots,
2122
- mergedPerRequestState,
2123
- viteServer,
2124
- jsRenderingGates,
2125
- prettyPrint
2126
- );
2127
- response.write(islandRuntimeAndGlobalScriptHtml);
2128
- }
2129
- response.write(pageChunks[pageChunks.length - 1]);
2130
- response.end();
2131
- } else {
2132
- response.writeHead(200);
2133
- response.write(pageHtml);
2134
- response.end();
2135
3258
  }
2136
- } catch (error) {
2137
- response.status(500).end(
2138
- `Failed proxy render of page id = ${contentId} hub id = ${portalId}
2139
-
2140
- ${error.stack}`
2141
- );
2142
- return;
3259
+ if (islands.length > 0) {
3260
+ const sortedIslandRoots = sortIslandRootsByPriority(islands);
3261
+ const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(
3262
+ sortedIslandRoots,
3263
+ mergedPerRequestState,
3264
+ viteServer,
3265
+ jsRenderingGates,
3266
+ prettyPrint
3267
+ );
3268
+ response.write(islandRuntimeAndGlobalScriptHtml);
3269
+ }
3270
+ response.write(pageChunks[pageChunks.length - 1]);
3271
+ response.end();
3272
+ } else {
3273
+ response.writeHead(200);
3274
+ response.write(pageHtml);
3275
+ response.end();
2143
3276
  }
2144
3277
  }
2145
3278
 
2146
3279
  // src/lib/renderModulePreview.ts
2147
- import localDevHttpImport6 from "@hubspot/local-dev-lib/http";
3280
+ import { http as hsCliHttp7 } from "@hubspot/local-dev-lib/http";
2148
3281
  import jsdom from "jsdom";
2149
3282
  var { JSDOM } = jsdom;
2150
- var { default: hsCliHttp6 } = localDevHttpImport6;
2151
3283
  async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv, cookieValue) {
2152
3284
  const moduleInfoQueryParams = new URLSearchParams({
2153
3285
  portalId: `${authedPortalId}`
2154
3286
  });
2155
- const moduleInfo = await hsCliHttp6.get(authedPortalId, {
3287
+ const moduleInfo = (await hsCliHttp7.get(authedPortalId, {
2156
3288
  url: `/api/designmanager/v1/modules/by-path/${encodeURIComponent(
2157
3289
  modulePath
2158
3290
  )}?${moduleInfoQueryParams}`,
@@ -2162,7 +3294,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2162
3294
  cookie: cookieValue,
2163
3295
  "User-Agent": "HubSpot CMS Dev Server"
2164
3296
  }
2165
- });
3297
+ })).data;
2166
3298
  const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2167
3299
  process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2168
3300
  const queryParams = new URLSearchParams({
@@ -2172,7 +3304,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2172
3304
  hsLoginVerifyDisabled: `${true}`,
2173
3305
  module_id: moduleInfo.moduleId
2174
3306
  });
2175
- const modulePreviewHtml = await hsCliHttp6.get(authedPortalId, {
3307
+ const modulePreviewHtml = (await hsCliHttp7.get(authedPortalId, {
2176
3308
  url: `/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`,
2177
3309
  headers: {
2178
3310
  ["content-type"]: "application/x-www-form-urlencoded",
@@ -2181,7 +3313,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2181
3313
  cookie: cookieValue,
2182
3314
  "User-Agent": "HubSpot CMS Dev Server"
2183
3315
  }
2184
- });
3316
+ })).data;
2185
3317
  if (currentHubApiDomainOverride) {
2186
3318
  process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2187
3319
  } else {
@@ -2196,7 +3328,7 @@ async function renderRemoteModulePreview(modulePath, authedPortalId, authedEnv,
2196
3328
  }
2197
3329
  async function renderLocalProjectModulePreview(moduleName, authedPortalId, authedEnv, authedHublet, webRoot2, viteServer, jsRenderingGates, projectName, projectComponentPath, fullOriginalUrl, cookieValue) {
2198
3330
  const modulePath = normalizePath3(
2199
- path4.resolve(webRoot2, "components/modules/", moduleName)
3331
+ path7.resolve(webRoot2, "components/modules/", moduleName)
2200
3332
  );
2201
3333
  const basePath = `preview/${getEntryPointBasePath(modulePath)}`;
2202
3334
  const environmentConfig = buildStaticEnvConfig2(
@@ -2253,7 +3385,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
2253
3385
  });
2254
3386
  const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;
2255
3387
  process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;
2256
- const templatePreview = await hsCliHttp6.post(authedPortalId, {
3388
+ const templatePreview = (await hsCliHttp7.post(authedPortalId, {
2257
3389
  url: `/api/cos-rendering/v1/public/_hcms/preview/template/multiform?${queryParams}`,
2258
3390
  headers: {
2259
3391
  ["content-type"]: "application/x-www-form-urlencoded",
@@ -2263,7 +3395,7 @@ async function renderLocalProjectModulePreview(moduleName, authedPortalId, authe
2263
3395
  "User-Agent": "HubSpot CMS Dev Server"
2264
3396
  },
2265
3397
  data: `module=${encodeURIComponent(JSON.stringify(localModule))}`
2266
- });
3398
+ })).data;
2267
3399
  if (currentHubApiDomainOverride) {
2268
3400
  process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;
2269
3401
  } else {
@@ -2310,7 +3442,7 @@ var partialRouteHandler = async (request2, response) => {
2310
3442
  "html/baseTemplate.html"
2311
3443
  );
2312
3444
  const partialPath = normalizePath4(
2313
- path5.resolve(webRoot2, "components/partials/", partialName)
3445
+ path8.resolve(webRoot2, "components/partials/", partialName)
2314
3446
  );
2315
3447
  const entrypointPath = normalizePath4(
2316
3448
  [
@@ -2396,7 +3528,7 @@ var partialRouteHandler = async (request2, response) => {
2396
3528
  continue;
2397
3529
  localProjectModulePreviewPromises.push(
2398
3530
  renderLocalProjectModulePreview(
2399
- path5.basename(localProjectModule.path),
3531
+ path8.basename(localProjectModule.path),
2400
3532
  authedPortalId,
2401
3533
  authedEnv,
2402
3534
  authedHublet,
@@ -2534,7 +3666,7 @@ var linksToAllModulesRouteHandler_default = linksToAllModuleRouteHandler;
2534
3666
 
2535
3667
  // src/routes/module.ts
2536
3668
  import { buildStaticEnvConfig as buildStaticEnvConfig4 } from "@hubspot/cms-components";
2537
- import path6 from "path";
3669
+ import path9 from "path";
2538
3670
  import { normalizePath as normalizePath5 } from "vite";
2539
3671
  var moduleRouteHandler = async (request2, response) => {
2540
3672
  sendTrackingRequest("view-module-route");
@@ -2554,7 +3686,7 @@ var moduleRouteHandler = async (request2, response) => {
2554
3686
  "html/baseTemplate.html"
2555
3687
  );
2556
3688
  const modulePath = normalizePath5(
2557
- path6.resolve(webRoot2, "components/modules/", moduleName)
3689
+ path9.resolve(webRoot2, "components/modules/", moduleName)
2558
3690
  );
2559
3691
  const entrypointPath = normalizePath5(
2560
3692
  [
@@ -2638,16 +3770,16 @@ var module_default = moduleRouteHandler;
2638
3770
  import http from "http";
2639
3771
  import https from "https";
2640
3772
  import { getAccountId as getAccountId2 } from "@hubspot/local-dev-lib/config";
2641
- async function requestPage(url3, redirects = 0, originalUrl) {
3773
+ async function requestPage(url4, redirects = 0, originalUrl) {
2642
3774
  if (redirects > 5) {
2643
3775
  throw new Error(
2644
3776
  `Hit too many redirects to HEAD requests for ${originalUrl}`
2645
3777
  );
2646
3778
  }
2647
3779
  return new Promise((resolve3, reject) => {
2648
- const protocolAPI = url3.startsWith("https://") ? https : http;
3780
+ const protocolAPI = url4.startsWith("https://") ? https : http;
2649
3781
  protocolAPI.request(
2650
- url3,
3782
+ url4,
2651
3783
  {
2652
3784
  method: "HEAD",
2653
3785
  headers: {
@@ -2674,12 +3806,12 @@ async function requestPage(url3, redirects = 0, originalUrl) {
2674
3806
  }
2675
3807
  }
2676
3808
  if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
2677
- console.log(`Redirecting to ${res.headers.location} (from ${url3})`);
3809
+ console.log(`Redirecting to ${res.headers.location} (from ${url4})`);
2678
3810
  return resolve3(
2679
3811
  requestPage(
2680
3812
  res.headers.location,
2681
3813
  redirects + 1,
2682
- originalUrl ?? url3
3814
+ originalUrl ?? url4
2683
3815
  )
2684
3816
  );
2685
3817
  }
@@ -2697,11 +3829,11 @@ async function requestPage(url3, redirects = 0, originalUrl) {
2697
3829
  }).end();
2698
3830
  });
2699
3831
  }
2700
- async function fetchContentMetadata(url3, portalId) {
2701
- const { portalIdHeader, contentId, res } = await requestPage(url3);
3832
+ async function fetchContentMetadata(url4, portalId) {
3833
+ const { portalIdHeader, contentId, res } = await requestPage(url4);
2702
3834
  if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {
2703
3835
  throw new Error(
2704
- `There were multiple hub ID or content ID headers in the HEAD request to ${url3}`
3836
+ `There were multiple hub ID or content ID headers in the HEAD request to ${url4}`
2705
3837
  );
2706
3838
  } else {
2707
3839
  const portalIdFromResponse = parseInt(portalIdHeader, 10);
@@ -2713,15 +3845,15 @@ async function fetchContentMetadata(url3, portalId) {
2713
3845
  }
2714
3846
  if (res.statusCode !== 200 && !(portalIdFromResponse && pageAccount && contentId)) {
2715
3847
  throw new Error(
2716
- `${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.` : ""}`
3848
+ `${res.statusCode} ${res.statusMessage} - Unable to obtain HEAD information from ${url4}. ${res.statusCode === 429 && res.headers["retry-after"] ? `Retry after ${res.headers["retry-after"]} seconds.` : ""}`
2717
3849
  );
2718
3850
  } else if (!portalId || !contentId) {
2719
3851
  throw new Error(
2720
- `Missing hub ID or content ID headers on HEAD request to ${url3}`
3852
+ `Missing hub ID or content ID headers on HEAD request to ${url4}`
2721
3853
  );
2722
3854
  } else if (isNaN(portalId)) {
2723
3855
  throw new Error(
2724
- `Hub ID from the HEAD request is not a number: '${portalId}' (${url3})`
3856
+ `Hub ID from the HEAD request is not a number: '${portalId}' (${url4})`
2725
3857
  );
2726
3858
  }
2727
3859
  const hublet = "na1";
@@ -2828,8 +3960,51 @@ function proxyPageResourceRedirect(req, res, next) {
2828
3960
  }
2829
3961
  }
2830
3962
 
3963
+ // src/components/HubLModulesList.tsx
3964
+ import { jsx as jsx6 } from "react/jsx-runtime";
3965
+ function HubLModulesList({ modules }) {
3966
+ return modules.length === 0 ? /* @__PURE__ */ jsx6("p", { children: "No modules found." }) : /* @__PURE__ */ jsx6("ul", { children: modules.map((module) => /* @__PURE__ */ jsx6("li", { children: /* @__PURE__ */ jsx6("a", { href: `/hublmodule/${removePreviewPrefix(module.path)}`, children: removePreviewPrefix(module.path) }) }, module.moduleId)) });
3967
+ }
3968
+
3969
+ // src/api/designmanager.ts
3970
+ import { http as hsCliHttp8 } from "@hubspot/local-dev-lib/http";
3971
+ var DESIGN_MANAGER_API_PATH = "designmanager/v1";
3972
+ async function fetchHubLModules(accountId, previewToken) {
3973
+ return (await hsCliHttp8.get(accountId, {
3974
+ url: `${DESIGN_MANAGER_API_PATH}/modules/local-preview?previewToken=${previewToken}`
3975
+ })).data;
3976
+ }
3977
+ async function fetchPreviewTemplates(accountId, previewToken) {
3978
+ return (await hsCliHttp8.get(accountId, {
3979
+ url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}`
3980
+ })).data;
3981
+ }
3982
+ async function fetchModuleByPath(accountId, path15) {
3983
+ return (await hsCliHttp8.get(accountId, {
3984
+ url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path15}?portalId=${accountId}`
3985
+ })).data;
3986
+ }
3987
+ async function fetchTemplateByPath(accountId, path15) {
3988
+ return (await hsCliHttp8.get(accountId, {
3989
+ url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path15}?portalId=${accountId}`
3990
+ })).data;
3991
+ }
3992
+
3993
+ // src/components/HubLTemplatesList.tsx
3994
+ import { jsx as jsx7, jsxs as jsxs3 } from "react/jsx-runtime";
3995
+ function HubLTemplatesList({ templates }) {
3996
+ return templates.length === 0 ? /* @__PURE__ */ jsxs3("p", { children: [
3997
+ "No templates found ",
3998
+ JSON.stringify(templates)
3999
+ ] }) : /* @__PURE__ */ jsx7("ul", { children: templates.filter((t2) => isCodedFile(t2.filename)).map((template) => /* @__PURE__ */ jsx7("li", { children: /* @__PURE__ */ jsx7("a", { href: `/template/${removePreviewPrefix(template.path)}`, children: removePreviewPrefix(template.path) }) }, template.previewKey)) });
4000
+ }
4001
+ var TEMPLATE_EXTENSION_REGEX = new RegExp(/(?<!module)\.html$/);
4002
+ function isCodedFile(filePath) {
4003
+ return TEMPLATE_EXTENSION_REGEX.test(filePath);
4004
+ }
4005
+
2831
4006
  // src/routes/homeRouteHandler.tsx
2832
- import { Fragment, jsx as jsx6, jsxs as jsxs3 } from "react/jsx-runtime";
4007
+ import { Fragment, jsx as jsx8, jsxs as jsxs4 } from "react/jsx-runtime";
2833
4008
  var homeRouteHandler = async (request2, response, next) => {
2834
4009
  const domainToProxy = getSubDomainFromValidLocalDomain(request2.hostname);
2835
4010
  if (domainToProxy) {
@@ -2837,16 +4012,40 @@ var homeRouteHandler = async (request2, response, next) => {
2837
4012
  return;
2838
4013
  }
2839
4014
  sendTrackingRequest("view-home-route");
2840
- const { webRoot: webRoot2, storybookEnabled, devServerPort } = request2.app.locals;
4015
+ const {
4016
+ authedPortalId,
4017
+ webRoot: webRoot2,
4018
+ storybookEnabled,
4019
+ devServerPort,
4020
+ localPreviewToken,
4021
+ jsRenderingGates
4022
+ } = request2.app.locals;
4023
+ const isUngatedForUnifiedThemePreview = jsRenderingGates.includes(
4024
+ "CMS:React:UnifiedThemePreview"
4025
+ );
2841
4026
  const { partialNames } = findAllPartialsInRoot(webRoot2);
2842
4027
  const { moduleNames } = findAllModulesInRoot(webRoot2);
4028
+ const hublModuleData = await fetchHubLModules(
4029
+ authedPortalId,
4030
+ localPreviewToken
4031
+ );
4032
+ const hublTemplateData = await fetchPreviewTemplates(
4033
+ authedPortalId,
4034
+ localPreviewToken
4035
+ );
2843
4036
  const { html: responseHtml } = await renderOnServer(
2844
- /* @__PURE__ */ jsxs3(Fragment, { children: [
2845
- storybookEnabled ? /* @__PURE__ */ jsx6("h2", { children: /* @__PURE__ */ jsx6("a", { href: `//storybook.${request2.hostname}:${devServerPort}`, children: "Storybook" }) }) : null,
2846
- /* @__PURE__ */ jsx6("h2", { children: "Partials" }),
2847
- /* @__PURE__ */ jsx6(PartialsList, { webRoot: webRoot2, partialNames }),
2848
- /* @__PURE__ */ jsx6("h2", { children: "Modules" }),
2849
- /* @__PURE__ */ jsx6(ModulesList_default, { webRoot: webRoot2, moduleNames })
4037
+ /* @__PURE__ */ jsxs4(Fragment, { children: [
4038
+ storybookEnabled ? /* @__PURE__ */ jsx8("h2", { children: /* @__PURE__ */ jsx8("a", { href: `//storybook.${request2.hostname}:${devServerPort}`, children: "Storybook" }) }) : null,
4039
+ /* @__PURE__ */ jsx8("h2", { children: "Partials" }),
4040
+ /* @__PURE__ */ jsx8(PartialsList, { webRoot: webRoot2, partialNames }),
4041
+ /* @__PURE__ */ jsx8("h2", { children: "React modules" }),
4042
+ /* @__PURE__ */ jsx8(ModulesList_default, { webRoot: webRoot2, moduleNames }),
4043
+ isUngatedForUnifiedThemePreview && /* @__PURE__ */ jsxs4(Fragment, { children: [
4044
+ /* @__PURE__ */ jsx8("h2", { children: "HubL modules" }),
4045
+ /* @__PURE__ */ jsx8(HubLModulesList, { modules: hublModuleData.objects }),
4046
+ /* @__PURE__ */ jsx8("h2", { children: "HubL templates" }),
4047
+ /* @__PURE__ */ jsx8(HubLTemplatesList, { templates: hublTemplateData.objects })
4048
+ ] })
2850
4049
  ] })
2851
4050
  );
2852
4051
  response.status(200).set({ "Content-Type": "text/html" }).end(responseHtml);
@@ -2854,7 +4053,7 @@ var homeRouteHandler = async (request2, response, next) => {
2854
4053
  var homeRouteHandler_default = homeRouteHandler;
2855
4054
 
2856
4055
  // src/routes/proxyPathPageRouteHandler.tsx
2857
- import { jsx as jsx7, jsxs as jsxs4 } from "react/jsx-runtime";
4056
+ import { jsx as jsx9, jsxs as jsxs5 } from "react/jsx-runtime";
2858
4057
  async function proxyPathPageRouteHandler(request2, response, next) {
2859
4058
  sendTrackingRequest("view-proxy-path-route");
2860
4059
  const {
@@ -2869,11 +4068,11 @@ async function proxyPathPageRouteHandler(request2, response, next) {
2869
4068
  }
2870
4069
  if (!request2.query.page) {
2871
4070
  const { html: responseHtml } = await renderOnServer(
2872
- /* @__PURE__ */ jsxs4("div", { children: [
2873
- /* @__PURE__ */ jsx7("h2", { children: "Local Proxy" }),
2874
- /* @__PURE__ */ jsxs4("form", { action: "/proxy", children: [
2875
- /* @__PURE__ */ jsx7("label", { htmlFor: "page", style: { display: "block" }, children: "Page URL" }),
2876
- /* @__PURE__ */ jsx7(
4071
+ /* @__PURE__ */ jsxs5("div", { children: [
4072
+ /* @__PURE__ */ jsx9("h2", { children: "Local Proxy" }),
4073
+ /* @__PURE__ */ jsxs5("form", { action: "/proxy", children: [
4074
+ /* @__PURE__ */ jsx9("label", { htmlFor: "page", style: { display: "block" }, children: "Page URL" }),
4075
+ /* @__PURE__ */ jsx9(
2877
4076
  "input",
2878
4077
  {
2879
4078
  style: { width: "300px" },
@@ -2882,7 +4081,7 @@ async function proxyPathPageRouteHandler(request2, response, next) {
2882
4081
  placeholder: "https://somecmspage.com/path"
2883
4082
  }
2884
4083
  ),
2885
- /* @__PURE__ */ jsx7("button", { style: { display: "block" }, children: "Proxy" })
4084
+ /* @__PURE__ */ jsx9("button", { style: { display: "block" }, children: "Proxy" })
2886
4085
  ] })
2887
4086
  ] })
2888
4087
  );
@@ -3029,7 +4228,7 @@ function proxyServerlessRequest(req, res, next) {
3029
4228
  }
3030
4229
 
3031
4230
  // src/routes/modulePreviewRouteHandler.ts
3032
- import path7 from "path";
4231
+ import path10 from "path";
3033
4232
  import { normalizePath as normalizePath6 } from "vite";
3034
4233
  async function modulePreviewRouteHandler(request2, response) {
3035
4234
  sendTrackingRequest("view-module-preview-route");
@@ -3045,7 +4244,7 @@ async function modulePreviewRouteHandler(request2, response) {
3045
4244
  } = request2.app.locals;
3046
4245
  const moduleName = request2.params.moduleName;
3047
4246
  const modulePath = normalizePath6(
3048
- path7.resolve(webRoot2, "components/modules/", moduleName)
4247
+ path10.resolve(webRoot2, "components/modules/", moduleName)
3049
4248
  );
3050
4249
  try {
3051
4250
  const {
@@ -3096,6 +4295,147 @@ ${e.stack}`);
3096
4295
  }
3097
4296
  var modulePreviewRouteHandler_default = modulePreviewRouteHandler;
3098
4297
 
4298
+ // src/routes/hublModuleRouteHandler.ts
4299
+ import { http as hsCliHttp9 } from "@hubspot/local-dev-lib/http";
4300
+ var hublModuleRouteHandler = async (request2, response) => {
4301
+ sendTrackingRequest("view-hubl-module-route");
4302
+ const { authedPortalId, localPreviewToken } = request2.app.locals;
4303
+ const { modulePath } = request2.params;
4304
+ if (!modulePath) {
4305
+ response.status(200).set({ "Content-Type": "text/html" }).end(buildModuleIndex());
4306
+ return;
4307
+ }
4308
+ const calculatedPath = `@preview/${localPreviewToken}/${modulePath}.module`;
4309
+ let customWidgetInfo;
4310
+ try {
4311
+ customWidgetInfo = await fetchModuleByPath(authedPortalId, calculatedPath);
4312
+ } catch (err) {
4313
+ console.log(`Failed to fetch module data for ${calculatedPath}`);
4314
+ }
4315
+ const params = {
4316
+ module_id: customWidgetInfo.moduleId,
4317
+ hs_preview_key: customWidgetInfo.previewKey,
4318
+ updated: Date.now(),
4319
+ ...request2.query
4320
+ };
4321
+ const previewUrl = new URL(getPreviewUrl(request2, params));
4322
+ try {
4323
+ const result = (await hsCliHttp9.get(authedPortalId, {
4324
+ baseURL: previewUrl.origin,
4325
+ url: previewUrl.pathname,
4326
+ params
4327
+ })).data;
4328
+ const html = addRefreshScript(result);
4329
+ response.status(200).set({ "Content-Type": "text/html" }).end(html);
4330
+ } catch (err) {
4331
+ console.log(err);
4332
+ response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex(err));
4333
+ }
4334
+ };
4335
+ var buildErrorIndex = (err) => buildHTMLResponse(`
4336
+ <div>
4337
+ <h2>Module</h2>
4338
+ <p>ERROR</p>
4339
+ </div>
4340
+ `);
4341
+ var buildModuleIndex = () => buildHTMLResponse(`
4342
+ <div>
4343
+ <h2>Module</h2>
4344
+ <p>Please provide a module path in the request</p>
4345
+ </div>
4346
+ `);
4347
+
4348
+ // src/routes/hublTemplateRouteHandler.ts
4349
+ import { http as hsCliHttp10 } from "@hubspot/local-dev-lib/http";
4350
+ import {
4351
+ buildStaticEnvConfig as buildStaticEnvConfig5
4352
+ } from "@hubspot/cms-components";
4353
+ import { getEnv as getEnv2 } from "@hubspot/local-dev-lib/config";
4354
+ var templateRouteHandler = async (request2, response) => {
4355
+ sendTrackingRequest("view-template-route");
4356
+ const {
4357
+ authedPortalId,
4358
+ localPreviewToken,
4359
+ projectName,
4360
+ viteServer,
4361
+ webRoot: webRoot2,
4362
+ projectComponentPath,
4363
+ jsRenderingGates
4364
+ } = request2.app.locals;
4365
+ const environmentConfig = buildStaticEnvConfig5(
4366
+ authedPortalId,
4367
+ "na1",
4368
+ getEnv2(authedPortalId),
4369
+ false,
4370
+ jsRenderingGates
4371
+ );
4372
+ const { templatePath } = request2.params;
4373
+ if (!templatePath) {
4374
+ response.status(200).set({ "Content-Type": "text/html" }).end(buildTemplateIndex());
4375
+ return;
4376
+ }
4377
+ const calculatedPath = `@preview/${localPreviewToken}/${templatePath}`;
4378
+ let templateInfo;
4379
+ try {
4380
+ templateInfo = await fetchTemplateByPath(authedPortalId, calculatedPath);
4381
+ } catch (err) {
4382
+ console.error(`Failed to fetch template data for ${calculatedPath}: ${err}`);
4383
+ }
4384
+ if (!templateInfo || !("previewKey" in templateInfo)) {
4385
+ response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex2());
4386
+ return;
4387
+ }
4388
+ const localProxyProject = process.env.DEFAULT_MODULE_PATH_REWRITE ? `@default-modules/${projectName}` : `@projects/${projectName}`;
4389
+ const params = {
4390
+ template_file_path: calculatedPath,
4391
+ hs_preview_key: templateInfo.previewKey,
4392
+ localPreviewToken,
4393
+ hsLocalProxyProject: localProxyProject,
4394
+ localProxySchemaVersion: "2",
4395
+ hsLoginVerifyDisabled: `${true}`,
4396
+ ...request2.query
4397
+ };
4398
+ const previewUrl = new URL(getPreviewUrl(request2, params));
4399
+ try {
4400
+ const result = (await hsCliHttp10.get(authedPortalId, {
4401
+ baseURL: previewUrl.origin,
4402
+ url: previewUrl.pathname,
4403
+ params
4404
+ })).data;
4405
+ const pageHtml = addRefreshScript(result);
4406
+ infillReactModulesAndWriteResponse(
4407
+ response,
4408
+ pageHtml,
4409
+ webRoot2,
4410
+ "fullOriginalUrl",
4411
+ environmentConfig,
4412
+ viteServer,
4413
+ projectName,
4414
+ projectComponentPath,
4415
+ jsRenderingGates,
4416
+ false
4417
+ );
4418
+ } catch (err) {
4419
+ response.status(500).set({ "Content-Type": "text/html" }).end(buildErrorIndex2());
4420
+ }
4421
+ };
4422
+ function buildErrorIndex2() {
4423
+ return buildHTMLResponse(`
4424
+ <div>
4425
+ <h2>Error</h2>
4426
+ <p>Failed to fetch template data.</p>
4427
+ </div>
4428
+ `);
4429
+ }
4430
+ function buildTemplateIndex() {
4431
+ return buildHTMLResponse(`
4432
+ <div>
4433
+ <h2>Template</h2>
4434
+ <p>Please provide a template path in the request</p>
4435
+ </div>
4436
+ `);
4437
+ }
4438
+
3099
4439
  // src/routes/createDevServerRoutes.ts
3100
4440
  var STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(
3101
4441
  (domain) => `storybook.${domain}`
@@ -3103,8 +4443,8 @@ var STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(
3103
4443
  var createDevServerRoutes = async (viteServer, storybookPort) => {
3104
4444
  const devServerApp = Router();
3105
4445
  devServerApp.use((request2, response, next) => {
3106
- const { method, url: url3, hostname } = request2;
3107
- debug(`${method}:${hostname}${url3}`);
4446
+ const { method, url: url4, hostname } = request2;
4447
+ debug(`${method}:${hostname}${url4}`);
3108
4448
  next();
3109
4449
  });
3110
4450
  if (storybookPort) {
@@ -3123,10 +4463,13 @@ var createDevServerRoutes = async (viteServer, storybookPort) => {
3123
4463
  devServerApp.get("/partials/", linksToAllPartialsRouteHandler_default);
3124
4464
  devServerApp.get("/partial/:partial", partial_default);
3125
4465
  devServerApp.get("/partial/:partial/*", partial_default);
4466
+ devServerApp.get("/remote-fs-dirty", remoteFsDirtyHandler);
3126
4467
  devServerApp.get("/preview/module/:moduleName", modulePreviewRouteHandler_default);
3127
4468
  devServerApp.get("/modules/", linksToAllModulesRouteHandler_default);
3128
4469
  devServerApp.get("/module/:moduleName", module_default);
3129
4470
  devServerApp.get("/module/:moduleName/*", module_default);
4471
+ devServerApp.get("/hublmodule/:modulePath(*)", hublModuleRouteHandler);
4472
+ devServerApp.get("/template/:templatePath(*)", templateRouteHandler);
3130
4473
  devServerApp.all("/hs/serverless/*", proxyServerlessRequest);
3131
4474
  devServerApp.all("/_hcms/api/*", proxyServerlessRequest);
3132
4475
  devServerApp.get("/", homeRouteHandler_default);
@@ -3148,9 +4491,12 @@ import express from "express";
3148
4491
 
3149
4492
  // src/shadowDevServer/createShadowDevServerRoutes.ts
3150
4493
  import { Router as Router2 } from "express";
3151
- import { getAccountId as getAccountId3, getEnv as getEnv2 } from "@hubspot/local-dev-lib/config";
4494
+ import { getAccountId as getAccountId3, getEnv as getEnv3 } from "@hubspot/local-dev-lib/config";
3152
4495
  import cors from "cors";
3153
- import { buildStaticEnvConfig as buildStaticEnvConfig5 } from "@hubspot/cms-components";
4496
+ import { exec } from "child_process";
4497
+ import path11 from "path";
4498
+ import url2 from "url";
4499
+ import { buildStaticEnvConfig as buildStaticEnvConfig6 } from "@hubspot/cms-components";
3154
4500
  function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
3155
4501
  return async function shadowDevServerCheckHandler(request2, response) {
3156
4502
  const { query } = request2;
@@ -3173,7 +4519,7 @@ function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
3173
4519
  if (accountId === null) {
3174
4520
  throw new Error();
3175
4521
  }
3176
- proxyEnv = getEnv2(accountId);
4522
+ proxyEnv = getEnv3(accountId);
3177
4523
  } catch (e) {
3178
4524
  response.status(500).end(
3179
4525
  `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`
@@ -3187,7 +4533,7 @@ function getShadowDevServerCheckHandler(devServerPort, projectName, gates) {
3187
4533
  contentId
3188
4534
  );
3189
4535
  const { previewKey } = previewInfo;
3190
- const environmentConfig = buildStaticEnvConfig5(
4536
+ const environmentConfig = buildStaticEnvConfig6(
3191
4537
  portalId,
3192
4538
  "na1",
3193
4539
  // bad lazy TF (but does it really matter for this check)
@@ -3225,6 +4571,40 @@ ${error.stack}`
3225
4571
  }
3226
4572
  };
3227
4573
  }
4574
+ function getRunTestsHandler() {
4575
+ return async function runTestsHandler(request2, response) {
4576
+ const cmsDevServerPath = path11.join(
4577
+ path11.dirname(url2.fileURLToPath(import.meta.url)),
4578
+ "../.."
4579
+ );
4580
+ exec("npm run test", { cwd: cmsDevServerPath }, (error, stdout, stderr) => {
4581
+ if (error) {
4582
+ response.status(500).json({ error: stderr });
4583
+ return;
4584
+ }
4585
+ response.status(200).json({ response: stdout });
4586
+ });
4587
+ };
4588
+ }
4589
+ function getRunBuildHandler() {
4590
+ return async function runTestsHandler(request2, response) {
4591
+ const cmsDevServerPath = path11.join(
4592
+ path11.dirname(url2.fileURLToPath(import.meta.url)),
4593
+ "../.."
4594
+ );
4595
+ exec(
4596
+ "npm run build",
4597
+ { cwd: cmsDevServerPath },
4598
+ (error, stdout, stderr) => {
4599
+ if (error) {
4600
+ response.status(500).json({ error: stderr });
4601
+ return;
4602
+ }
4603
+ response.status(200).json({ response: stdout });
4604
+ }
4605
+ );
4606
+ };
4607
+ }
3228
4608
  async function createShadowDevServerRoutes(devServerPort, projectName, gates) {
3229
4609
  const shadowDevServerRoutes = Router2();
3230
4610
  shadowDevServerRoutes.get(
@@ -3232,6 +4612,8 @@ async function createShadowDevServerRoutes(devServerPort, projectName, gates) {
3232
4612
  cors(),
3233
4613
  getShadowDevServerCheckHandler(devServerPort, projectName, gates)
3234
4614
  );
4615
+ shadowDevServerRoutes.get("/test", cors(), getRunTestsHandler());
4616
+ shadowDevServerRoutes.get("/build", cors(), getRunBuildHandler());
3235
4617
  return shadowDevServerRoutes;
3236
4618
  }
3237
4619
 
@@ -3305,6 +4687,23 @@ function devSecretsPlugin(secretNames) {
3305
4687
  }
3306
4688
 
3307
4689
  // src/createViteDevServer.ts
4690
+ import { readFileSync as readFileSync3 } from "fs";
4691
+ import { join as join4 } from "path";
4692
+ function getPackageJson(packagePath2) {
4693
+ return JSON.parse(readFileSync3(join4(packagePath2, "package.json")).toString());
4694
+ }
4695
+ function getDepsForPackage(packagePath2) {
4696
+ const packageJson = getPackageJson(packagePath2);
4697
+ return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];
4698
+ }
4699
+ function getDepsForPackageIfExists(packagePath2) {
4700
+ try {
4701
+ return getDepsForPackage(packagePath2);
4702
+ } catch (e) {
4703
+ console.log("No package.json at ", packagePath2);
4704
+ return [];
4705
+ }
4706
+ }
3308
4707
  async function createViteDevServer(webRoot2, port, sslEnabled, domainsToProxy = [], jsRenderingGates, secretNames) {
3309
4708
  const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
3310
4709
  `${proxyDomain}.localhost`,
@@ -3316,21 +4715,78 @@ Custom origin: ${process.env.VITE_ORIGIN}
3316
4715
  `);
3317
4716
  }
3318
4717
  const origin = process.env.VITE_ORIGIN ?? (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);
4718
+ const consumerDeps = getDepsForPackageIfExists(webRoot2);
4719
+ const isProjectWithReact = consumerDeps.includes("@hubspot/cms-components");
4720
+ const ssrAndOptimizeDep = isProjectWithReact ? {
4721
+ ssr: {
4722
+ // TODO: might need more entries here to get things to resolve through
4723
+ // resolveWebRootDepsPlugin
4724
+ noExternal: "@hubspot/cms-components"
4725
+ },
4726
+ resolve: {
4727
+ conditions: ["server"],
4728
+ dedupe: ["react", "react-dom", "@hubspot/cms-components", "styled-jsx"]
4729
+ },
4730
+ optimizeDeps: {
4731
+ include: ["react", "react-dom", "react-dom/client"]
4732
+ }
4733
+ } : {};
4734
+ const reactAndIslandsPlugins = isProjectWithReact || process.env.VITEST ? [
4735
+ react({
4736
+ babel: {
4737
+ plugins: [
4738
+ "babel-plugin-styled-components",
4739
+ "styled-jsx/babel",
4740
+ "macros"
4741
+ ]
4742
+ }
4743
+ }),
4744
+ clientIslandEntryPlugin(),
4745
+ resolveIslandPlugin(),
4746
+ jsRenderingGates.includes("CMS:JSRenderer:RemoveCjsPlugin") ? null : viteCommonjs(),
4747
+ devSecretsPlugin(secretNames),
4748
+ noncePlaceholderPlugin()
4749
+ ] : [];
3319
4750
  const viteConfig = {
3320
4751
  appType: "custom",
3321
4752
  server: {
3322
4753
  middlewareMode: true,
3323
4754
  host: "hslocal.net",
3324
4755
  origin,
3325
- https: sslEnabled,
3326
4756
  hmr: {
3327
4757
  protocol: sslEnabled ? "wss" : void 0
3328
4758
  }
3329
4759
  },
3330
4760
  root: webRoot2,
4761
+ ...ssrAndOptimizeDep,
4762
+ plugins: [
4763
+ jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
4764
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
4765
+ ...reactAndIslandsPlugins
4766
+ ],
4767
+ css: {
4768
+ postcss: webRoot2
4769
+ },
4770
+ envDir: webRoot2,
4771
+ envPrefix: "HS_"
4772
+ };
4773
+ return createViteServer(viteConfig);
4774
+ }
4775
+ var createViteDevServer_default = createViteDevServer;
4776
+
4777
+ // src/createAppServer.ts
4778
+ import { createServer as createViteServer2 } from "vite";
4779
+ import { default as react2 } from "@vitejs/plugin-react";
4780
+ async function createAppServer(webRoot2, port) {
4781
+ const origin = `http://hslocal.net:${port}`;
4782
+ const viteConfig = {
4783
+ server: {
4784
+ middlewareMode: false,
4785
+ host: "hslocal.net",
4786
+ origin
4787
+ },
4788
+ root: webRoot2,
3331
4789
  ssr: {
3332
- // TODO: might need more entries here to get things to resolve through
3333
- // resolveWebRootDepsPlugin
3334
4790
  noExternal: "@hubspot/cms-components"
3335
4791
  },
3336
4792
  resolve: {
@@ -3341,9 +4797,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
3341
4797
  include: ["react", "react-dom", "react-dom/client"]
3342
4798
  },
3343
4799
  plugins: [
3344
- jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
3345
- sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
3346
- react({
4800
+ react2({
3347
4801
  babel: {
3348
4802
  plugins: [
3349
4803
  "babel-plugin-styled-components",
@@ -3353,10 +4807,7 @@ Custom origin: ${process.env.VITE_ORIGIN}
3353
4807
  }
3354
4808
  }),
3355
4809
  clientIslandEntryPlugin(),
3356
- resolveIslandPlugin(),
3357
- jsRenderingGates.includes("CMS:JSRenderer:RemoveCjsPlugin") ? null : viteCommonjs(),
3358
- devSecretsPlugin(secretNames),
3359
- noncePlaceholderPlugin()
4810
+ resolveIslandPlugin()
3360
4811
  ],
3361
4812
  css: {
3362
4813
  postcss: webRoot2
@@ -3364,9 +4815,9 @@ Custom origin: ${process.env.VITE_ORIGIN}
3364
4815
  envDir: webRoot2,
3365
4816
  envPrefix: "HS_"
3366
4817
  };
3367
- return createViteServer(viteConfig);
4818
+ return createViteServer2(viteConfig);
3368
4819
  }
3369
- var createViteDevServer_default = createViteDevServer;
4820
+ var createAppServer_default = createAppServer;
3370
4821
 
3371
4822
  // src/lib/httpsRedirectingServer.ts
3372
4823
  import net2 from "net";
@@ -3424,12 +4875,10 @@ var mapEnabledFeaturesToGates = (enabledFeatures) => {
3424
4875
  return gates;
3425
4876
  }, []);
3426
4877
  };
3427
- async function getJsRenderingGates(portalId, env, personalAccessKey) {
3428
- const { enabledFeatures = {} } = await fetchAccessToken(
3429
- personalAccessKey,
3430
- env,
3431
- portalId
3432
- );
4878
+ async function getJsRenderingGates(portalId, env2, personalAccessKey) {
4879
+ const {
4880
+ data: { enabledFeatures }
4881
+ } = await fetchAccessToken(personalAccessKey, env2, portalId);
3433
4882
  const envGates = getGatesFromEnv();
3434
4883
  const gates = mapEnabledFeaturesToGates(enabledFeatures);
3435
4884
  const mergedGates = [...envGates, ...gates];
@@ -3439,16 +4888,16 @@ async function getJsRenderingGates(portalId, env, personalAccessKey) {
3439
4888
 
3440
4889
  // src/createDevServer.ts
3441
4890
  import {
3442
- getEnv as getEnv3,
4891
+ getEnv as getEnv4,
3443
4892
  getAccountId as getAccountId4,
3444
- getAccountConfig as getAccountConfig2,
4893
+ getAccountConfig as getAccountConfig3,
3445
4894
  loadConfig,
3446
4895
  validateConfig
3447
4896
  } from "@hubspot/local-dev-lib/config";
3448
4897
  import { fetchSecrets } from "@hubspot/local-dev-lib/api/secrets";
3449
4898
 
3450
4899
  // src/proxyPage/fetchDomains.ts
3451
- import localDevHttpImport7 from "@hubspot/local-dev-lib/http";
4900
+ import { http as hsCliHttp11 } from "@hubspot/local-dev-lib/http";
3452
4901
 
3453
4902
  // src/lib/errors.ts
3454
4903
  var MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.
@@ -3470,7 +4919,7 @@ ${messageEnd}`);
3470
4919
  function logMissingScopeWarning(error) {
3471
4920
  console.warn(error.message);
3472
4921
  }
3473
- function isMissingScopeError(error) {
4922
+ function isMissingScopeError2(error) {
3474
4923
  return error.statusCode === 403 && (error.error.message.match(OAUTH_ERROR_REGEX) || error.error.message.startsWith(NOT_PUBLIC_USE_ERROR));
3475
4924
  }
3476
4925
  function handleSecretsError(error) {
@@ -3504,17 +4953,16 @@ function handleSecretsError(error) {
3504
4953
  }
3505
4954
 
3506
4955
  // src/proxyPage/fetchDomains.ts
3507
- var { default: hsCliHttp7 } = localDevHttpImport7;
3508
4956
  async function fetchDomains(portalId) {
3509
4957
  try {
3510
- const result = await hsCliHttp7.get(portalId, {
4958
+ const result = (await hsCliHttp11.get(portalId, {
3511
4959
  url: `/cms/v3/domains`,
3512
4960
  params: { portalId },
3513
4961
  responseType: "json"
3514
- });
4962
+ })).data;
3515
4963
  return result.results;
3516
4964
  } catch (error) {
3517
- if (isMissingScopeError(error)) {
4965
+ if (isMissingScopeError2(error)) {
3518
4966
  throw new MissingScopeError(error);
3519
4967
  }
3520
4968
  throw error;
@@ -3530,25 +4978,24 @@ async function fetchWebsiteDomainNames(portalId) {
3530
4978
  }
3531
4979
 
3532
4980
  // src/lib/validateHSPlatform.ts
3533
- import path8 from "path";
3534
- import fs3 from "fs";
4981
+ import path12 from "path";
4982
+ import fs4 from "fs";
3535
4983
  import select from "@inquirer/select";
3536
- import localDevHttpImport8 from "@hubspot/local-dev-lib/http";
3537
- var { default: hsCliHttp8 } = localDevHttpImport8;
4984
+ import { http as hsCliHttp12 } from "@hubspot/local-dev-lib/http";
3538
4985
  var HSPROJECT_JSON = "hsproject.json";
3539
4986
  function checkFileExists(filePath) {
3540
- return fs3.existsSync(filePath) && fs3.statSync(filePath).isFile();
4987
+ return fs4.existsSync(filePath) && fs4.statSync(filePath).isFile();
3541
4988
  }
3542
4989
  function findHSProjectJson(startPath) {
3543
4990
  let currentDir = startPath;
3544
4991
  let dirLevel = 0;
3545
4992
  const maxDirLevel = 4;
3546
- while (path8.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
3547
- const filePath = path8.join(currentDir, HSPROJECT_JSON);
4993
+ while (path12.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {
4994
+ const filePath = path12.join(currentDir, HSPROJECT_JSON);
3548
4995
  if (checkFileExists(filePath)) {
3549
4996
  return filePath;
3550
4997
  }
3551
- currentDir = path8.dirname(currentDir);
4998
+ currentDir = path12.dirname(currentDir);
3552
4999
  dirLevel++;
3553
5000
  }
3554
5001
  console.log(
@@ -3563,15 +5010,15 @@ async function validateHSPlatform(projectConfigPath, portalId) {
3563
5010
  );
3564
5011
  return false;
3565
5012
  }
3566
- const hsProjectJSONContents = fs3.readFileSync(projectConfigPath, "utf8");
5013
+ const hsProjectJSONContents = fs4.readFileSync(projectConfigPath, "utf8");
3567
5014
  const hsProjectJSONData = JSON.parse(hsProjectJSONContents);
3568
5015
  const { platformVersion } = hsProjectJSONData;
3569
5016
  let platformVersionResult;
3570
5017
  try {
3571
- platformVersionResult = await hsCliHttp8.get(portalId, {
5018
+ platformVersionResult = (await hsCliHttp12.get(portalId, {
3572
5019
  url: `developer/projects/v1/platformVersion`,
3573
5020
  responseType: "json"
3574
- });
5021
+ })).data;
3575
5022
  } catch (e) {
3576
5023
  console.error(e.message);
3577
5024
  console.log(
@@ -3591,7 +5038,7 @@ async function validateHSPlatform(projectConfigPath, portalId) {
3591
5038
  });
3592
5039
  hsProjectJSONData.platformVersion = answer;
3593
5040
  try {
3594
- fs3.writeFileSync(
5041
+ fs4.writeFileSync(
3595
5042
  projectConfigPath,
3596
5043
  JSON.stringify(hsProjectJSONData, void 0, 2),
3597
5044
  "utf8"
@@ -3608,7 +5055,7 @@ async function validateHSPlatform(projectConfigPath, portalId) {
3608
5055
  }
3609
5056
 
3610
5057
  // src/createDevServer.ts
3611
- import localDevHttpImport9 from "@hubspot/local-dev-lib/http";
5058
+ import { http as hsCliHttp13 } from "@hubspot/local-dev-lib/http";
3612
5059
 
3613
5060
  // ../cms-js-internal/dist/buildFieldsTypes.js
3614
5061
  import { writeFileSync } from "fs";
@@ -3853,8 +5300,8 @@ function writeFieldsType(fields, fileName, typeName) {
3853
5300
  }
3854
5301
 
3855
5302
  // src/lib/watchFieldsUpdates.ts
3856
- import fs4 from "fs";
3857
- import path9 from "path";
5303
+ import fs5 from "fs";
5304
+ import path13 from "path";
3858
5305
  import readline from "readline";
3859
5306
  var lastSerializedFieldsCache = {};
3860
5307
  var formatAsTypeName = (str) => {
@@ -3866,18 +5313,18 @@ var isInModulesFolder = (filePath, projectRoot) => {
3866
5313
  const getEntryPathFromId = (id) => {
3867
5314
  return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, "") : "";
3868
5315
  };
3869
- const currentModuleId = path9.normalize(filePath);
5316
+ const currentModuleId = path13.normalize(filePath);
3870
5317
  const moduleEntryPath = getEntryPathFromId(currentModuleId);
3871
- const subFolderTokens = moduleEntryPath.split(path9.sep);
5318
+ const subFolderTokens = moduleEntryPath.split(path13.sep);
3872
5319
  return {
3873
5320
  inModuleFolder: subFolderTokens[0] === "components" && subFolderTokens[1] === "modules",
3874
5321
  isRootModuleFile: subFolderTokens.length === 3
3875
5322
  };
3876
5323
  };
3877
5324
  var fileContainsAutoGenComment = async (filePath) => {
3878
- if (!fs4.existsSync(filePath))
5325
+ if (!fs5.existsSync(filePath))
3879
5326
  return true;
3880
- const stream2 = fs4.createReadStream(filePath);
5327
+ const stream2 = fs5.createReadStream(filePath);
3881
5328
  const reader = readline.createInterface({ input: stream2 });
3882
5329
  const firstLine = await new Promise(
3883
5330
  (resolve3) => reader.once("line", (line) => resolve3(line.trim()))
@@ -3895,10 +5342,10 @@ var getIndexFile = (filePath, projectRoot) => {
3895
5342
  return void 0;
3896
5343
  if (isRootModuleFile)
3897
5344
  return { indexFilePath: filePath, isRootModuleFile };
3898
- const dir = path9.dirname(filePath);
3899
- const files = fs4.readdirSync(dir);
5345
+ const dir = path13.dirname(filePath);
5346
+ const files = fs5.readdirSync(dir);
3900
5347
  const indexFileName = files.find((file) => file.startsWith("index."));
3901
- return indexFileName ? { indexFilePath: path9.join(dir, indexFileName), isRootModuleFile } : void 0;
5348
+ return indexFileName ? { indexFilePath: path13.join(dir, indexFileName), isRootModuleFile } : void 0;
3902
5349
  };
3903
5350
  var getIndexFileFields = async (indexFilePath, indexFileName, viteServer) => {
3904
5351
  let indexFile;
@@ -3922,7 +5369,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3922
5369
  if (!indexInfo)
3923
5370
  return;
3924
5371
  const { indexFilePath, isRootModuleFile } = indexInfo;
3925
- const indexFileName = path9.parse(indexFilePath).name;
5372
+ const indexFileName = path13.parse(indexFilePath).name;
3926
5373
  const isTypeFile = filePath.endsWith(".types.ts");
3927
5374
  if (isTypeFile)
3928
5375
  return;
@@ -3933,7 +5380,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3933
5380
  );
3934
5381
  if (fields) {
3935
5382
  const typeFileName = isRootModuleFile ? `${indexFileName}.fields.types.ts` : "fields.type.ts";
3936
- const typeFilePath = path9.join(path9.dirname(filePath), typeFileName);
5383
+ const typeFilePath = path13.join(path13.dirname(filePath), typeFileName);
3937
5384
  const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];
3938
5385
  const serializedFields = JSON.stringify(fields);
3939
5386
  if (lastSerializedFields === serializedFields)
@@ -3941,7 +5388,7 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3941
5388
  const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);
3942
5389
  if (!hasAutoGenComment)
3943
5390
  return;
3944
- const moduleFolderName = path9.basename(path9.dirname(filePath));
5391
+ const moduleFolderName = path13.basename(path13.dirname(filePath));
3945
5392
  const outputTypeName = formatAsTypeName(moduleFolderName);
3946
5393
  const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);
3947
5394
  if (didSucceed) {
@@ -3957,26 +5404,37 @@ var maybeUpdateFields = async (filePath, viteServer, projectRoot) => {
3957
5404
  var startFieldsTypeGenWatcher = (viteServer, projectRoot) => {
3958
5405
  const { moduleSubpaths } = findAllModulesInRoot(projectRoot);
3959
5406
  moduleSubpaths.forEach((modulePath) => {
3960
- const resolvedPath = path9.resolve(projectRoot, modulePath);
5407
+ const resolvedPath = path13.resolve(projectRoot, modulePath);
3961
5408
  maybeUpdateFields(resolvedPath, viteServer, projectRoot);
3962
5409
  });
3963
5410
  const watchCallback = (filePath) => maybeUpdateFields(filePath, viteServer, projectRoot);
3964
5411
  viteServer.watcher.on("add", watchCallback).on("change", watchCallback);
3965
5412
  };
3966
5413
 
5414
+ // src/lib/configHelpers.ts
5415
+ function getSecretNamesFromConfig(config) {
5416
+ var _a, _b;
5417
+ if ("secretNames" in config && ((_a = config.secretNames) == null ? void 0 : _a.length) > 0) {
5418
+ return config.secretNames;
5419
+ }
5420
+ if ("secret_names" in config && ((_b = config.secret_names) == null ? void 0 : _b.length) > 0) {
5421
+ return config.secret_names;
5422
+ }
5423
+ return [];
5424
+ }
5425
+
3967
5426
  // src/createDevServer.ts
3968
- var { default: hsCliHttp9 } = localDevHttpImport9;
3969
5427
  var BASE_PATH = "/";
3970
5428
  var PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3e3;
3971
5429
  var SHADOW_PORT = 1442;
3972
5430
  var STORYBOOK_PORT = process.env.STORYBOOK_PORT ? parseInt(process.env.STORYBOOK_PORT, 10) : 3123;
3973
- async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2) {
3974
- var _a;
5431
+ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2, hubspotCliAccountNameOption2, sslEnabledOption2, fieldGenEnabledOption2, themePreviewOptions2, showUI) {
3975
5432
  let authedPortalId = null;
3976
5433
  let authedEnv = null;
3977
5434
  let jsRenderingGates = [];
3978
5435
  let personalAccessKey = null;
3979
5436
  let secretNames = [];
5437
+ let secretNamesFromConfig = [];
3980
5438
  if (hubspotCliConfigPathOption2 && hubspotCliAccountNameOption2) {
3981
5439
  console.log(
3982
5440
  `Loading HS auth (account = ${hubspotCliAccountNameOption2}) configuration at: ${hubspotCliConfigPathOption2}`
@@ -3991,25 +5449,18 @@ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2
3991
5449
  );
3992
5450
  }
3993
5451
  loadConfig(hubspotCliConfigPathOption2 || null, { useEnv: false });
3994
- let cmsAssetConfig;
3995
- try {
3996
- cmsAssetConfig = getCMSAssetConfig(webRoot2);
3997
- } catch (e) {
3998
- console.error(
3999
- `Error finding or parsing cms-assets.json when initializing in ${webRoot2}`
4000
- );
4001
- process.exit(1);
4002
- }
5452
+ const cmsAssetConfig = getCMSAssetConfig(webRoot2);
5453
+ secretNamesFromConfig = getSecretNamesFromConfig(cmsAssetConfig);
4003
5454
  if (validateConfig()) {
4004
5455
  authedPortalId = getAccountId4(hubspotCliAccountNameOption2);
4005
- const env = getEnv3(hubspotCliAccountNameOption2);
4006
- if (!env) {
5456
+ const env2 = getEnv4(hubspotCliAccountNameOption2);
5457
+ if (!env2) {
4007
5458
  throw new Error(
4008
5459
  `No environment found for account ${hubspotCliAccountNameOption2} from hubspot.config.yaml`
4009
5460
  );
4010
5461
  }
4011
- authedEnv = env;
4012
- personalAccessKey = getAccountConfig2(authedPortalId) && getAccountConfig2(authedPortalId).personalAccessKey;
5462
+ authedEnv = env2;
5463
+ personalAccessKey = getAccountConfig3(authedPortalId) && getAccountConfig3(authedPortalId).personalAccessKey;
4013
5464
  if (!authedPortalId && hubspotCliAccountNameOption2) {
4014
5465
  console.error(
4015
5466
  `Couldn't find ${hubspotCliAccountNameOption2} in your hubspot.config.yaml`
@@ -4029,36 +5480,37 @@ async function createDevServer(webRoot2, storybook2, hubspotCliConfigPathOption2
4029
5480
  );
4030
5481
  }
4031
5482
  }
4032
- try {
4033
- const secretsResponse = await fetchSecrets(authedPortalId);
4034
- if (cmsAssetConfig.secretNames && secretsResponse) {
4035
- secretNames = secretsResponse.results.filter(
4036
- (secretName) => cmsAssetConfig.secretNames.includes(secretName)
4037
- );
4038
- if (secretNames.length < cmsAssetConfig.secretNames.length) {
4039
- const missingSecrets = cmsAssetConfig.secretNames.filter(
4040
- (secretName) => secretsResponse.results.includes(secretName) === false
4041
- );
4042
- console.error(
4043
- `Secrets ${missingSecrets.join(
4044
- ", "
4045
- )} could not be found as initialized for this account, be sure to use \`hs secrets add\``
5483
+ if (cmsAssetConfig) {
5484
+ try {
5485
+ const secretsResponse = (await fetchSecrets(authedPortalId)).data;
5486
+ if (secretNamesFromConfig && secretsResponse) {
5487
+ secretNames = secretsResponse.results.filter(
5488
+ (secretName) => secretNamesFromConfig.includes(secretName)
4046
5489
  );
5490
+ if (secretNames.length < secretNamesFromConfig.length) {
5491
+ const missingSecrets = secretNamesFromConfig.filter(
5492
+ (secretName) => secretsResponse.results.includes(secretName) === false
5493
+ );
5494
+ console.error(
5495
+ `Secrets ${missingSecrets.join(
5496
+ ", "
5497
+ )} could not be found as initialized for this account, be sure to use \`hs secrets add\``
5498
+ );
5499
+ }
4047
5500
  }
5501
+ } catch (e) {
5502
+ handleSecretsError(e);
5503
+ console.log(e);
4048
5504
  }
4049
- } catch (error) {
4050
- handleSecretsError(error);
4051
5505
  }
4052
5506
  } else {
4053
5507
  console.warn(
4054
5508
  `Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).
4055
5509
  If needed you can refer to another config file with --config.
4056
5510
 
4057
- Local proxy functionality and module preview routes will not work without setting up authentication. You can work purely on modules locally at "/module/[module_name]", however the experience may be degraded do to missing account data.`
5511
+ Local proxy functionality and module preview routes will not work without setting up authentication. You can work purely on modules locally at "/module/[module_name]", however the experience may be degraded due to missing account data.`
4058
5512
  );
4059
- if (((_a = cmsAssetConfig.secretNames) == null ? void 0 : _a.length) > 0) {
4060
- secretNames = cmsAssetConfig.secretNames;
4061
- }
5513
+ secretNames = secretNamesFromConfig;
4062
5514
  }
4063
5515
  setTrackingInfo(authedPortalId, authedEnv);
4064
5516
  sendTrackingRequest("start-dev-server");
@@ -4083,19 +5535,33 @@ Local proxy functionality and module preview routes will not work without settin
4083
5535
  }
4084
5536
  let authedHublet;
4085
5537
  try {
4086
- const accountInformation = await hsCliHttp9.get(authedPortalId, {
5538
+ const accountInformation = (await hsCliHttp13.get(authedPortalId, {
4087
5539
  url: "/account-info/v3/details"
4088
- });
5540
+ })).data;
4089
5541
  authedHublet = accountInformation.dataHostingLocation;
4090
5542
  } catch (e) {
4091
5543
  authedHublet = "na1";
4092
5544
  }
4093
- const absoluteWebRoot = normalizePath7(path10.resolve(process.cwd(), webRoot2));
5545
+ const absoluteWebRoot = normalizePath7(path14.resolve(process.cwd(), webRoot2));
4094
5546
  const [__webRootProjectFolder, webRootProjectComponentFolder] = absoluteWebRoot.replace(/\/$/, "").split("/").slice(-2);
4095
5547
  const projectConfigPath = findHSProjectJson(absoluteWebRoot);
4096
5548
  if (authedPortalId) {
4097
5549
  await validateHSPlatform(projectConfigPath, authedPortalId);
4098
5550
  }
5551
+ const isUngatedForUnifiedThemePreview = jsRenderingGates.includes(
5552
+ "CMS:React:UnifiedThemePreview"
5553
+ );
5554
+ let _localPreviewToken = null;
5555
+ let _tokenStatus;
5556
+ if (themePreviewOptions2 && isUngatedForUnifiedThemePreview) {
5557
+ const { localPreviewToken, tokenStatus } = await initiatePreviewSession(
5558
+ authedPortalId,
5559
+ absoluteWebRoot,
5560
+ themePreviewOptions2
5561
+ );
5562
+ _localPreviewToken = localPreviewToken;
5563
+ _tokenStatus = tokenStatus;
5564
+ }
4099
5565
  const viteServer = await createViteDevServer_default(
4100
5566
  absoluteWebRoot,
4101
5567
  PORT,
@@ -4110,7 +5576,7 @@ Local proxy functionality and module preview routes will not work without settin
4110
5576
  const viteHTTPSConfig = viteServer.config.server.https;
4111
5577
  const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;
4112
5578
  const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;
4113
- const projectName = getProjectNameFromHSConfig(projectConfigPath);
5579
+ const projectName = projectConfigPath ? getProjectNameFromHSConfig(projectConfigPath) : "";
4114
5580
  const httpServers = [];
4115
5581
  const expressServer = express2();
4116
5582
  expressServer.locals.devServerHost = "hslocal.net";
@@ -4126,6 +5592,7 @@ Local proxy functionality and module preview routes will not work without settin
4126
5592
  expressServer.locals.projectComponentPath = webRootProjectComponentFolder;
4127
5593
  expressServer.locals.jsRenderingGates = jsRenderingGates;
4128
5594
  expressServer.locals.domainsToProxy = domainsToProxy;
5595
+ expressServer.locals.localPreviewToken = _localPreviewToken;
4129
5596
  expressServer.use(bodyParser.json());
4130
5597
  expressServer.use(
4131
5598
  BASE_PATH,
@@ -4166,9 +5633,18 @@ Local proxy functionality and module preview routes will not work without settin
4166
5633
  HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})
4167
5634
  `
4168
5635
  );
5636
+ if (showUI) {
5637
+ const appWebRoot = path14.join(
5638
+ path14.dirname(url3.fileURLToPath(import.meta.url)),
5639
+ "../app"
5640
+ );
5641
+ const appServer = await createAppServer_default(appWebRoot, PORT + 1);
5642
+ await appServer.listen(PORT + 1);
5643
+ httpServers.push(appServer);
5644
+ }
4169
5645
  if (storybook2) {
4170
- const packageRoot = path10.dirname(url2.fileURLToPath(import.meta.url));
4171
- const configPath = path10.resolve(packageRoot, "./storybook-main");
5646
+ const packageRoot = path14.dirname(url3.fileURLToPath(import.meta.url));
5647
+ const configPath = path14.resolve(packageRoot, "./storybook-main");
4172
5648
  sendTrackingRequest("start-storybook");
4173
5649
  const storybookProcess = spawn(
4174
5650
  "sb",
@@ -4188,7 +5664,7 @@ HubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectCom
4188
5664
  portalId: authedPortalId.toString(),
4189
5665
  hsEnv: authedEnv,
4190
5666
  hublet: authedHublet,
4191
- WEB_ROOT: path10.join(webRoot2, "components")
5667
+ WEB_ROOT: path14.join(webRoot2, "components")
4192
5668
  }
4193
5669
  }
4194
5670
  );
@@ -4235,16 +5711,26 @@ var {
4235
5711
  hubspotCliAccountNameOption,
4236
5712
  sslEnabledOption,
4237
5713
  storybook,
4238
- fieldGenEnabledOption
5714
+ fieldGenEnabledOption,
5715
+ resetSession
4239
5716
  } = getDevServerCommandLineOptions(process.argv);
4240
5717
  if (!webRoot) {
4241
5718
  throw new Error(`No web root path argument specified`);
4242
5719
  }
5720
+ var themePreviewOptions;
5721
+ var builtThemePreviewOptions = await buildThemePreviewOptions(webRoot);
5722
+ if (builtThemePreviewOptions) {
5723
+ themePreviewOptions = {
5724
+ ...builtThemePreviewOptions,
5725
+ resetSession
5726
+ };
5727
+ }
4243
5728
  createDevServer_default(
4244
5729
  webRoot,
4245
5730
  storybook,
4246
5731
  hubspotCliConfigPathOption,
4247
5732
  hubspotCliAccountNameOption,
4248
5733
  sslEnabledOption,
4249
- fieldGenEnabledOption
5734
+ fieldGenEnabledOption,
5735
+ themePreviewOptions
4250
5736
  );