@hubspot/cms-dev-server 1.1.0-prerelease.8 → 1.2.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 (125) hide show
  1. package/dist/app/assets/LexendDeca-Bold-B8uERmr8.woff2 +0 -0
  2. package/dist/app/assets/LexendDeca-Light-BtcvwT5C.woff2 +0 -0
  3. package/dist/app/assets/LexendDeca-Medium-CxVPR2j6.woff2 +0 -0
  4. package/dist/app/assets/LexendDeca-SemiBold-BhzS3XUP.woff2 +0 -0
  5. package/dist/app/assets/index-PcyCbkys.css +1 -0
  6. package/dist/app/assets/index-tvg7JxpD.js +164 -0
  7. package/dist/app/index.html +15 -0
  8. package/dist/app/server/assets/RenderTreeSeparately-T6CL43QJ-D50VfKo0.js +111 -0
  9. package/dist/app/server/serverEntry.js +3641 -0
  10. package/dist/generateJsonFromJsx.js +744 -0
  11. package/dist/html/baseTemplate.html +1 -0
  12. package/dist/index.js +5800 -0
  13. package/dist/internalSsr.js +1312 -0
  14. package/dist/island-runtime.js +267 -0
  15. package/dist/run.js +6495 -4
  16. package/dist/storybook/index.js +241 -0
  17. package/dist/storybook-main/main.js +1457 -0
  18. package/dist/storybook-main/preview.js +21 -0
  19. package/package.json +93 -24
  20. package/types/api/designmanager.d.ts +44 -0
  21. package/types/api/project.d.ts +5 -0
  22. package/types/api/session.d.ts +2 -0
  23. package/types/components/HubLModulesList.d.ts +4 -0
  24. package/types/components/HubLTemplatesList.d.ts +5 -0
  25. package/types/components/ModulesList.d.ts +5 -0
  26. package/types/components/PartialsList.d.ts +4 -0
  27. package/types/createAppServer.d.ts +3 -0
  28. package/types/createDevServer.d.ts +5 -0
  29. package/types/createViteDevServer.d.ts +6 -0
  30. package/types/fileManager.d.ts +4 -0
  31. package/types/index.d.ts +2 -0
  32. package/types/lib/cliUtils.d.ts +15 -0
  33. package/types/lib/configHelpers.d.ts +2 -0
  34. package/types/lib/criticalDevErrorsToServerMessages.d.ts +4 -0
  35. package/types/lib/debug.d.ts +1 -0
  36. package/types/lib/errors.d.ts +6 -0
  37. package/types/lib/fetchModuleGraphQLData.d.ts +24 -0
  38. package/types/lib/fullOriginalUrlFromRequest.d.ts +2 -0
  39. package/types/lib/gates.d.ts +2 -0
  40. package/types/lib/getDevServerUIData.d.ts +60 -0
  41. package/types/lib/getFieldValuesForModule.d.ts +2 -0
  42. package/types/lib/getJSRenderingGates.d.ts +8 -0
  43. package/types/lib/httpsRedirectingServer.d.ts +11 -0
  44. package/types/lib/logColors.d.ts +6 -0
  45. package/types/lib/moduleGraph.d.ts +1 -0
  46. package/types/lib/packagePath.d.ts +1 -0
  47. package/types/lib/pathHelpers.d.ts +3 -0
  48. package/types/lib/previewUtils.d.ts +22 -0
  49. package/types/lib/proxyHelpers.d.ts +29 -0
  50. package/types/lib/renderComponentWithCSS.d.ts +14 -0
  51. package/types/lib/renderHelpers.d.ts +1 -0
  52. package/types/lib/renderModule.d.ts +11 -0
  53. package/types/lib/renderModuleFieldsJson.d.ts +4 -0
  54. package/types/lib/renderModulePreview.d.ts +6 -0
  55. package/types/lib/renderPartial.d.ts +5 -0
  56. package/types/lib/templates.d.ts +4 -0
  57. package/types/lib/trackUsage.d.ts +3 -0
  58. package/types/lib/validateHSPlatform.d.ts +3 -0
  59. package/types/lib/watchFieldsUpdates.d.ts +22 -0
  60. package/types/plugins/cmsComponentsShimPlugin.d.ts +11 -0
  61. package/types/plugins/devSecretsPlugin.d.ts +2 -0
  62. package/types/plugins/hsStaticAssetPlugin.d.ts +2 -0
  63. package/types/proxyPage/constants.d.ts +1 -0
  64. package/types/proxyPage/fetchContentMetadata.d.ts +7 -0
  65. package/types/proxyPage/fetchDomains.d.ts +9 -0
  66. package/types/proxyPage/fetchPreviewInfo.d.ts +7 -0
  67. package/types/proxyPage/proxyPage.d.ts +11 -0
  68. package/types/proxyPage/renderLocalError.d.ts +2 -0
  69. package/types/proxyPage/utils.d.ts +4 -0
  70. package/types/routes/appServerRouteHandler.d.ts +3 -0
  71. package/types/routes/createAppServerAPIRoutes.d.ts +5 -0
  72. package/types/routes/createDevServerRoutes.d.ts +4 -0
  73. package/types/routes/hublModuleRouteHandler.d.ts +2 -0
  74. package/types/routes/hublTemplateRouteHandler.d.ts +2 -0
  75. package/types/routes/legacyRouteHandler.d.ts +3 -0
  76. package/types/routes/linksToAllModulesRouteHandler.d.ts +2 -0
  77. package/types/routes/linksToAllPartialsRouteHandler.d.ts +2 -0
  78. package/types/routes/module.d.ts +3 -0
  79. package/types/routes/moduleFieldsJson.d.ts +3 -0
  80. package/types/routes/modulePreviewRouteHandler.d.ts +3 -0
  81. package/types/routes/partial.d.ts +2 -0
  82. package/types/routes/proxyPageResourceRedirect.d.ts +2 -0
  83. package/types/routes/proxyPageRouteHandler.d.ts +2 -0
  84. package/types/routes/proxyPathPageResourceRedirect.d.ts +2 -0
  85. package/types/routes/proxyPathPageRouteHandler.d.ts +2 -0
  86. package/types/routes/proxyServerlessHandler.d.ts +2 -0
  87. package/types/routes/remoteFsDirtyHandler.d.ts +2 -0
  88. package/types/shadowDevServer/createShadowDevServerRoutes.d.ts +1 -0
  89. package/types/shadowDevServer/startShadowDevServer.d.ts +1 -0
  90. package/types/storybook/getFieldsArgTypes.d.ts +3 -0
  91. package/types/storybook/getNestedFieldObjectForArgs.d.ts +6 -0
  92. package/types/storybook/index.d.ts +1 -0
  93. package/types/storybook/moduleStory.d.ts +5 -0
  94. package/types/storybook/types.d.ts +15 -0
  95. package/dist/components/ModulesList.js +0 -14
  96. package/dist/components/PartialsList.js +0 -13
  97. package/dist/createDevServer.js +0 -26
  98. package/dist/createViteDevServer.js +0 -26
  99. package/dist/lib/argHelpers.js +0 -6
  100. package/dist/lib/cli.js +0 -23
  101. package/dist/lib/fullOriginalUrlFromRequest.js +0 -3
  102. package/dist/lib/htmlHelpers.js +0 -10
  103. package/dist/lib/moduleGraph.js +0 -11
  104. package/dist/lib/proxyHelpers.js +0 -69
  105. package/dist/lib/proxyHelpers.test.js +0 -136
  106. package/dist/lib/renderComponentWithCSS.js +0 -26
  107. package/dist/lib/renderHelpers.js +0 -45
  108. package/dist/lib/renderModule.js +0 -88
  109. package/dist/lib/renderPartial.js +0 -12
  110. package/dist/lib/templates.js +0 -48
  111. package/dist/plugins/devMockClientEntryPlugin.js +0 -52
  112. package/dist/proxyPage/constants.js +0 -4
  113. package/dist/proxyPage/fetchContentMetadata.js +0 -51
  114. package/dist/proxyPage/fetchPreviewInfo.js +0 -37
  115. package/dist/proxyPage/proxyPage.js +0 -167
  116. package/dist/proxyPage/renderLocalError.js +0 -27
  117. package/dist/proxyPage/utils.js +0 -38
  118. package/dist/routes/createDevServerRoutes.js +0 -21
  119. package/dist/routes/homeRouteHandler.js +0 -12
  120. package/dist/routes/linksToAllModulesRouteHandler.js +0 -10
  121. package/dist/routes/linksToAllPartialsRouteHandler.js +0 -10
  122. package/dist/routes/module.js +0 -27
  123. package/dist/routes/partial.js +0 -27
  124. package/dist/routes/proxyPageResourceRedirect.js +0 -12
  125. package/dist/routes/proxyPageRouteHandler.js +0 -40
