@hubspot/cms-dev-server 1.1.0-prerelease.9 → 1.2.1

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 (139) hide show
  1. package/dist/.DS_Store +0 -0
  2. package/dist/app/assets/LexendDeca-Bold-B8uERmr8.woff2 +0 -0
  3. package/dist/app/assets/LexendDeca-Light-BtcvwT5C.woff2 +0 -0
  4. package/dist/app/assets/LexendDeca-Medium-CxVPR2j6.woff2 +0 -0
  5. package/dist/app/assets/LexendDeca-SemiBold-BhzS3XUP.woff2 +0 -0
  6. package/dist/app/assets/index-PcyCbkys.css +1 -0
  7. package/dist/app/assets/index-tvg7JxpD.js +164 -0
  8. package/dist/app/index.html +15 -0
  9. package/dist/app/server/assets/RenderTreeSeparately-T6CL43QJ-D50VfKo0.js +111 -0
  10. package/dist/app/server/serverEntry.js +3641 -0
  11. package/dist/generateJsonFromJsx.js +744 -0
  12. package/dist/html/baseTemplate.html +1 -0
  13. package/dist/index.js +5807 -0
  14. package/dist/internalSsr.js +1313 -0
  15. package/dist/island-runtime.js +267 -0
  16. package/dist/run.js +6502 -4
  17. package/dist/storybook/index.js +241 -0
  18. package/dist/storybook-main/main.js +1458 -0
  19. package/dist/storybook-main/preview.js +21 -0
  20. package/package.json +93 -24
  21. package/types/api/designmanager.d.ts +44 -0
  22. package/types/api/project.d.ts +5 -0
  23. package/types/api/session.d.ts +2 -0
  24. package/types/components/HubLModulesList.d.ts +4 -0
  25. package/types/components/HubLTemplatesList.d.ts +5 -0
  26. package/types/components/ModulesList.d.ts +5 -0
  27. package/types/components/PartialsList.d.ts +4 -0
  28. package/types/constants/errors.d.ts +5 -0
  29. package/types/createAppServer.d.ts +3 -0
  30. package/types/createAppViteConfig.d.ts +2 -0
  31. package/types/createDevServer.d.ts +5 -0
  32. package/types/createViteDevServer.d.ts +6 -0
  33. package/types/fileManager.d.ts +4 -0
  34. package/types/index.d.ts +2 -0
  35. package/types/lib/cli.d.ts +22 -0
  36. package/types/lib/cliUtils.d.ts +15 -0
  37. package/types/lib/configHelpers.d.ts +2 -0
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/criticalDevErrorsToServerMessages.d.ts +4 -0
  40. package/types/lib/debug.d.ts +1 -0
  41. package/types/lib/errors.d.ts +6 -0
  42. package/types/lib/fetchModuleGraphQLData.d.ts +24 -0
  43. package/types/lib/fullOriginalUrlFromRequest.d.ts +2 -0
  44. package/types/lib/gates.d.ts +2 -0
  45. package/types/lib/getDevServerUIData.d.ts +60 -0
  46. package/types/lib/getFieldValuesForModule.d.ts +2 -0
  47. package/types/lib/getJSRenderingGates.d.ts +8 -0
  48. package/types/lib/httpsRedirectingServer.d.ts +11 -0
  49. package/types/lib/logColors.d.ts +6 -0
  50. package/types/lib/moduleGraph.d.ts +1 -0
  51. package/types/lib/packagePath.d.ts +1 -0
  52. package/types/lib/pathHelpers.d.ts +3 -0
  53. package/types/lib/previewUtils.d.ts +22 -0
  54. package/types/lib/proxyHelpers.d.ts +29 -0
  55. package/types/lib/renderComponentWithCSS.d.ts +14 -0
  56. package/types/lib/renderHelpers.d.ts +1 -0
  57. package/types/lib/renderModule.d.ts +11 -0
  58. package/types/lib/renderModuleFieldsJson.d.ts +4 -0
  59. package/types/lib/renderModulePreview.d.ts +6 -0
  60. package/types/lib/renderPartial.d.ts +5 -0
  61. package/types/lib/templates.d.ts +4 -0
  62. package/types/lib/trackUsage.d.ts +3 -0
  63. package/types/lib/validateHSPlatform.d.ts +3 -0
  64. package/types/lib/watchFieldsUpdates.d.ts +22 -0
  65. package/types/plugins/cmsComponentsShimPlugin.d.ts +11 -0
  66. package/types/plugins/devSecretsPlugin.d.ts +2 -0
  67. package/types/plugins/hsStaticAssetPlugin.d.ts +2 -0
  68. package/types/proxyPage/constants.d.ts +1 -0
  69. package/types/proxyPage/fetchContentMetadata.d.ts +7 -0
  70. package/types/proxyPage/fetchDomains.d.ts +9 -0
  71. package/types/proxyPage/fetchPreviewInfo.d.ts +7 -0
  72. package/types/proxyPage/proxyPage.d.ts +11 -0
  73. package/types/proxyPage/renderLocalError.d.ts +2 -0
  74. package/types/proxyPage/utils.d.ts +4 -0
  75. package/types/routes/api.d.ts +2 -0
  76. package/types/routes/appServerApiRouteHandler.d.ts +5 -0
  77. package/types/routes/appServerRouteHandler.d.ts +3 -0
  78. package/types/routes/appServerRoutes.d.ts +5 -0
  79. package/types/routes/createAppServerAPIRoutes.d.ts +5 -0
  80. package/types/routes/createAppServerRoutes.d.ts +5 -0
  81. package/types/routes/createDevServerRoutes.d.ts +4 -0
  82. package/types/routes/homeRouteHandler.d.ts +3 -0
  83. package/types/routes/hublModuleRouteHandler.d.ts +2 -0
  84. package/types/routes/hublTemplateRouteHandler.d.ts +2 -0
  85. package/types/routes/legacyRouteHandler.d.ts +3 -0
  86. package/types/routes/linksToAllModulesRouteHandler.d.ts +2 -0
  87. package/types/routes/linksToAllPartialsRouteHandler.d.ts +2 -0
  88. package/types/routes/module.d.ts +3 -0
  89. package/types/routes/moduleFieldsJson.d.ts +3 -0
  90. package/types/routes/modulePreviewRouteHandler.d.ts +3 -0
  91. package/types/routes/partial.d.ts +2 -0
  92. package/types/routes/proxyPageResourceRedirect.d.ts +2 -0
  93. package/types/routes/proxyPageRouteHandler.d.ts +2 -0
  94. package/types/routes/proxyPathPageResourceRedirect.d.ts +2 -0
  95. package/types/routes/proxyPathPageRouteHandler.d.ts +2 -0
  96. package/types/routes/proxyServerlessHandler.d.ts +2 -0
  97. package/types/routes/remoteFsDirtyHandler.d.ts +2 -0
  98. package/types/shadowDevServer/createShadowDevServerRoutes.d.ts +1 -0
  99. package/types/shadowDevServer/startShadowDevServer.d.ts +1 -0
  100. package/types/storybook/getFieldsArgTypes.d.ts +3 -0
  101. package/types/storybook/getNestedFieldObjectForArgs.d.ts +6 -0
  102. package/types/storybook/index.d.ts +1 -0
  103. package/types/storybook/moduleStory.d.ts +5 -0
  104. package/types/storybook/types.d.ts +15 -0
  105. package/types/storybook-main/preview.d.ts +9 -0
  106. package/dist/components/ModulesList.js +0 -14
  107. package/dist/components/PartialsList.js +0 -13
  108. package/dist/createDevServer.js +0 -26
  109. package/dist/createViteDevServer.js +0 -26
  110. package/dist/lib/createIslandsGlobalJsForClientInDev.js +0 -32
  111. package/dist/lib/fullOriginalUrlFromRequest.js +0 -3
  112. package/dist/lib/htmlHelpers.js +0 -10
  113. package/dist/lib/moduleGraph.js +0 -11
  114. package/dist/lib/proxyHelpers.js +0 -69
  115. package/dist/lib/proxyHelpers.test.js +0 -136
  116. package/dist/lib/renderComponentWithCSS.js +0 -26
  117. package/dist/lib/renderHelpers.js +0 -45
  118. package/dist/lib/renderModule.js +0 -88
  119. package/dist/lib/renderPartial.js +0 -12
  120. package/dist/lib/templates.js +0 -48
  121. package/dist/lib/traverseFieldsJson.js +0 -78
  122. package/dist/proxyPage/constants.js +0 -4
  123. package/dist/proxyPage/fetchContentMetadata.js +0 -51
  124. package/dist/proxyPage/fetchPreviewInfo.js +0 -37
  125. package/dist/proxyPage/proxyPage.js +0 -167
  126. package/dist/proxyPage/renderLocalError.js +0 -27
  127. package/dist/proxyPage/utils.js +0 -38
  128. package/dist/render/renderOnServer.js +0 -40
  129. package/dist/render/renderOnServer.test.js +0 -24
  130. package/dist/render/renderStreamToPromise.js +0 -35
  131. package/dist/resolveSharedDeps.js +0 -28
  132. package/dist/routes/createDevServerRoutes.js +0 -21
  133. package/dist/routes/homeRouteHandler.js +0 -12
  134. package/dist/routes/linksToAllModulesRouteHandler.js +0 -10
  135. package/dist/routes/linksToAllPartialsRouteHandler.js +0 -10
  136. package/dist/routes/module.js +0 -27
  137. package/dist/routes/partial.js +0 -27
  138. package/dist/routes/proxyPageResourceRedirect.js +0 -12
  139. package/dist/routes/proxyPageRouteHandler.js +0 -40
@@ -0,0 +1,1458 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // ../cms-js-internal/dist/types-Bqf9htWu.js
12
+ import path from "path";
13
+ import { createHash } from "crypto";
14
+ import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
15
+ import { join } from "path/posix";
16
+ function createPreloadLink(assetPath, basePath = "") {
17
+ if (assetPath && assetPath[0] !== "/") {
18
+ assetPath = `/${assetPath}`;
19
+ }
20
+ if (assetPath.endsWith(".js")) {
21
+ return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
22
+ } else if (CSS_LANGS_RE.test(assetPath)) {
23
+ return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
24
+ } else if (assetPath.endsWith(".woff")) {
25
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
26
+ } else if (assetPath.endsWith(".woff2")) {
27
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
28
+ } else if (assetPath.endsWith(".gif")) {
29
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
30
+ } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
31
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
32
+ } else if (assetPath.endsWith(".png")) {
33
+ return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
34
+ } else {
35
+ throw new Error(`Unknown preload type for ${assetPath}`);
36
+ }
37
+ }
38
+ function sortKeys(input, options = {}) {
39
+ const { deep, compare } = options;
40
+ const cache = /* @__PURE__ */ new WeakMap();
41
+ function deepSortArray(array) {
42
+ const resultFromCache = cache.get(array);
43
+ if (resultFromCache !== void 0) {
44
+ return resultFromCache;
45
+ }
46
+ const result = [];
47
+ cache.set(array, result);
48
+ result.push(
49
+ ...array.map((item) => {
50
+ if (Array.isArray(item)) {
51
+ return deepSortArray(item);
52
+ }
53
+ if (isPlainObject(item)) {
54
+ return _sortKeys(item);
55
+ }
56
+ return item;
57
+ })
58
+ );
59
+ return result;
60
+ }
61
+ function _sortKeys(object) {
62
+ const resultFromCache = cache.get(object);
63
+ if (resultFromCache !== void 0) {
64
+ return resultFromCache;
65
+ }
66
+ const result = {};
67
+ const keys = Object.keys(object).sort(compare);
68
+ cache.set(object, result);
69
+ for (const key of keys) {
70
+ const value = object[key];
71
+ let newValue;
72
+ if (deep && Array.isArray(value)) {
73
+ newValue = deepSortArray(value);
74
+ } else {
75
+ newValue = deep && isPlainObject(value) ? _sortKeys(value) : value;
76
+ }
77
+ Object.defineProperty(result, key, {
78
+ ...Object.getOwnPropertyDescriptor(object, key),
79
+ value: newValue
80
+ });
81
+ }
82
+ return result;
83
+ }
84
+ if (Array.isArray(input)) {
85
+ return deep ? deepSortArray(input) : [...input];
86
+ }
87
+ return _sortKeys(input);
88
+ }
89
+ function isPlainObject(value) {
90
+ if (typeof value !== "object" || value === null) {
91
+ return false;
92
+ }
93
+ const prototype = Object.getPrototypeOf(value);
94
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
95
+ }
96
+ function escapeChar(unsafeChar) {
97
+ return inlineJsEscapeChars[unsafeChar];
98
+ }
99
+ function escapeForInlineJS(input) {
100
+ return input.replace(badInlineJsChars, escapeChar);
101
+ }
102
+ function jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent = 2, prettyPrint = true } = {}) {
103
+ const indentString = " ".repeat(baseIndent);
104
+ jsonIndent = prettyPrint ? jsonIndent : void 0;
105
+ let sorted;
106
+ try {
107
+ if (isPlainObject(input) || Array.isArray(input)) {
108
+ sorted = sortKeys(input, { deep: true });
109
+ }
110
+ } catch (e) {
111
+ console.error("Error sorting Island keys", e);
112
+ }
113
+ return escapeForInlineJS(
114
+ JSON.stringify(sorted ?? input, null, jsonIndent)
115
+ ).replace(/\n/gm, `
116
+ ${indentString}`);
117
+ }
118
+ function resolveIslandPlugin(islandsSet) {
119
+ return {
120
+ enforce: "pre",
121
+ name: "resolve-islands",
122
+ configResolved(config) {
123
+ viteRoot = config.root;
124
+ viteCommand = config.command;
125
+ },
126
+ load(id) {
127
+ if (id.endsWith("?island") || id.endsWith("?client")) {
128
+ const [idWithNoParam] = id.split("?");
129
+ const islandModuleImportPath = `${idWithNoParam}?client-entry`;
130
+ const componentExtension = path.extname(idWithNoParam);
131
+ const componentFilenameWithNoExtension = path.basename(
132
+ idWithNoParam,
133
+ componentExtension
134
+ );
135
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
136
+ const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
137
+ if (islandsSet) {
138
+ islandsSet.add(moduleId);
139
+ }
140
+ return `
141
+ const moduleId = '${moduleId}';
142
+
143
+ const lazyComponent = () => import('${islandModuleImportPath}');
144
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
145
+ lazyComponent.moduleId = moduleId;
146
+
147
+ export default lazyComponent;
148
+ `;
149
+ }
150
+ return null;
151
+ }
152
+ };
153
+ }
154
+ function resolveIslandToPlainModulePlugin(enabled = true) {
155
+ return {
156
+ enforce: "pre",
157
+ name: "resolve-islands-to-plain",
158
+ configResolved(config) {
159
+ viteRoot = config.root;
160
+ viteCommand = config.command;
161
+ },
162
+ async resolveId(id, importer, options) {
163
+ if (enabled && (id.endsWith("?island") || id.endsWith("?client"))) {
164
+ const newId = id.replace("?island", "").replace("?client", "");
165
+ const resolution = await this.resolve(newId, importer, {
166
+ skipSelf: true,
167
+ ...options
168
+ });
169
+ if (resolution) {
170
+ return resolution;
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+ };
176
+ }
177
+ function resolveIslandToPlainModuleNoopPlugin() {
178
+ return resolveIslandToPlainModulePlugin(false);
179
+ }
180
+ function clientIslandEntryPlugin() {
181
+ return {
182
+ enforce: "pre",
183
+ name: "client-island-entry-plugin",
184
+ resolveId(id) {
185
+ if (id === virtualClientRenderIslandModuleId) {
186
+ return virtualClientRenderIslandModuleId;
187
+ }
188
+ return null;
189
+ },
190
+ load(id) {
191
+ if (id.endsWith("?client-entry")) {
192
+ const [idWithNoParam] = id.split("?");
193
+ return `
194
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
195
+ import Component from '${idWithNoParam}';
196
+
197
+ export function render(island) {
198
+ return clientRenderIsland(island, Component)
199
+ }
200
+
201
+ export default Component;
202
+ `;
203
+ }
204
+ if (id === virtualClientRenderIslandModuleId) {
205
+ return clientRenderIsland;
206
+ }
207
+ return null;
208
+ }
209
+ };
210
+ }
211
+ function getEntryPointHash(entryPoint) {
212
+ return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
213
+ }
214
+ function getEntryPointHashWithIndexSuffix(entryPoint, index) {
215
+ const renderIndexSuffix = index != null ? `i${index}` : "";
216
+ return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
217
+ }
218
+ function getCombinedReactUrl() {
219
+ const hsEnv = process.env.HS_ENV;
220
+ const fileVersion = hsEnv === "prod" ? `react-combined.mjs` : "react-combined-qa.mjs";
221
+ return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;
222
+ }
223
+ function getIslandRuntimeConfigUrl() {
224
+ const hsEnv = process.env.HS_ENV;
225
+ const fileVersion = hsEnv === "prod" ? `island-runtime.mjs` : "island-runtime-qa.mjs";
226
+ return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;
227
+ }
228
+ function includesHublDataReference(templateSource) {
229
+ const hublDataPattern = /\{%\s+set\s+(experimentalHublData|hublData)\s*=/;
230
+ return !!templateSource.match(hublDataPattern);
231
+ }
232
+ function getCMSAssetConfig(webRoot2) {
233
+ const cmsAssetsPath = path.join(webRoot2, "cms-assets.json");
234
+ const cmsThemePath = path.join(webRoot2, "theme.json");
235
+ const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;
236
+ const parsedConfig = JSON.parse(
237
+ fs.readFileSync(configPathToUse).toString()
238
+ );
239
+ return parsedConfig;
240
+ }
241
+ function getCMSAssetConfigIfExists(webRoot2) {
242
+ try {
243
+ return getCMSAssetConfig(webRoot2);
244
+ } catch (e) {
245
+ console.error(
246
+ `Error finding or parsing cms-assets.json in ${webRoot2}, but ignoring for now`
247
+ );
248
+ return {};
249
+ }
250
+ }
251
+ function areBuildHealthChecksEnabled(config) {
252
+ var _a, _b;
253
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;
254
+ }
255
+ function doHealthChecksFailTheBuild(config) {
256
+ var _a, _b;
257
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;
258
+ }
259
+ function getServerIncludePrebundleDepPatterns(config) {
260
+ var _a, _b;
261
+ return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];
262
+ }
263
+ function getBuildInfo(buildDir) {
264
+ try {
265
+ const buildInfo = JSON.parse(
266
+ readFileSync(path.join(buildDir, BUILD_INFO_PATH)).toString()
267
+ );
268
+ return buildInfo;
269
+ } catch (e) {
270
+ throw new Error(`Error loading build-info.json, path: ${BUILD_INFO_PATH}`);
271
+ }
272
+ }
273
+ function getBaseAssetUrlFromBuild(buildDir) {
274
+ return getBuildInfo(buildDir).baseAssetUrl;
275
+ }
276
+ function isUngatedFor(gates, gate) {
277
+ return gates.includes(gate);
278
+ }
279
+ function ungatedAtBuildTimeFor(buildDir, gate) {
280
+ try {
281
+ const buildInfo = getBuildInfo(buildDir);
282
+ return isUngatedFor(buildInfo.gates, gate);
283
+ } catch (e) {
284
+ return false;
285
+ }
286
+ }
287
+ function findAllModulesInRoot(webRoot2) {
288
+ const allModuleComponents = findAllComponentsIn(
289
+ webRoot2,
290
+ "./components/modules"
291
+ );
292
+ const moduleNames = Object.keys(allModuleComponents).map(
293
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
294
+ );
295
+ const moduleSubpaths = Object.keys(allModuleComponents);
296
+ const moduleExtensions = Object.values(allModuleComponents).map((path22) => {
297
+ if (!path22)
298
+ return "";
299
+ const extension = path22.split(".").pop() || "";
300
+ return extension;
301
+ });
302
+ const moduleNamesWithExtension = Object.values(allModuleComponents).map(
303
+ (path22) => {
304
+ if (!path22)
305
+ return "";
306
+ const file = path22.replace("components/modules/", "");
307
+ return file.includes("/index.") ? file.split("/index.")[0] : file;
308
+ }
309
+ );
310
+ return {
311
+ moduleNames,
312
+ moduleSubpaths,
313
+ moduleNamesWithExtension,
314
+ moduleExtensions
315
+ };
316
+ }
317
+ function findAllPartialsInRoot(webRoot2) {
318
+ const allPartialComponents = findAllComponentsIn(
319
+ webRoot2,
320
+ "./components/partials"
321
+ );
322
+ const partialNames = Object.keys(allPartialComponents).map(
323
+ (partialSubpath) => partialSubpath.replace("components/partials/", "").replace("/index", "")
324
+ );
325
+ const partialSubpaths = Object.keys(allPartialComponents);
326
+ return { partialNames, partialSubpaths };
327
+ }
328
+ function namespaceModulePropsShape(props) {
329
+ const {
330
+ dataQueryResult,
331
+ hublParameters,
332
+ fieldValues: passedFieldValues,
333
+ hublData,
334
+ experimentalHublData,
335
+ moduleName,
336
+ supplementalFieldValues
337
+ } = props;
338
+ const oldPropsShape = { ...props };
339
+ if (oldPropsShape.dataQueryResult) {
340
+ delete oldPropsShape.dataQueryResult;
341
+ }
342
+ if (oldPropsShape.hublParameters) {
343
+ delete oldPropsShape.hublParameters;
344
+ }
345
+ const fieldValues = passedFieldValues || oldPropsShape;
346
+ return {
347
+ ...fieldValues,
348
+ dataQueryResult,
349
+ fieldValues,
350
+ hublParameters,
351
+ hublData,
352
+ experimentalHublData,
353
+ moduleName,
354
+ supplementalFieldValues
355
+ };
356
+ }
357
+ function setIn(object, nestedKeysArray, value) {
358
+ let curr = object;
359
+ const finalKey = nestedKeysArray.pop();
360
+ for (let index = 0; index < nestedKeysArray.length; index++) {
361
+ const currentKey = nestedKeysArray[index];
362
+ const nextKey = nestedKeysArray[index + 1];
363
+ if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
364
+ if (curr[currentKey] === void 0) {
365
+ curr[currentKey] = [];
366
+ }
367
+ }
368
+ if (curr[currentKey] === void 0) {
369
+ curr[currentKey] = {};
370
+ }
371
+ curr = curr[currentKey];
372
+ }
373
+ if (value !== void 0) {
374
+ curr[finalKey] = value;
375
+ }
376
+ }
377
+ function isStylesheetAsset(staticAsset) {
378
+ return staticAsset.type === "stylesheet";
379
+ }
380
+ var COMPONENT_EXTENSIONS, ENTRY_POINTS_PATH, MODULE_FOLDER_PATH, TEMPLATE_FOLDER_PATH, VIRTUAL_ISLAND_RUNTIME, VIRTUAL_CONFIG_SETUP, CSS_LANGS_RE, collectCssModules, collectCssInDev, badInlineJsChars, inlineJsEscapeChars, viteRoot, viteCommand, clientRenderIsland, virtualClientRenderIslandModuleId, scriptTagToLogServerMessages, getComponentExtension, hasComponentExtension, isStorybookStory, removeComponentExtension, COMBINED_REACT_BASE_PATH, ISLAND_RUNTIME_CONFIG_BASE_PATH, removeIndexFromPath, removeIndexOrTrailingJsFromPath, HEALTHCHECKS_ENABLED_DEFAULT, HEALTHCHECKS_STRICT_DEFAULT, BUILD_INFO_PATH, GATES, ENABLED_FEATURES_GATE_MAP, findAllComponentsIn;
381
+ var init_types_Bqf9htWu = __esm({
382
+ "../cms-js-internal/dist/types-Bqf9htWu.js"() {
383
+ COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
384
+ ENTRY_POINTS_PATH = "components/partials/";
385
+ MODULE_FOLDER_PATH = "components/modules/";
386
+ TEMPLATE_FOLDER_PATH = "components/templates/";
387
+ VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
388
+ VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
389
+ CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
390
+ collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
391
+ const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
392
+ modulePathToStartWith
393
+ );
394
+ if (!appModulesForPath || appModulesForPath.size === 0) {
395
+ throw new Error(`No modules at: ${modulePathToStartWith}`);
396
+ } else if (appModulesForPath.size > 1) {
397
+ throw new Error(`More than one module at: ${modulePathToStartWith}`);
398
+ }
399
+ const appModule = Array.from(appModulesForPath.values())[0];
400
+ const allServerSideModulesImported = /* @__PURE__ */ new Set();
401
+ const newCssModules = [];
402
+ const moduleQueue = Array.from(appModule.importedModules);
403
+ for (const importedModule of moduleQueue) {
404
+ if (allServerSideModulesImported.has(importedModule.id)) {
405
+ continue;
406
+ }
407
+ allServerSideModulesImported.add(importedModule.id);
408
+ const isCss = CSS_LANGS_RE.test(importedModule.file);
409
+ const moduleModulesToQueue = Array.from(importedModule.importedModules);
410
+ if (isCss && !cssModulesImported.has(importedModule)) {
411
+ cssModulesImported.add(importedModule);
412
+ newCssModules.push(importedModule);
413
+ }
414
+ moduleQueue.push(...moduleModulesToQueue);
415
+ }
416
+ return newCssModules;
417
+ };
418
+ collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
419
+ return `${collectCssModules(
420
+ modulePathToStartWith,
421
+ viteServer,
422
+ cssModulesImported
423
+ ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
424
+ `;
425
+ };
426
+ badInlineJsChars = /[\u2028\u2029<>/]/g;
427
+ inlineJsEscapeChars = {
428
+ "\u2028": "\\u2028",
429
+ "\u2029": "\\u2029",
430
+ "<": "\\u003C",
431
+ ">": "\\u003E",
432
+ "/": "\\u002F"
433
+ };
434
+ clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport * as cmsComponents from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nconst buildIslandIdentifierPrefix =\n cmsComponents.buildIslandIdentifierPrefix || ((id) => id);\n\nexport function clientRenderIsland(\n renderableIsland: RenderableIsland,\n Component: React.ComponentType<any>\n) {\n const {\n island,\n rootElement,\n postHydration,\n pageUrl,\n islands,\n basePath,\n WrapperModule,\n } = renderableIsland;\n let reactRoot: any;\n\n const rootOptions = {\n // Ensure useId is unique across island roots\n identifierPrefix: buildIslandIdentifierPrefix(renderableIsland.island.id),\n };\n\n let innerComponent = <Component islandId={island.id} {...island.props} />;\n if (WrapperModule) {\n innerComponent = <WrapperModule>{innerComponent}</WrapperModule>;\n }\n\n const elementsToHydrate = (\n <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n <ClientRenderContextProvider\n pageUrl={pageUrl}\n islands={islands}\n onTopLevelHydrationFinish={postHydration}\n island={island}\n basePath={basePath}\n >\n {innerComponent}\n </ClientRenderContextProvider>\n </Suspense>\n );\n\n if (island.clientOnly) {\n reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n reactRoot.render(elementsToHydrate);\n } else {\n reactRoot = ReactDOMClient.hydrateRoot(\n rootElement,\n elementsToHydrate,\n rootOptions\n );\n }\n return reactRoot;\n}\n";
435
+ virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
436
+ scriptTagToLogServerMessages = (messagesForBrowser, groupLabel, nonceAttribute) => {
437
+ if (!messagesForBrowser) {
438
+ return "";
439
+ }
440
+ const consoleLines = [];
441
+ for (const message of messagesForBrowser) {
442
+ let funcString = "console.log";
443
+ if (message.level === "error") {
444
+ funcString = "console.error";
445
+ }
446
+ if (message.level === "warn") {
447
+ funcString = "console.warn";
448
+ }
449
+ const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
450
+ consoleLines.push(` ${funcString}(${argString});`);
451
+ }
452
+ let groupStart = "";
453
+ let groupEnd = "";
454
+ if (groupLabel !== void 0 && groupLabel !== null) {
455
+ groupStart = `
456
+ console.group(${JSON.stringify(groupLabel)});`;
457
+ groupEnd = ` console.groupEnd()
458
+ `;
459
+ }
460
+ return `<script ${nonceAttribute}>${groupStart}
461
+ ${consoleLines.join("\n")}
462
+ ${groupEnd}</script>
463
+ `;
464
+ };
465
+ getComponentExtension = (componentPath) => {
466
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
467
+ (ext) => componentPath.endsWith(ext)
468
+ );
469
+ if (filteredExtensions.length === 1) {
470
+ return filteredExtensions[0];
471
+ }
472
+ return void 0;
473
+ };
474
+ hasComponentExtension = (componentPath) => {
475
+ return !!getComponentExtension(componentPath);
476
+ };
477
+ isStorybookStory = (componentPath) => {
478
+ return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
479
+ };
480
+ removeComponentExtension = (componentPath) => {
481
+ const ext = getComponentExtension(componentPath);
482
+ if (ext == null) {
483
+ return componentPath;
484
+ }
485
+ return componentPath.slice(0, -1 * ext.length);
486
+ };
487
+ COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
488
+ ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
489
+ removeIndexFromPath = (id) => {
490
+ return id.replace(/\/index\.[jt]sx?$/, "");
491
+ };
492
+ removeIndexOrTrailingJsFromPath = (id) => {
493
+ return removeIndexFromPath(id).replace(/\.[jt]sx?$/, "");
494
+ };
495
+ HEALTHCHECKS_ENABLED_DEFAULT = true;
496
+ HEALTHCHECKS_STRICT_DEFAULT = false;
497
+ BUILD_INFO_PATH = "/build-info.json";
498
+ GATES = [
499
+ "CMS:JSRenderer:GetServerSideProps",
500
+ "CMS:JSRenderer:ModuleHubl",
501
+ "CMS:JSRenderer:RemoveCjsPlugin",
502
+ "CMS:JSRenderer:RemoveMockClientEntryPlugin",
503
+ "CMS:JSRenderer:AnalyzeCmsModules",
504
+ "CMS:JSRenderer:CompressResponse"
505
+ ];
506
+ ENABLED_FEATURES_GATE_MAP = {
507
+ "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
508
+ "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
509
+ "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
510
+ };
511
+ findAllComponentsIn = (webRoot2, componentsFolder) => {
512
+ const fullComponentsFolderPath = join(webRoot2, componentsFolder);
513
+ const componentsByName = {};
514
+ if (!existsSync(fullComponentsFolderPath)) {
515
+ return componentsByName;
516
+ }
517
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
518
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
519
+ const subdirPath = join(componentsFolder, fileOrFolderName);
520
+ const isDirectory = lstatSync(fullPath).isDirectory();
521
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
522
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
523
+ componentsByName[subdirPathNoExtension] = subdirPath;
524
+ } else if (isDirectory) {
525
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
526
+ const potentialIndexModule = join(
527
+ subdirPath,
528
+ `index${potentialExtension}`
529
+ );
530
+ const fullPotentialPath = join(
531
+ fullPath,
532
+ `index${potentialExtension}`
533
+ );
534
+ if (existsSync(fullPotentialPath)) {
535
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
536
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
537
+ break;
538
+ }
539
+ }
540
+ }
541
+ });
542
+ return componentsByName;
543
+ };
544
+ }
545
+ });
546
+
547
+ // ../cms-js-internal/dist/index.js
548
+ var dist_exports = {};
549
+ __export(dist_exports, {
550
+ COMPONENT_EXTENSIONS: () => COMPONENT_EXTENSIONS,
551
+ CSS_LANGS_RE: () => CSS_LANGS_RE,
552
+ DndAreaSlot: () => DndAreaSlot,
553
+ ENABLED_FEATURES_GATE_MAP: () => ENABLED_FEATURES_GATE_MAP,
554
+ ENTRY_POINTS_PATH: () => ENTRY_POINTS_PATH,
555
+ GATES: () => GATES,
556
+ GlobalPartialSlot: () => GlobalPartialSlot,
557
+ MODULE_FOLDER_PATH: () => MODULE_FOLDER_PATH,
558
+ ModuleSlot: () => ModuleSlot,
559
+ TEMPLATE_FOLDER_PATH: () => TEMPLATE_FOLDER_PATH,
560
+ VIRTUAL_CONFIG_SETUP: () => VIRTUAL_CONFIG_SETUP,
561
+ VIRTUAL_ISLAND_RUNTIME: () => VIRTUAL_ISLAND_RUNTIME,
562
+ areBuildHealthChecksEnabled: () => areBuildHealthChecksEnabled,
563
+ clientIslandEntryPlugin: () => clientIslandEntryPlugin,
564
+ collectCssInDev: () => collectCssInDev,
565
+ collectCssModules: () => collectCssModules,
566
+ createIslandsGlobalJsForClientInDev: () => createIslandsGlobalJsForClientInDev,
567
+ doHealthChecksFailTheBuild: () => doHealthChecksFailTheBuild,
568
+ escapeForInlineJS: () => escapeForInlineJS,
569
+ findAllComponentsIn: () => findAllComponentsIn,
570
+ findAllModulesInRoot: () => findAllModulesInRoot,
571
+ findAllPartialsInRoot: () => findAllPartialsInRoot,
572
+ findCmsModules: () => findCmsModules,
573
+ getBaseAssetUrlFromBuild: () => getBaseAssetUrlFromBuild,
574
+ getBuildInfo: () => getBuildInfo,
575
+ getCMSAssetConfig: () => getCMSAssetConfig,
576
+ getCMSAssetConfigIfExists: () => getCMSAssetConfigIfExists,
577
+ getCombinedReactUrl: () => getCombinedReactUrl,
578
+ getComponentExtension: () => getComponentExtension,
579
+ getEntryPointHash: () => getEntryPointHash,
580
+ getEntryPointHashWithIndexSuffix: () => getEntryPointHashWithIndexSuffix,
581
+ getIslandRuntimeConfigUrl: () => getIslandRuntimeConfigUrl,
582
+ getIslandUrls: () => getIslandUrls,
583
+ getServerGlobalsToInject: () => getServerGlobalsToInject,
584
+ getServerIncludePrebundleDepPatterns: () => getServerIncludePrebundleDepPatterns,
585
+ hasComponentExtension: () => hasComponentExtension,
586
+ includesHublDataReference: () => includesHublDataReference,
587
+ isStorybookStory: () => isStorybookStory,
588
+ isStylesheetAsset: () => isStylesheetAsset,
589
+ isUngatedFor: () => isUngatedFor,
590
+ jsonStringifyAndEscapeForInlineJS: () => jsonStringifyAndEscapeForInlineJS,
591
+ namespaceModulePropsShape: () => namespaceModulePropsShape,
592
+ noncePlaceholderPlugin: () => noncePlaceholderPlugin,
593
+ removeComponentExtension: () => removeComponentExtension,
594
+ removeIndexFromPath: () => removeIndexFromPath,
595
+ removeIndexOrTrailingJsFromPath: () => removeIndexOrTrailingJsFromPath,
596
+ renderComponentOnServer: () => renderComponentOnServer,
597
+ renderFieldsToJson: () => renderFieldsToJson,
598
+ renderOnServer: () => renderOnServer,
599
+ renderStreamToPromise: () => renderStreamToPromise,
600
+ resolveIslandPlugin: () => resolveIslandPlugin,
601
+ resolveIslandToPlainModuleNoopPlugin: () => resolveIslandToPlainModuleNoopPlugin,
602
+ resolveIslandToPlainModulePlugin: () => resolveIslandToPlainModulePlugin,
603
+ scriptTagToLogServerMessages: () => scriptTagToLogServerMessages,
604
+ serializeIslandDataForInlineScript: () => serializeIslandDataForInlineScript,
605
+ setIn: () => setIn,
606
+ ungatedAtBuildTimeFor: () => ungatedAtBuildTimeFor,
607
+ virtualClientRenderIslandModuleId: () => virtualClientRenderIslandModuleId
608
+ });
609
+ import * as dotProp from "dot-prop";
610
+ import * as parser from "@babel/parser";
611
+ import _traverse from "@babel/traverse";
612
+ import * as t from "@babel/types";
613
+ import { jsx } from "react/jsx-runtime";
614
+ import stream from "stream";
615
+ import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
616
+ import * as cmsComponents from "@hubspot/cms-components";
617
+ import { ServerRenderContext } from "@hubspot/cms-components";
618
+ import { isValidElement, cloneElement } from "react";
619
+ function filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {
620
+ if (!supplementalFieldValues) {
621
+ return supplementalFieldValues;
622
+ }
623
+ if (!supplementalFieldValuesRead) {
624
+ return supplementalFieldValues;
625
+ }
626
+ const result = {};
627
+ Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {
628
+ if (hasProperty(supplementalFieldValues, fieldPath)) {
629
+ setProperty(
630
+ result,
631
+ fieldPath,
632
+ getProperty(supplementalFieldValues, fieldPath)
633
+ );
634
+ }
635
+ });
636
+ return result;
637
+ }
638
+ function getIslandUrls(roots, viteDevServer) {
639
+ return roots.map((island) => {
640
+ const islandModule = viteDevServer.moduleGraph.getModuleById(
641
+ island.moduleId
642
+ );
643
+ if (!islandModule) {
644
+ throw new Error(`Unknown island moduleId: ${island.moduleId}`);
645
+ }
646
+ let wrapperModule;
647
+ if (island.wrapperModuleId) {
648
+ wrapperModule = viteDevServer.moduleGraph.getModuleById(
649
+ island.wrapperModuleId
650
+ );
651
+ }
652
+ const tweakedIsland = {
653
+ ...island,
654
+ url: islandModule.url,
655
+ wrapperUrl: wrapperModule ? wrapperModule.url : void 0
656
+ };
657
+ return tweakedIsland;
658
+ });
659
+ }
660
+ function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
661
+ if (!perServerRequestData.has("sharedStateIDs")) {
662
+ return new Map(perServerRequestData);
663
+ }
664
+ const perServerRequestDataWithUrls = new Map(
665
+ perServerRequestData
666
+ );
667
+ perServerRequestData.get("sharedStateIDs").forEach((id) => {
668
+ const reducer = perServerRequestData.get(id);
669
+ if (reducer.reducerFuncModuleId) {
670
+ const reducerWithUrl = {
671
+ ...reducer,
672
+ reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(
673
+ reducer.reducerFuncModuleId
674
+ ).url
675
+ };
676
+ perServerRequestDataWithUrls.set(id, reducerWithUrl);
677
+ }
678
+ });
679
+ return perServerRequestDataWithUrls;
680
+ }
681
+ function noncePlaceholderPlugin() {
682
+ const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
683
+ return {
684
+ name: "hs-nonce-placeholder",
685
+ enforce: "post",
686
+ apply() {
687
+ return HS_DEPLOYED;
688
+ },
689
+ transformIndexHtml(html) {
690
+ const regex = /<(style|script|link) (.*)>/gi;
691
+ const replacer = (_, p1, p2) => {
692
+ if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
693
+ p1 === "link" && p2.includes('rel="stylesheet"')) {
694
+ const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
695
+ p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
696
+ }
697
+ return `<${p1} ${p2}>`;
698
+ };
699
+ return html.replace(regex, replacer);
700
+ }
701
+ };
702
+ }
703
+ function findCmsModules(buildContentDescriptors = {}) {
704
+ let config;
705
+ return {
706
+ enforce: "pre",
707
+ name: "findCmsModules",
708
+ configResolved(resolvedConfig) {
709
+ config = resolvedConfig;
710
+ },
711
+ transform(code, id) {
712
+ const moduleInfo = this.getModuleInfo(id);
713
+ if (!shouldAnalyzeModule(config, moduleInfo, code))
714
+ return null;
715
+ const contentDescriptors = analyzeSourceCodeUsages(
716
+ this,
717
+ moduleInfo,
718
+ config,
719
+ code
720
+ );
721
+ if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
722
+ return {
723
+ meta: {
724
+ findCmsModules: contentDescriptors
725
+ }
726
+ };
727
+ }
728
+ },
729
+ buildEnd(error) {
730
+ if (error)
731
+ throw error;
732
+ const entryPoints = getEntryPoints(this, config);
733
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
734
+ this,
735
+ entryPoints
736
+ );
737
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
738
+ config,
739
+ entryPointCmsModuleMap
740
+ );
741
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
742
+ this,
743
+ entryPoints
744
+ );
745
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
746
+ config,
747
+ entryPointIslandCmsModuleMap
748
+ );
749
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
750
+ this.error(`
751
+ Error: <Module /> cannot be used within <Island />
752
+ Found invalid usages:
753
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
754
+ `);
755
+ }
756
+ const modulesWithinModules = filterEntryPointsToModules(
757
+ relativeEntryPointCmsModuleMap
758
+ );
759
+ if (Object.keys(modulesWithinModules).length > 0) {
760
+ this.error(`
761
+ Error: <Module /> can only be used in React Partials
762
+ Found invalid usages:
763
+ ${JSON.stringify(modulesWithinModules, null, 2)}
764
+ `);
765
+ }
766
+ Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
767
+ }
768
+ };
769
+ }
770
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
771
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
772
+ ([entryPointPath, cmsModules]) => {
773
+ return [toRelativePath(config, entryPointPath), cmsModules];
774
+ }
775
+ );
776
+ return Object.fromEntries(relativeEntries);
777
+ }
778
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
779
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
780
+ ([entryPointPath, islandContentDescriptors]) => {
781
+ const islandCmsModuleUsage = Object.fromEntries(
782
+ Object.entries(islandContentDescriptors).map(
783
+ ([islandPath, contentDescriptors]) => {
784
+ return [
785
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
786
+ contentDescriptors
787
+ ];
788
+ }
789
+ )
790
+ );
791
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
792
+ }
793
+ );
794
+ return Object.fromEntries(relativeEntries);
795
+ }
796
+ function toRelativePath(config, path3) {
797
+ return path3.replace(`${config.root}/`, "");
798
+ }
799
+ function shouldAnalyzeModule(config, moduleInfo, code) {
800
+ const [fileId, __] = moduleInfo.id.split("?");
801
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
802
+ return (
803
+ // analyze customer code only
804
+ !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
805
+ (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
806
+ );
807
+ }
808
+ function getEntryPoints(ctx, config) {
809
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
810
+ }
811
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
812
+ const entryPointCmsModuleUsage = {};
813
+ for (const entryPoint of entryPoints) {
814
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
815
+ if (result) {
816
+ entryPointCmsModuleUsage[entryPoint.id] = result;
817
+ }
818
+ }
819
+ return entryPointCmsModuleUsage;
820
+ }
821
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
822
+ const entryPointIslandsCmsModuleMap = {};
823
+ for (const entryPoint of entryPoints) {
824
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
825
+ if (result) {
826
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
827
+ }
828
+ }
829
+ return entryPointIslandsCmsModuleMap;
830
+ }
831
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
832
+ const sourceAst = parser.parse(code, {
833
+ sourceType: "module",
834
+ plugins: ["jsx", "typescript"]
835
+ });
836
+ const contentDescriptors = { modules: {}, dndAreas: {} };
837
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
838
+ let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
839
+ traverse(sourceAst, {
840
+ ImportDeclaration(path3) {
841
+ if (t.isStringLiteral(path3.node.source, {
842
+ value: "@hubspot/cms-components"
843
+ })) {
844
+ for (const specifier of path3.node.specifiers) {
845
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
846
+ name: CMS_MODULE_COMPONENT_NAME
847
+ })) {
848
+ moduleComponentLocalImportName = specifier.local.name;
849
+ }
850
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
851
+ name: DND_AREA_COMPONENT_NAME
852
+ })) {
853
+ dndAreaComponentLocalImportName = specifier.local.name;
854
+ }
855
+ }
856
+ }
857
+ },
858
+ JSXOpeningElement(path3) {
859
+ if (t.isJSXIdentifier(path3.node.name, {
860
+ name: moduleComponentLocalImportName
861
+ })) {
862
+ let cmsModuleName;
863
+ let cmsModulePath;
864
+ let cmsModuleLabel;
865
+ for (const prop of path3.node.attributes) {
866
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
867
+ cmsModuleName = prop.value.value;
868
+ continue;
869
+ }
870
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
871
+ cmsModulePath = prop.value.value;
872
+ continue;
873
+ }
874
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
875
+ cmsModuleLabel = prop.value.value;
876
+ continue;
877
+ }
878
+ ctx.error(
879
+ new Error(
880
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
881
+ )
882
+ );
883
+ }
884
+ const cmsModuleProps = {
885
+ name: cmsModuleName,
886
+ path: cmsModulePath
887
+ };
888
+ if (cmsModuleLabel) {
889
+ cmsModuleProps.label = cmsModuleLabel;
890
+ }
891
+ if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
892
+ ctx.error(
893
+ new Error(
894
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
895
+ )
896
+ );
897
+ }
898
+ contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
899
+ }
900
+ if (t.isJSXIdentifier(path3.node.name, {
901
+ name: dndAreaComponentLocalImportName
902
+ })) {
903
+ let dndAreaName;
904
+ for (const prop of path3.node.attributes) {
905
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
906
+ dndAreaName = prop.value.value;
907
+ continue;
908
+ }
909
+ ctx.error(
910
+ new Error(
911
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
912
+ )
913
+ );
914
+ }
915
+ const dndArea = {
916
+ name: dndAreaName
917
+ };
918
+ if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
919
+ ctx.error(
920
+ new Error(
921
+ `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
922
+ )
923
+ );
924
+ }
925
+ contentDescriptors.dndAreas[dndArea.name] = dndArea;
926
+ }
927
+ }
928
+ });
929
+ return contentDescriptors;
930
+ }
931
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
932
+ if (Object.hasOwn(result, moduleId)) {
933
+ return result[moduleId];
934
+ }
935
+ const moduleInfo = ctx.getModuleInfo(moduleId);
936
+ let entryPointContentDescriptors = null;
937
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
938
+ entryPointContentDescriptors = {
939
+ ...entryPointContentDescriptors,
940
+ ...moduleInfo.meta[PLUGIN_NAME]
941
+ };
942
+ }
943
+ for (const importedId of [
944
+ ...moduleInfo.importedIds,
945
+ ...moduleInfo.dynamicallyImportedIds
946
+ ]) {
947
+ if (processed.has(importedId)) {
948
+ continue;
949
+ }
950
+ const importedResult = findCmsModuleUsages(
951
+ ctx,
952
+ importedId,
953
+ processed,
954
+ result
955
+ );
956
+ if (importedResult) {
957
+ entryPointContentDescriptors = {
958
+ ...entryPointContentDescriptors,
959
+ ...importedResult
960
+ };
961
+ }
962
+ }
963
+ if (entryPointContentDescriptors) {
964
+ result[moduleId] = entryPointContentDescriptors;
965
+ }
966
+ processed.add(moduleId);
967
+ return entryPointContentDescriptors;
968
+ }
969
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
970
+ processedIslands.add(moduleId);
971
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
972
+ return islandModuleResults[moduleId];
973
+ }
974
+ const moduleInfo = ctx.getModuleInfo(moduleId);
975
+ let resultForModuleId = {};
976
+ if (moduleInfo.id.endsWith("?client-entry")) {
977
+ const mergedDataDependencies = findCmsModuleUsages(
978
+ ctx,
979
+ moduleInfo.id,
980
+ processed,
981
+ results
982
+ );
983
+ if (mergedDataDependencies) {
984
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
985
+ }
986
+ }
987
+ for (const importedId of [
988
+ ...moduleInfo.importedIds,
989
+ ...moduleInfo.dynamicallyImportedIds
990
+ ]) {
991
+ if (processedIslands.has(importedId)) {
992
+ continue;
993
+ }
994
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
995
+ ctx,
996
+ importedId,
997
+ processedIslands,
998
+ islandModuleResults,
999
+ processed,
1000
+ results
1001
+ );
1002
+ if (importerCmsModuleUsageResult) {
1003
+ resultForModuleId = {
1004
+ ...resultForModuleId,
1005
+ ...importerCmsModuleUsageResult
1006
+ };
1007
+ }
1008
+ }
1009
+ if (Object.keys(resultForModuleId).length > 0) {
1010
+ islandModuleResults[moduleId] = resultForModuleId;
1011
+ return resultForModuleId;
1012
+ }
1013
+ return null;
1014
+ }
1015
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
1016
+ return Object.fromEntries(
1017
+ Object.entries(entryPointCmsModuleMap).filter(
1018
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
1019
+ )
1020
+ );
1021
+ }
1022
+ async function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {
1023
+ const { props } = propsAndDeps;
1024
+ const componentDebugName = Component.displayName || Component.name;
1025
+ const supplementalFieldValues = contextOptions == null ? void 0 : contextOptions.supplementalFieldValues;
1026
+ const messagesForBrowser = contextOptions == null ? void 0 : contextOptions.messagesForBrowser;
1027
+ const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
1028
+ environmentConfig,
1029
+ entryPointBasePath,
1030
+ supplementalFieldValues,
1031
+ messagesForBrowser
1032
+ }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);
1033
+ if (getServerSideProps !== void 0 && typeof getServerSideProps === "function") {
1034
+ const gSSPResult = await renderServerSidePropsWithAsyncLocalStoreContext(
1035
+ getServerSideProps,
1036
+ propsAndDeps,
1037
+ renderContext
1038
+ );
1039
+ if (gSSPResult) {
1040
+ props.serverSideProps = gSSPResult.serverSideProps;
1041
+ }
1042
+ }
1043
+ return renderOnServer(
1044
+ /* @__PURE__ */ jsx(Component, { ...props }),
1045
+ renderContext,
1046
+ componentDebugName,
1047
+ renderOptions
1048
+ );
1049
+ }
1050
+ async function renderOnServer(elements, renderContext = bootStrapRenderContext(), debugName, renderOptions) {
1051
+ let html = await renderStreamToPromise(
1052
+ /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }),
1053
+ renderOptions
1054
+ );
1055
+ if (renderContext.messagesForBrowser.length > 0) {
1056
+ html = `${html}${scriptTagToLogServerMessages(
1057
+ renderContext.messagesForBrowser,
1058
+ `Server messages rendering: ${debugName}`
1059
+ )}`;
1060
+ }
1061
+ return { html, renderContext };
1062
+ }
1063
+ function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
1064
+ if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
1065
+ prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
1066
+ }
1067
+ const serializedJson = jsonStringifyAndEscapeForInlineJS(
1068
+ environmentConfig.toJSON(),
1069
+ { baseIndent: 6, prettyPrint }
1070
+ );
1071
+ const globals = [`window.__hsEnvConfig = ${serializedJson};`];
1072
+ if (hsServerPageUrl) {
1073
+ globals.push(
1074
+ `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(
1075
+ hsServerPageUrl
1076
+ )};`
1077
+ );
1078
+ }
1079
+ if (hsBasePath) {
1080
+ globals.push(
1081
+ `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`
1082
+ );
1083
+ }
1084
+ if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {
1085
+ const firstCriticalDevError = criticalDevErrors[0];
1086
+ globals.push(`
1087
+ customElements.whenDefined('vite-error-overlay').then(() => {
1088
+ const ErrorOverlay = customElements.get('vite-error-overlay');
1089
+ const error = new Error(${jsonStringifyAndEscapeForInlineJS(
1090
+ firstCriticalDevError.message
1091
+ )});
1092
+ const overlay = new ErrorOverlay(error);
1093
+
1094
+ document.body.appendChild(overlay);
1095
+ })
1096
+ `);
1097
+ }
1098
+ const nonceAttr = includeNonces && cmsComponents.SCRIPT_NONCE_PLACEHOLDER ? ` nonce="${cmsComponents.SCRIPT_NONCE_PLACEHOLDER}"` : "";
1099
+ return `
1100
+ <script type="text/javascript"${nonceAttr}>
1101
+ ${globals.join("\n ")}
1102
+ </script>
1103
+ `;
1104
+ }
1105
+ function renderFieldsJSX(fieldsJSX) {
1106
+ let moduleJson;
1107
+ const outputCallback = (callbackJson) => {
1108
+ moduleJson = callbackJson;
1109
+ };
1110
+ renderToStaticMarkup(
1111
+ cloneElement(fieldsJSX, {
1112
+ outputCallback
1113
+ })
1114
+ );
1115
+ if (!moduleJson) {
1116
+ throw new Error("couldn't render module fields definition to fields.json");
1117
+ }
1118
+ return moduleJson;
1119
+ }
1120
+ function renderFieldsToJson(fields, moduleName) {
1121
+ let fieldsJSON;
1122
+ try {
1123
+ if (isValidElement(fields)) {
1124
+ fieldsJSON = renderFieldsJSX(fields);
1125
+ } else if (Array.isArray(fields)) {
1126
+ fieldsJSON = fields;
1127
+ } else {
1128
+ throw new Error(
1129
+ `Couldn't recognize \`fields\` value for module ${moduleName}`
1130
+ );
1131
+ }
1132
+ return fieldsJSON;
1133
+ } catch (e2) {
1134
+ e2.message = `Error when rendering fields for ${moduleName}: ${e2.message}`;
1135
+ throw e2;
1136
+ }
1137
+ }
1138
+ function DndAreaSlot(props) {
1139
+ return /* @__PURE__ */ jsx(
1140
+ "div",
1141
+ {
1142
+ suppressHydrationWarning: true,
1143
+ dangerouslySetInnerHTML: {
1144
+ __html: `<!-- hs-dnd-area-placeholder-${props.name} -->`
1145
+ }
1146
+ }
1147
+ );
1148
+ }
1149
+ function ModuleSlot(props) {
1150
+ return /* @__PURE__ */ jsx(
1151
+ "div",
1152
+ {
1153
+ suppressHydrationWarning: true,
1154
+ dangerouslySetInnerHTML: {
1155
+ __html: `<!-- hs-module-placeholder-${props.name} -->`
1156
+ }
1157
+ }
1158
+ );
1159
+ }
1160
+ function GlobalPartialSlot(props) {
1161
+ return /* @__PURE__ */ jsx(
1162
+ "div",
1163
+ {
1164
+ suppressHydrationWarning: true,
1165
+ dangerouslySetInnerHTML: {
1166
+ __html: `<!-- hs-global-partial-placeholder-${props.name} -->`
1167
+ }
1168
+ }
1169
+ );
1170
+ }
1171
+ var setProperty, getProperty, hasProperty, serializeIslandDataForInlineScript, writeSharedStateToJsGlobal, createIslandsGlobalJsForClientInDev, traverse, CMS_MODULE_COMPONENT_NAME, DND_AREA_COMPONENT_NAME, PLUGIN_NAME, promiseForNewWritableStream, renderStreamToPromise, createServerRenderContextV22, createServerRenderContext2, renderServerSidePropsWithAsyncLocalStoreContext, bootStrapRenderContext;
1172
+ var init_dist = __esm({
1173
+ "../cms-js-internal/dist/index.js"() {
1174
+ init_types_Bqf9htWu();
1175
+ init_types_Bqf9htWu();
1176
+ ({ setProperty, getProperty, hasProperty } = dotProp);
1177
+ serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
1178
+ const islandsArrayToSerialize = tweakedIslandsArray.map(
1179
+ ({
1180
+ id,
1181
+ moduleName,
1182
+ moduleId,
1183
+ props,
1184
+ hydrateOn,
1185
+ clientOnly,
1186
+ priority,
1187
+ url,
1188
+ sharedStateID,
1189
+ supplementalFieldValues,
1190
+ wrapperModuleId,
1191
+ wrapperUrl,
1192
+ resolvedDataDependencies
1193
+ }) => {
1194
+ const output = {
1195
+ id,
1196
+ moduleName,
1197
+ moduleId,
1198
+ hydrateOn,
1199
+ clientOnly,
1200
+ priority,
1201
+ props,
1202
+ url
1203
+ };
1204
+ if (resolvedDataDependencies) {
1205
+ output.resolvedDataDependencies = resolvedDataDependencies;
1206
+ }
1207
+ if (sharedStateID) {
1208
+ output.sharedStateID = sharedStateID;
1209
+ }
1210
+ if (wrapperModuleId) {
1211
+ output.wrapperModuleId = wrapperModuleId;
1212
+ }
1213
+ if (wrapperUrl) {
1214
+ output.wrapperUrl = wrapperUrl;
1215
+ }
1216
+ const filteredSupplementalFieldValues = filterOutUnreadSupplementalFieldValues(
1217
+ supplementalFieldValues,
1218
+ perServerRequestData.get("supplementalFieldValuesRead")
1219
+ );
1220
+ if (filteredSupplementalFieldValues) {
1221
+ output.supplementalFieldValues = filteredSupplementalFieldValues;
1222
+ }
1223
+ if (output.clientOnly) {
1224
+ output.supplementalFieldValues = supplementalFieldValues;
1225
+ }
1226
+ return output;
1227
+ }
1228
+ );
1229
+ return jsonStringifyAndEscapeForInlineJS(islandsArrayToSerialize, {
1230
+ baseIndent,
1231
+ jsonIndent: 2,
1232
+ prettyPrint
1233
+ });
1234
+ };
1235
+ writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0, prettyPrint) => {
1236
+ const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x2) => !!x2);
1237
+ if (sharedStateIDs.length > 0) {
1238
+ const indentString = " ".repeat(indent);
1239
+ const stateByID = {};
1240
+ sharedStateIDs.forEach(
1241
+ (id) => stateByID[id] = perServerRequestData.get(id)
1242
+ );
1243
+ const stringifiedState = jsonStringifyAndEscapeForInlineJS(stateByID, {
1244
+ prettyPrint,
1245
+ jsonIndent: 2
1246
+ });
1247
+ return `
1248
+
1249
+ var newState = ${stringifiedState};
1250
+ if(window.__hsSSInit) {
1251
+ window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
1252
+ } else {
1253
+ window.__hsSSInit = newState;
1254
+ }`.replace(/\n/gm, `
1255
+ ${indentString}`);
1256
+ }
1257
+ return "";
1258
+ };
1259
+ createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
1260
+ const islands = getIslandUrls(roots, viteDevServer);
1261
+ const perServerRequestDataWithUrls = getPerServerRequestUrls(
1262
+ perServerRequestData,
1263
+ viteDevServer
1264
+ );
1265
+ return `${" ".repeat(
1266
+ indent
1267
+ )}window.__islands = ${serializeIslandDataForInlineScript(
1268
+ islands,
1269
+ perServerRequestData,
1270
+ indent,
1271
+ prettyPrint
1272
+ )}${writeSharedStateToJsGlobal(
1273
+ islands,
1274
+ perServerRequestDataWithUrls,
1275
+ indent,
1276
+ prettyPrint
1277
+ )}`;
1278
+ };
1279
+ traverse = _traverse.default;
1280
+ CMS_MODULE_COMPONENT_NAME = "Module";
1281
+ DND_AREA_COMPONENT_NAME = "DndArea";
1282
+ PLUGIN_NAME = "findCmsModules";
1283
+ promiseForNewWritableStream = () => {
1284
+ const chunks = [];
1285
+ const writableStream = new stream.Writable();
1286
+ writableStream._write = (chunk, encoding, done) => {
1287
+ chunks.push(Buffer.from(chunk));
1288
+ done();
1289
+ };
1290
+ const streamDonePromise = new Promise((resolve, reject) => {
1291
+ writableStream.on("error", (error) => {
1292
+ reject(error);
1293
+ });
1294
+ writableStream._final = (done) => {
1295
+ resolve(Buffer.concat(chunks).toString("utf8"));
1296
+ done();
1297
+ };
1298
+ });
1299
+ return { streamDonePromise, writableStream };
1300
+ };
1301
+ renderStreamToPromise = async (reactElements, options) => {
1302
+ const { streamDonePromise, writableStream } = promiseForNewWritableStream();
1303
+ const {
1304
+ pipe
1305
+ /* abort */
1306
+ } = renderToPipeableStream(reactElements, {
1307
+ ...options || {},
1308
+ onShellReady() {
1309
+ },
1310
+ onAllReady() {
1311
+ pipe(writableStream);
1312
+ if (options == null ? void 0 : options.onAllReady) {
1313
+ options.onAllReady();
1314
+ }
1315
+ }
1316
+ });
1317
+ return streamDonePromise;
1318
+ };
1319
+ ({
1320
+ createServerRenderContextV2: createServerRenderContextV22,
1321
+ createServerRenderContext: createServerRenderContext2,
1322
+ renderServerSidePropsWithAsyncLocalStoreContext
1323
+ } = cmsComponents);
1324
+ bootStrapRenderContext = () => {
1325
+ const renderContext = createServerRenderContextV22 ? createServerRenderContextV22(null, {
1326
+ environmentConfig: null,
1327
+ entryPointBasePath: "",
1328
+ supplementalFieldValues: {},
1329
+ messagesForBrowser: []
1330
+ }) : createServerRenderContext2("", null);
1331
+ return renderContext;
1332
+ };
1333
+ }
1334
+ });
1335
+
1336
+ // src/storybook-main/main.ts
1337
+ init_dist();
1338
+ import path2 from "path";
1339
+ import { createRequire } from "module";
1340
+ import { mergeConfig } from "vite";
1341
+ import { withoutVitePlugins } from "@storybook/builder-vite";
1342
+ import { default as react } from "@vitejs/plugin-react";
1343
+ var webRoot = process.env.WEB_ROOT;
1344
+ var storyPath = path2.resolve(process.cwd(), webRoot, "**/*.stories.*");
1345
+ var jsRenderingGates = process.env.GATES ? process.env.GATES.split(",") : [];
1346
+ var main_default = {
1347
+ addons: ["@storybook/addon-essentials"],
1348
+ framework: "@storybook/react-vite",
1349
+ stories: [storyPath],
1350
+ previewHead: (head) => {
1351
+ return `
1352
+ ${head}
1353
+
1354
+ <script type="module">
1355
+ import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';
1356
+
1357
+ initConfigSingletonFromJSON(${jsonStringifyAndEscapeForInlineJS(
1358
+ {
1359
+ portalId: process.env.portalId,
1360
+ hublet: process.env.hublet,
1361
+ hsEnv: process.env.hsEnv,
1362
+ hsDeployed: false,
1363
+ hsJSRGates: jsRenderingGates
1364
+ },
1365
+ { prettyPrint: false }
1366
+ )})
1367
+ </script>
1368
+
1369
+ `;
1370
+ },
1371
+ viteFinal: async (config) => {
1372
+ const { resolveIslandPlugin: resolveIslandPlugin2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
1373
+ const viteConfig = {
1374
+ define: {
1375
+ global: "globalThis",
1376
+ "process.env": "{}",
1377
+ "process.platform": '"browser"',
1378
+ "process.version": '"v18.0.0"',
1379
+ "process.versions": "{}",
1380
+ "process.browser": "true",
1381
+ "process.nextTick": "((fn, ...args) => setTimeout(() => fn(...args), 0))"
1382
+ },
1383
+ resolve: {
1384
+ dedupe: [
1385
+ "react",
1386
+ "react-dom",
1387
+ "@hubspot/cms-components",
1388
+ "@hubspot/cms-dev-server"
1389
+ ],
1390
+ alias: {
1391
+ process: "process/browser",
1392
+ buffer: "buffer"
1393
+ }
1394
+ },
1395
+ optimizeDeps: {
1396
+ include: ["react", "react-dom", "react-dom/client", "buffer"],
1397
+ exclude: ["fsevents"]
1398
+ },
1399
+ css: {
1400
+ postcss: webRoot
1401
+ },
1402
+ plugins: [
1403
+ // Provide Node.js globals for browser environment
1404
+ {
1405
+ name: "provide-nodejs-globals",
1406
+ config(__config, { command }) {
1407
+ if (command === "serve") {
1408
+ config.define = config.define || {};
1409
+ config.define.global = "globalThis";
1410
+ config.define.Buffer = "Buffer";
1411
+ }
1412
+ },
1413
+ transformIndexHtml: {
1414
+ order: "pre",
1415
+ handler(html) {
1416
+ return html.replace(
1417
+ "<head>",
1418
+ `<head>
1419
+ <script type="module">
1420
+ import { Buffer } from 'buffer';
1421
+ window.Buffer = Buffer;
1422
+ globalThis.Buffer = Buffer;
1423
+ </script>`
1424
+ );
1425
+ }
1426
+ }
1427
+ },
1428
+ resolveIslandPlugin2(),
1429
+ (() => {
1430
+ const require2 = createRequire(import.meta.url);
1431
+ return react({
1432
+ babel: {
1433
+ plugins: [
1434
+ require2.resolve("babel-plugin-styled-components"),
1435
+ require2.resolve("styled-jsx/babel"),
1436
+ require2.resolve("babel-plugin-macros")
1437
+ ]
1438
+ }
1439
+ });
1440
+ })()
1441
+ ]
1442
+ };
1443
+ const configNoReact = {
1444
+ ...config,
1445
+ // replacing the default usage of `@vite/plugin-react` (it emits multiple
1446
+ // sub-plugins listed here) to add our babel plugin configuration
1447
+ plugins: await withoutVitePlugins(config.plugins, [
1448
+ "vite:react-babel",
1449
+ "vite:react-swc",
1450
+ "vite:react-refresh"
1451
+ ])
1452
+ };
1453
+ return mergeConfig(configNoReact, viteConfig);
1454
+ }
1455
+ };
1456
+ export {
1457
+ main_default as default
1458
+ };