@@ -0,0 +1,744 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/generateJsonFromJsx.ts
4
+ import path3 from "path";
5
+ import fs from "fs/promises";
6
+ import { normalizePath as normalizePath2 } from "vite";
7
+
8
+ // src/createViteDevServer.ts
9
+ import { createServer as createViteServer } from "vite";
10
+ import { createRequire } from "module";
11
+ import { default as react } from "@vitejs/plugin-react";
12
+
13
+ // ../cms-js-internal/dist/types-ohevhxjF.js
14
+ import path from "path";
15
+ var viteRoot;
16
+ var viteCommand;
17
+ function resolveIslandPlugin(islandsSet) {
18
+ return {
19
+ enforce: "pre",
20
+ name: "resolve-islands",
21
+ configResolved(config) {
22
+ viteRoot = config.root;
23
+ viteCommand = config.command;
24
+ },
25
+ load(id) {
26
+ if (id.endsWith("?island") || id.endsWith("?client")) {
27
+ const [idWithNoParam] = id.split("?");
28
+ const islandModuleImportPath = `${idWithNoParam}?client-entry`;
29
+ const componentExtension = path.extname(idWithNoParam);
30
+ const componentFilenameWithNoExtension = path.basename(
31
+ idWithNoParam,
32
+ componentExtension
33
+ );
34
+ const modulePath = idWithNoParam.replace(`${viteRoot}/`, "");
35
+ const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
36
+ if (islandsSet) {
37
+ islandsSet.add(moduleId);
38
+ }
39
+ return `
40
+ const moduleId = '${moduleId}';
41
+
42
+ const lazyComponent = () => import('${islandModuleImportPath}');
43
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
44
+ lazyComponent.moduleId = moduleId;
45
+
46
+ export default lazyComponent;
47
+ `;
48
+ }
49
+ return null;
50
+ }
51
+ };
52
+ }
53
+ var 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";
54
+ var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
55
+ function clientIslandEntryPlugin() {
56
+ return {
57
+ enforce: "pre",
58
+ name: "client-island-entry-plugin",
59
+ resolveId(id) {
60
+ if (id === virtualClientRenderIslandModuleId) {
61
+ return virtualClientRenderIslandModuleId;
62
+ }
63
+ return null;
64
+ },
65
+ load(id) {
66
+ if (id.endsWith("?client-entry")) {
67
+ const [idWithNoParam] = id.split("?");
68
+ return `
69
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
70
+ import Component from '${idWithNoParam}';
71
+
72
+ export function render(island) {
73
+ return clientRenderIsland(island, Component)
74
+ }
75
+
76
+ export default Component;
77
+ `;
78
+ }
79
+ if (id === virtualClientRenderIslandModuleId) {
80
+ return clientRenderIsland;
81
+ }
82
+ return null;
83
+ }
84
+ };
85
+ }
86
+
87
+ // ../cms-js-internal/dist/index.js
88
+ import * as dotProp from "dot-prop";
89
+ import * as parser from "@babel/parser";
90
+ import _traverse from "@babel/traverse";
91
+ import * as t from "@babel/types";
92
+ import * as cmsComponents from "@hubspot/cms-components";
93
+ var { setProperty, getProperty, hasProperty } = dotProp;
94
+ function noncePlaceholderPlugin() {
95
+ const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
96
+ return {
97
+ name: "hs-nonce-placeholder",
98
+ enforce: "post",
99
+ apply() {
100
+ return HS_DEPLOYED;
101
+ },
102
+ transformIndexHtml(html) {
103
+ const regex = /<(style|script|link) (.*)>/gi;
104
+ const replacer = (_, p1, p2) => {
105
+ if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
106
+ p1 === "link" && p2.includes('rel="stylesheet"')) {
107
+ const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
108
+ p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
109
+ }
110
+ return `<${p1} ${p2}>`;
111
+ };
112
+ return html.replace(regex, replacer);
113
+ }
114
+ };
115
+ }
116
+ var traverse = _traverse.default;
117
+ var CMS_MODULE_COMPONENT_NAME = "Module";
118
+ var DND_AREA_COMPONENT_NAME = "DndArea";
119
+ var PLUGIN_NAME = "findCmsModules";
120
+ function findCmsModules(buildContentDescriptors = {}) {
121
+ let config;
122
+ return {
123
+ enforce: "pre",
124
+ name: "findCmsModules",
125
+ configResolved(resolvedConfig) {
126
+ config = resolvedConfig;
127
+ },
128
+ transform(code, id) {
129
+ const moduleInfo = this.getModuleInfo(id);
130
+ if (!shouldAnalyzeModule(config, moduleInfo, code))
131
+ return null;
132
+ const contentDescriptors = analyzeSourceCodeUsages(
133
+ this,
134
+ moduleInfo,
135
+ config,
136
+ code
137
+ );
138
+ if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
139
+ return {
140
+ meta: {
141
+ findCmsModules: contentDescriptors
142
+ }
143
+ };
144
+ }
145
+ },
146
+ buildEnd(error) {
147
+ if (error)
148
+ throw error;
149
+ const entryPoints = getEntryPoints(this, config);
150
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
151
+ this,
152
+ entryPoints
153
+ );
154
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
155
+ config,
156
+ entryPointCmsModuleMap
157
+ );
158
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
159
+ this,
160
+ entryPoints
161
+ );
162
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
163
+ config,
164
+ entryPointIslandCmsModuleMap
165
+ );
166
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
167
+ this.error(`
168
+ Error: <Module /> cannot be used within <Island />
169
+ Found invalid usages:
170
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
171
+ `);
172
+ }
173
+ const modulesWithinModules = filterEntryPointsToModules(
174
+ relativeEntryPointCmsModuleMap
175
+ );
176
+ if (Object.keys(modulesWithinModules).length > 0) {
177
+ this.error(`
178
+ Error: <Module /> can only be used in React Partials
179
+ Found invalid usages:
180
+ ${JSON.stringify(modulesWithinModules, null, 2)}
181
+ `);
182
+ }
183
+ Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
184
+ }
185
+ };
186
+ }
187
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
188
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
189
+ ([entryPointPath, cmsModules]) => {
190
+ return [toRelativePath(config, entryPointPath), cmsModules];
191
+ }
192
+ );
193
+ return Object.fromEntries(relativeEntries);
194
+ }
195
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
196
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
197
+ ([entryPointPath, islandContentDescriptors]) => {
198
+ const islandCmsModuleUsage = Object.fromEntries(
199
+ Object.entries(islandContentDescriptors).map(
200
+ ([islandPath, contentDescriptors]) => {
201
+ return [
202
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
203
+ contentDescriptors
204
+ ];
205
+ }
206
+ )
207
+ );
208
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
209
+ }
210
+ );
211
+ return Object.fromEntries(relativeEntries);
212
+ }
213
+ function toRelativePath(config, path4) {
214
+ return path4.replace(`${config.root}/`, "");
215
+ }
216
+ function shouldAnalyzeModule(config, moduleInfo, code) {
217
+ const [fileId, __] = moduleInfo.id.split("?");
218
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
219
+ return (
220
+ // analyze customer code only
221
+ !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
222
+ (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
223
+ );
224
+ }
225
+ function getEntryPoints(ctx, config) {
226
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
227
+ }
228
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
229
+ const entryPointCmsModuleUsage = {};
230
+ for (const entryPoint of entryPoints) {
231
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
232
+ if (result) {
233
+ entryPointCmsModuleUsage[entryPoint.id] = result;
234
+ }
235
+ }
236
+ return entryPointCmsModuleUsage;
237
+ }
238
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
239
+ const entryPointIslandsCmsModuleMap = {};
240
+ for (const entryPoint of entryPoints) {
241
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
242
+ if (result) {
243
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
244
+ }
245
+ }
246
+ return entryPointIslandsCmsModuleMap;
247
+ }
248
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
249
+ const sourceAst = parser.parse(code, {
250
+ sourceType: "module",
251
+ plugins: ["jsx", "typescript"]
252
+ });
253
+ const contentDescriptors = { modules: {}, dndAreas: {} };
254
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
255
+ let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
256
+ traverse(sourceAst, {
257
+ ImportDeclaration(path4) {
258
+ if (t.isStringLiteral(path4.node.source, {
259
+ value: "@hubspot/cms-components"
260
+ })) {
261
+ for (const specifier of path4.node.specifiers) {
262
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
263
+ name: CMS_MODULE_COMPONENT_NAME
264
+ })) {
265
+ moduleComponentLocalImportName = specifier.local.name;
266
+ }
267
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
268
+ name: DND_AREA_COMPONENT_NAME
269
+ })) {
270
+ dndAreaComponentLocalImportName = specifier.local.name;
271
+ }
272
+ }
273
+ }
274
+ },
275
+ JSXOpeningElement(path4) {
276
+ if (t.isJSXIdentifier(path4.node.name, {
277
+ name: moduleComponentLocalImportName
278
+ })) {
279
+ let cmsModuleName;
280
+ let cmsModulePath;
281
+ let cmsModuleLabel;
282
+ for (const prop of path4.node.attributes) {
283
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
284
+ cmsModuleName = prop.value.value;
285
+ continue;
286
+ }
287
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
288
+ cmsModulePath = prop.value.value;
289
+ continue;
290
+ }
291
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
292
+ cmsModuleLabel = prop.value.value;
293
+ continue;
294
+ }
295
+ ctx.error(
296
+ new Error(
297
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
298
+ )
299
+ );
300
+ }
301
+ const cmsModuleProps = {
302
+ name: cmsModuleName,
303
+ path: cmsModulePath
304
+ };
305
+ if (cmsModuleLabel) {
306
+ cmsModuleProps.label = cmsModuleLabel;
307
+ }
308
+ if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
309
+ ctx.error(
310
+ new Error(
311
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
312
+ )
313
+ );
314
+ }
315
+ contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
316
+ }
317
+ if (t.isJSXIdentifier(path4.node.name, {
318
+ name: dndAreaComponentLocalImportName
319
+ })) {
320
+ let dndAreaName;
321
+ for (const prop of path4.node.attributes) {
322
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
323
+ dndAreaName = prop.value.value;
324
+ continue;
325
+ }
326
+ ctx.error(
327
+ new Error(
328
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
329
+ )
330
+ );
331
+ }
332
+ const dndArea = {
333
+ name: dndAreaName
334
+ };
335
+ if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
336
+ ctx.error(
337
+ new Error(
338
+ `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
339
+ )
340
+ );
341
+ }
342
+ contentDescriptors.dndAreas[dndArea.name] = dndArea;
343
+ }
344
+ }
345
+ });
346
+ return contentDescriptors;
347
+ }
348
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
349
+ if (Object.hasOwn(result, moduleId)) {
350
+ return result[moduleId];
351
+ }
352
+ const moduleInfo = ctx.getModuleInfo(moduleId);
353
+ let entryPointContentDescriptors = null;
354
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
355
+ entryPointContentDescriptors = {
356
+ ...entryPointContentDescriptors,
357
+ ...moduleInfo.meta[PLUGIN_NAME]
358
+ };
359
+ }
360
+ for (const importedId of [
361
+ ...moduleInfo.importedIds,
362
+ ...moduleInfo.dynamicallyImportedIds
363
+ ]) {
364
+ if (processed.has(importedId)) {
365
+ continue;
366
+ }
367
+ const importedResult = findCmsModuleUsages(
368
+ ctx,
369
+ importedId,
370
+ processed,
371
+ result
372
+ );
373
+ if (importedResult) {
374
+ entryPointContentDescriptors = {
375
+ ...entryPointContentDescriptors,
376
+ ...importedResult
377
+ };
378
+ }
379
+ }
380
+ if (entryPointContentDescriptors) {
381
+ result[moduleId] = entryPointContentDescriptors;
382
+ }
383
+ processed.add(moduleId);
384
+ return entryPointContentDescriptors;
385
+ }
386
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
387
+ processedIslands.add(moduleId);
388
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
389
+ return islandModuleResults[moduleId];
390
+ }
391
+ const moduleInfo = ctx.getModuleInfo(moduleId);
392
+ let resultForModuleId = {};
393
+ if (moduleInfo.id.endsWith("?client-entry")) {
394
+ const mergedDataDependencies = findCmsModuleUsages(
395
+ ctx,
396
+ moduleInfo.id,
397
+ processed,
398
+ results
399
+ );
400
+ if (mergedDataDependencies) {
401
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
402
+ }
403
+ }
404
+ for (const importedId of [
405
+ ...moduleInfo.importedIds,
406
+ ...moduleInfo.dynamicallyImportedIds
407
+ ]) {
408
+ if (processedIslands.has(importedId)) {
409
+ continue;
410
+ }
411
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
412
+ ctx,
413
+ importedId,
414
+ processedIslands,
415
+ islandModuleResults,
416
+ processed,
417
+ results
418
+ );
419
+ if (importerCmsModuleUsageResult) {
420
+ resultForModuleId = {
421
+ ...resultForModuleId,
422
+ ...importerCmsModuleUsageResult
423
+ };
424
+ }
425
+ }
426
+ if (Object.keys(resultForModuleId).length > 0) {
427
+ islandModuleResults[moduleId] = resultForModuleId;
428
+ return resultForModuleId;
429
+ }
430
+ return null;
431
+ }
432
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
433
+ return Object.fromEntries(
434
+ Object.entries(entryPointCmsModuleMap).filter(
435
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
436
+ )
437
+ );
438
+ }
439
+ var {
440
+ createServerRenderContextV2: createServerRenderContextV22,
441
+ createServerRenderContext: createServerRenderContext2,
442
+ renderServerSidePropsWithAsyncLocalStoreContext
443
+ } = cmsComponents;
444
+
445
+ // src/createViteDevServer.ts
446
+ import { default as mkcert } from "vite-plugin-mkcert";
447
+ import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
448
+
449
+ // src/plugins/devSecretsPlugin.ts
450
+ function devSecretsPlugin(secretNames = []) {
451
+ return {
452
+ name: "dev-secrets",
453
+ config: () => {
454
+ return {
455
+ define: {
456
+ "import.meta.env.secretNames": secretNames
457
+ }
458
+ };
459
+ }
460
+ };
461
+ }
462
+
463
+ // src/plugins/cmsComponentsShimPlugin.ts
464
+ function cmsComponentsShimPlugin() {
465
+ return {
466
+ name: "cms-components-shim",
467
+ resolveId(id) {
468
+ if (id === "@hubspot/cms-components" || id.startsWith("@hubspot/cms-components/")) {
469
+ return `\0${id}`;
470
+ }
471
+ return null;
472
+ },
473
+ load(id) {
474
+ if (id === "\0@hubspot/cms-components") {
475
+ return `
476
+ export const HSEnvironment = {};
477
+ export const Hublet = {};
478
+ export const createEmptyServerRenderContext = () => ({});
479
+ export const buildStaticEnvConfig = () => ({});
480
+ export const initConfigSingletonFromJSON = () => ({});
481
+ export default {};
482
+ `;
483
+ }
484
+ if (id === "\0@hubspot/cms-components/config") {
485
+ return `
486
+ export const EnvironmentConfig = {};
487
+ export const initConfigSingletonFromJSON = () => ({});
488
+ export default {};
489
+ `;
490
+ }
491
+ if (id === "\0@hubspot/cms-components/fields") {
492
+ return `
493
+ export const Field = {};
494
+ export const traverseFieldsJSON = () => ({});
495
+ export default {};
496
+ `;
497
+ }
498
+ if (id.startsWith("\0@hubspot/cms-components/")) {
499
+ return "export default {};";
500
+ }
501
+ return null;
502
+ }
503
+ };
504
+ }
505
+
506
+ // src/plugins/hsStaticAssetPlugin.ts
507
+ import { createProxyMiddleware } from "http-proxy-middleware";
508
+ function hsStaticAssetPlugin() {
509
+ return {
510
+ name: "hsstatic-assets-plugin",
511
+ enforce: "pre",
512
+ configureServer(server) {
513
+ return () => {
514
+ const getDomainInfo = (req) => {
515
+ const { authedPortalId, authedHublet, sslEnabled, authedEnv } = req.app.locals;
516
+ const env = authedEnv === "qa" ? "qa" : "";
517
+ const previewDomain = `${authedPortalId}.hubspotpreview${env}-${authedHublet}.com`;
518
+ const protocol = sslEnabled ? "https" : "http";
519
+ return { previewDomain, protocol };
520
+ };
521
+ server.middlewares.use(
522
+ createProxyMiddleware(
523
+ (__pathname, req) => {
524
+ var _a;
525
+ if (!((_a = req.url) == null ? void 0 : _a.match("^/hs/hsstatic/.*")))
526
+ return false;
527
+ const { authedPortalId, authedHublet, authedEnv } = req.app.locals;
528
+ return !!(authedPortalId && authedHublet && authedEnv);
529
+ },
530
+ {
531
+ changeOrigin: true,
532
+ secure: false,
533
+ xfwd: true,
534
+ logLevel: "silent",
535
+ // This is a placeholder target that gets overridden by the router
536
+ // but is a required parameter for initialization
537
+ target: "https://hubspot.com",
538
+ router: (req) => {
539
+ const { previewDomain, protocol } = getDomainInfo(req);
540
+ return `${protocol}://${previewDomain}`;
541
+ },
542
+ onProxyReq: (proxyReq, req, __res) => {
543
+ const { previewDomain, protocol } = getDomainInfo(req);
544
+ proxyReq.setHeader("X-Forwarded-Proto", protocol);
545
+ proxyReq.setHeader("host", previewDomain);
546
+ proxyReq.setHeader(
547
+ "referer",
548
+ `${protocol}://${previewDomain}/content-rendering/v1/public/_hcms/preview/template/multi`
549
+ );
550
+ }
551
+ }
552
+ )
553
+ );
554
+ };
555
+ }
556
+ };
557
+ }
558
+
559
+ // src/createViteDevServer.ts
560
+ import { readFileSync } from "fs";
561
+ import { join } from "path";
562
+ function getPackageJson(packagePath2) {
563
+ return JSON.parse(readFileSync(join(packagePath2, "package.json")).toString());
564
+ }
565
+ function getDepsForPackage(packagePath2) {
566
+ const packageJson = getPackageJson(packagePath2);
567
+ return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];
568
+ }
569
+ function getDepsForPackageIfExists(packagePath2) {
570
+ try {
571
+ return getDepsForPackage(packagePath2);
572
+ } catch (e) {
573
+ console.log("No package.json at ", packagePath2);
574
+ return [];
575
+ }
576
+ }
577
+ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = [], jsRenderingGates, secretNames) {
578
+ const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
579
+ `${proxyDomain}.localhost`,
580
+ `${proxyDomain}.hslocal.net`
581
+ ]).flat();
582
+ if (process.env.VITE_ORIGIN) {
583
+ console.log(`
584
+ Custom origin: ${process.env.VITE_ORIGIN}
585
+ `);
586
+ }
587
+ const origin = process.env.VITE_ORIGIN ?? (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);
588
+ const consumerDeps = getDepsForPackageIfExists(webRoot);
589
+ const isProjectWithReact = consumerDeps.includes("@hubspot/cms-components") || process.env.TRANSLATE_ASSET;
590
+ const componentsShimPlugin = isProjectWithReact ? null : cmsComponentsShimPlugin();
591
+ const ssrAndOptimizeDep = isProjectWithReact ? {
592
+ ssr: {
593
+ // TODO: might need more entries here to get things to resolve through
594
+ // resolveWebRootDepsPlugin
595
+ noExternal: "@hubspot/cms-components"
596
+ },
597
+ resolve: {
598
+ conditions: ["server"],
599
+ dedupe: [
600
+ "react",
601
+ "react-dom",
602
+ "@hubspot/cms-components",
603
+ "styled-jsx"
604
+ ]
605
+ },
606
+ optimizeDeps: {
607
+ include: ["react", "react-dom", "react-dom/client"]
608
+ }
609
+ } : {};
610
+ const require2 = createRequire(import.meta.url);
611
+ const reactAndIslandsPlugins = isProjectWithReact || process.env.VITEST ? [
612
+ react({
613
+ babel: {
614
+ plugins: [
615
+ require2.resolve("babel-plugin-styled-components"),
616
+ require2.resolve("styled-jsx/babel"),
617
+ require2.resolve("babel-plugin-macros")
618
+ ]
619
+ }
620
+ }),
621
+ clientIslandEntryPlugin(),
622
+ resolveIslandPlugin(),
623
+ jsRenderingGates.includes("CMS:JSRenderer:RemoveCjsPlugin") ? null : viteCommonjs(),
624
+ devSecretsPlugin(secretNames),
625
+ noncePlaceholderPlugin()
626
+ ] : [];
627
+ const viteConfig = {
628
+ appType: "custom",
629
+ server: {
630
+ middlewareMode: true,
631
+ host: "hslocal.net",
632
+ origin,
633
+ hmr: {
634
+ protocol: sslEnabled ? "wss" : void 0
635
+ }
636
+ },
637
+ root: webRoot,
638
+ ...ssrAndOptimizeDep,
639
+ plugins: [
640
+ hsStaticAssetPlugin(),
641
+ jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
642
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
643
+ componentsShimPlugin,
644
+ ...reactAndIslandsPlugins
645
+ ],
646
+ css: {
647
+ postcss: webRoot
648
+ },
649
+ envDir: webRoot,
650
+ envPrefix: "HS_",
651
+ define: {
652
+ "process.env": {}
653
+ }
654
+ };
655
+ return createViteServer(viteConfig);
656
+ }
657
+ var createViteDevServer_default = createViteDevServer;
658
+
659
+ // src/lib/packagePath.ts
660
+ import path2 from "path";
661
+ import url from "url";
662
+ import { normalizePath } from "vite";
663
+ function packagePath(metaUrl, projectPath) {
664
+ if (true) {
665
+ return normalizePath(
666
+ path2.resolve(path2.dirname(url.fileURLToPath(metaUrl)), projectPath)
667
+ );
668
+ }
669
+ const parentDirPath = normalizePath(path2.dirname(url.fileURLToPath(metaUrl)));
670
+ const subPath = parentDirPath.replace(/^.+cms-dev-server\/src\//, "");
671
+ const subPathParentDirs = subPath.split("/").map(() => "..");
672
+ return path2.resolve(
673
+ path2.dirname(url.fileURLToPath(metaUrl)),
674
+ path2.join(...subPathParentDirs, projectPath)
675
+ );
676
+ }
677
+
678
+ // src/generateJsonFromJsx.ts
679
+ var internalSsrPath = packagePath(import.meta.url, "internalSsr");
680
+ async function writeFile(filePath, data) {
681
+ try {
682
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2));
683
+ console.log("File has been written successfully to: ", filePath);
684
+ } catch (error) {
685
+ console.error("Error writing to file", { filePath, error });
686
+ }
687
+ }
688
+ async function createJsonFiles(webRoot, data) {
689
+ const fieldsFilePath = path3.join(webRoot, "tmp-fields.json");
690
+ const metaFilePath = path3.join(webRoot, "tmp-meta.json");
691
+ const { fields, meta } = data;
692
+ if (!fields || !meta) {
693
+ throw new Error("Fields or meta exports are missing");
694
+ }
695
+ await writeFile(fieldsFilePath, fields);
696
+ await writeFile(metaFilePath, meta);
697
+ }
698
+ async function transformJsxToJson() {
699
+ const webRoot = process.argv[2];
700
+ if (!webRoot) {
701
+ throw new Error("Path to module directory not provided");
702
+ }
703
+ const moduleFiles = await fs.readdir(webRoot);
704
+ const indexFile = moduleFiles.find((file) => file.includes("index"));
705
+ if (!indexFile) {
706
+ throw new Error(
707
+ 'Index file that contains "fields" and "meta" exports not found'
708
+ );
709
+ }
710
+ const modulePath = path3.join(webRoot, indexFile);
711
+ const absoluteWebRoot = normalizePath2(path3.resolve(process.cwd(), webRoot));
712
+ const viteServer = await createViteDevServer_default(
713
+ absoluteWebRoot,
714
+ 3e3,
715
+ false,
716
+ [],
717
+ [],
718
+ []
719
+ );
720
+ try {
721
+ const { fields, meta } = await viteServer.ssrLoadModule(modulePath);
722
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
723
+ const fieldsJson = renderFieldsToJson(fields, meta.label);
724
+ await createJsonFiles(webRoot, { fields: fieldsJson, meta });
725
+ } catch (error) {
726
+ throw new Error("Failed to generate JSON from JSX: ", error);
727
+ }
728
+ }
729
+ (async () => {
730
+ try {
731
+ await transformJsxToJson();
732
+ process.exit(0);
733
+ } catch (error) {
734
+ console.error("An error occurred:", error);
735
+ process.exit(1);
736
+ }
737
+ })().catch((error) => {
738
+ throw error;
739
+ });
740
+ export {
741
+ createJsonFiles,
742
+ transformJsxToJson,
743
+ writeFile
744
+ };