@hubspot/cms-dev-server 1.2.47 → 1.2.49

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.
@@ -0,0 +1,1324 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/validateFields.ts
4
+ import path3 from "path";
5
+ import fs3 from "fs/promises";
6
+ import { normalizePath as normalizePath2 } from "vite";
7
+
8
+ // src/createViteDevServer.ts
9
+ import { createServer as createViteServer } from "vite";
10
+ import { createRequire } from "module";
11
+ import { default as react } from "@vitejs/plugin-react";
12
+
13
+ // ../cms-js-internal/dist/types-CBGC9bBc.js
14
+ import path from "path";
15
+ import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
16
+ import { join } from "path/posix";
17
+ var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
18
+ var viteRoot;
19
+ var viteCommand;
20
+ function resolveIslandPlugin(islandsSet) {
21
+ return {
22
+ enforce: "pre",
23
+ name: "resolve-islands",
24
+ configResolved(config) {
25
+ viteRoot = config.root;
26
+ viteCommand = config.command;
27
+ },
28
+ load(id) {
29
+ if (id.endsWith("?island") || id.endsWith("?client")) {
30
+ const [idWithNoParam] = id.split("?");
31
+ const islandModuleImportPath = `${idWithNoParam}?client-entry`;
32
+ const componentExtension = path.extname(idWithNoParam);
33
+ const componentFilenameWithNoExtension = path.basename(
34
+ idWithNoParam,
35
+ componentExtension
36
+ );
37
+ const modulePath = path.relative(viteRoot, idWithNoParam);
38
+ const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
39
+ if (islandsSet) {
40
+ islandsSet.add(moduleId);
41
+ }
42
+ return `
43
+ const moduleId = '${moduleId}';
44
+
45
+ const lazyComponent = () => import('${islandModuleImportPath}');
46
+ lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
47
+ lazyComponent.moduleId = moduleId;
48
+
49
+ export default lazyComponent;
50
+ `;
51
+ }
52
+ return null;
53
+ }
54
+ };
55
+ }
56
+ 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";
57
+ var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
58
+ function clientIslandEntryPlugin() {
59
+ return {
60
+ enforce: "pre",
61
+ name: "client-island-entry-plugin",
62
+ resolveId(id) {
63
+ if (id === virtualClientRenderIslandModuleId) {
64
+ return virtualClientRenderIslandModuleId;
65
+ }
66
+ return null;
67
+ },
68
+ load(id) {
69
+ if (id.endsWith("?client-entry")) {
70
+ const [idWithNoParam] = id.split("?");
71
+ return `
72
+ import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
73
+ import Component from '${idWithNoParam}';
74
+
75
+ export function render(island) {
76
+ return clientRenderIsland(island, Component)
77
+ }
78
+
79
+ export default Component;
80
+ `;
81
+ }
82
+ if (id === virtualClientRenderIslandModuleId) {
83
+ return clientRenderIsland;
84
+ }
85
+ return null;
86
+ }
87
+ };
88
+ }
89
+ var getComponentExtension = (componentPath) => {
90
+ const filteredExtensions = COMPONENT_EXTENSIONS.filter(
91
+ (ext) => componentPath.endsWith(ext)
92
+ );
93
+ if (filteredExtensions.length === 1) {
94
+ return filteredExtensions[0];
95
+ }
96
+ return void 0;
97
+ };
98
+ var hasComponentExtension = (componentPath) => {
99
+ return !!getComponentExtension(componentPath);
100
+ };
101
+ var isStorybookStory = (componentPath) => {
102
+ return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
103
+ };
104
+ var removeComponentExtension = (componentPath) => {
105
+ const ext = getComponentExtension(componentPath);
106
+ if (ext == null) {
107
+ return componentPath;
108
+ }
109
+ return componentPath.slice(0, -1 * ext.length);
110
+ };
111
+ var findAllComponentsIn = (webRoot, componentsFolder) => {
112
+ const fullComponentsFolderPath = join(webRoot, componentsFolder);
113
+ const componentsByName = {};
114
+ if (!existsSync(fullComponentsFolderPath)) {
115
+ return componentsByName;
116
+ }
117
+ readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
118
+ const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
119
+ const subdirPath = join(componentsFolder, fileOrFolderName);
120
+ const isDirectory = lstatSync(fullPath).isDirectory();
121
+ if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
122
+ const subdirPathNoExtension = removeComponentExtension(subdirPath);
123
+ componentsByName[subdirPathNoExtension] = subdirPath;
124
+ } else if (isDirectory) {
125
+ for (const potentialExtension of COMPONENT_EXTENSIONS) {
126
+ const potentialIndexModule = join(
127
+ subdirPath,
128
+ `index${potentialExtension}`
129
+ );
130
+ const fullPotentialPath = join(
131
+ fullPath,
132
+ `index${potentialExtension}`
133
+ );
134
+ if (existsSync(fullPotentialPath)) {
135
+ const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
136
+ componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
137
+ break;
138
+ }
139
+ }
140
+ }
141
+ });
142
+ return componentsByName;
143
+ };
144
+ function findAllModulesInRoot(webRoot) {
145
+ const allModuleComponents = findAllComponentsIn(
146
+ webRoot,
147
+ "./components/modules"
148
+ );
149
+ const moduleNames = Object.keys(allModuleComponents).map(
150
+ (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
151
+ );
152
+ const moduleSubpaths = Object.keys(allModuleComponents);
153
+ const moduleExtensions = Object.values(allModuleComponents).map((path22) => {
154
+ if (!path22)
155
+ return "";
156
+ const extension = path22.split(".").pop() || "";
157
+ return extension;
158
+ });
159
+ const moduleNamesWithExtension = Object.values(allModuleComponents).map(
160
+ (path22) => {
161
+ if (!path22)
162
+ return "";
163
+ const file = path22.replace("components/modules/", "");
164
+ return file.includes("/index.") ? file.split("/index.")[0] : file;
165
+ }
166
+ );
167
+ return {
168
+ moduleNames,
169
+ moduleSubpaths,
170
+ moduleNamesWithExtension,
171
+ moduleExtensions
172
+ };
173
+ }
174
+
175
+ // ../cms-js-internal/dist/index.js
176
+ import * as dotProp from "dot-prop";
177
+ import * as parser from "@babel/parser";
178
+ import _traverse from "@babel/traverse";
179
+ import * as t from "@babel/types";
180
+ import * as cmsComponents from "@hubspot/cms-components";
181
+ var { setProperty, getProperty, hasProperty } = dotProp;
182
+ function noncePlaceholderPlugin() {
183
+ const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
184
+ return {
185
+ name: "hs-nonce-placeholder",
186
+ enforce: "post",
187
+ apply() {
188
+ return HS_DEPLOYED;
189
+ },
190
+ transformIndexHtml(html) {
191
+ const regex = /<(style|script|link) (.*)>/gi;
192
+ const replacer = (_, p1, p2) => {
193
+ if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
194
+ p1 === "link" && p2.includes('rel="stylesheet"')) {
195
+ const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
196
+ p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
197
+ }
198
+ return `<${p1} ${p2}>`;
199
+ };
200
+ return html.replace(regex, replacer);
201
+ }
202
+ };
203
+ }
204
+ var traverse = _traverse.default;
205
+ var CMS_MODULE_COMPONENT_NAME = "Module";
206
+ var DND_AREA_COMPONENT_NAME = "DndArea";
207
+ var PLUGIN_NAME = "findCmsModules";
208
+ function findCmsModules(buildContentDescriptors = {}) {
209
+ let config;
210
+ return {
211
+ enforce: "pre",
212
+ name: "findCmsModules",
213
+ configResolved(resolvedConfig) {
214
+ config = resolvedConfig;
215
+ },
216
+ transform(code, id) {
217
+ const moduleInfo = this.getModuleInfo(id);
218
+ if (!shouldAnalyzeModule(config, moduleInfo, code))
219
+ return null;
220
+ const contentDescriptors = analyzeSourceCodeUsages(
221
+ this,
222
+ moduleInfo,
223
+ config,
224
+ code
225
+ );
226
+ if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
227
+ return {
228
+ meta: {
229
+ findCmsModules: contentDescriptors
230
+ }
231
+ };
232
+ }
233
+ },
234
+ buildEnd(error) {
235
+ if (error)
236
+ throw error;
237
+ const entryPoints = getEntryPoints(this, config);
238
+ const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
239
+ this,
240
+ entryPoints
241
+ );
242
+ const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
243
+ config,
244
+ entryPointCmsModuleMap
245
+ );
246
+ const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
247
+ this,
248
+ entryPoints
249
+ );
250
+ const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
251
+ config,
252
+ entryPointIslandCmsModuleMap
253
+ );
254
+ if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
255
+ this.error(`
256
+ Error: <Module /> cannot be used within <Island />
257
+ Found invalid usages:
258
+ ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
259
+ `);
260
+ }
261
+ const modulesWithinModules = filterEntryPointsToModules(
262
+ relativeEntryPointCmsModuleMap
263
+ );
264
+ if (Object.keys(modulesWithinModules).length > 0) {
265
+ this.error(`
266
+ Error: <Module /> can only be used in React Partials
267
+ Found invalid usages:
268
+ ${JSON.stringify(modulesWithinModules, null, 2)}
269
+ `);
270
+ }
271
+ Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
272
+ }
273
+ };
274
+ }
275
+ function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
276
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
277
+ ([entryPointPath, cmsModules]) => {
278
+ return [toRelativePath(config, entryPointPath), cmsModules];
279
+ }
280
+ );
281
+ return Object.fromEntries(relativeEntries);
282
+ }
283
+ function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
284
+ const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
285
+ ([entryPointPath, islandContentDescriptors]) => {
286
+ const islandCmsModuleUsage = Object.fromEntries(
287
+ Object.entries(islandContentDescriptors).map(
288
+ ([islandPath, contentDescriptors]) => {
289
+ return [
290
+ toRelativePath(config, islandPath).replace("?client-entry", ""),
291
+ contentDescriptors
292
+ ];
293
+ }
294
+ )
295
+ );
296
+ return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
297
+ }
298
+ );
299
+ return Object.fromEntries(relativeEntries);
300
+ }
301
+ function toRelativePath(config, path4) {
302
+ return path4.replace(`${config.root}/`, "");
303
+ }
304
+ function shouldAnalyzeModule(config, moduleInfo, code) {
305
+ const [fileId, __] = moduleInfo.id.split("?");
306
+ const isExternal = config.command !== "serve" && moduleInfo.isExternal;
307
+ return (
308
+ // analyze customer code only
309
+ !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
310
+ (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
311
+ );
312
+ }
313
+ function getEntryPoints(ctx, config) {
314
+ return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
315
+ }
316
+ function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
317
+ const entryPointCmsModuleUsage = {};
318
+ for (const entryPoint of entryPoints) {
319
+ const result = findCmsModuleUsages(ctx, entryPoint.id);
320
+ if (result) {
321
+ entryPointCmsModuleUsage[entryPoint.id] = result;
322
+ }
323
+ }
324
+ return entryPointCmsModuleUsage;
325
+ }
326
+ function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
327
+ const entryPointIslandsCmsModuleMap = {};
328
+ for (const entryPoint of entryPoints) {
329
+ const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
330
+ if (result) {
331
+ entryPointIslandsCmsModuleMap[entryPoint.id] = result;
332
+ }
333
+ }
334
+ return entryPointIslandsCmsModuleMap;
335
+ }
336
+ function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
337
+ const sourceAst = parser.parse(code, {
338
+ sourceType: "module",
339
+ plugins: ["jsx", "typescript"]
340
+ });
341
+ const contentDescriptors = { modules: {}, dndAreas: {} };
342
+ let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
343
+ let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
344
+ traverse(sourceAst, {
345
+ ImportDeclaration(path4) {
346
+ if (t.isStringLiteral(path4.node.source, {
347
+ value: "@hubspot/cms-components"
348
+ })) {
349
+ for (const specifier of path4.node.specifiers) {
350
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
351
+ name: CMS_MODULE_COMPONENT_NAME
352
+ })) {
353
+ moduleComponentLocalImportName = specifier.local.name;
354
+ }
355
+ if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
356
+ name: DND_AREA_COMPONENT_NAME
357
+ })) {
358
+ dndAreaComponentLocalImportName = specifier.local.name;
359
+ }
360
+ }
361
+ }
362
+ },
363
+ JSXOpeningElement(path4) {
364
+ if (t.isJSXIdentifier(path4.node.name, {
365
+ name: moduleComponentLocalImportName
366
+ })) {
367
+ let cmsModuleName;
368
+ let cmsModulePath;
369
+ let cmsModuleLabel;
370
+ for (const prop of path4.node.attributes) {
371
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
372
+ cmsModuleName = prop.value.value;
373
+ continue;
374
+ }
375
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
376
+ cmsModulePath = prop.value.value;
377
+ continue;
378
+ }
379
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
380
+ cmsModuleLabel = prop.value.value;
381
+ continue;
382
+ }
383
+ ctx.error(
384
+ new Error(
385
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
386
+ )
387
+ );
388
+ }
389
+ const cmsModuleProps = {
390
+ name: cmsModuleName,
391
+ path: cmsModulePath
392
+ };
393
+ if (cmsModuleLabel) {
394
+ cmsModuleProps.label = cmsModuleLabel;
395
+ }
396
+ if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
397
+ ctx.error(
398
+ new Error(
399
+ `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
400
+ )
401
+ );
402
+ }
403
+ contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
404
+ }
405
+ if (t.isJSXIdentifier(path4.node.name, {
406
+ name: dndAreaComponentLocalImportName
407
+ })) {
408
+ let dndAreaName;
409
+ for (const prop of path4.node.attributes) {
410
+ if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
411
+ dndAreaName = prop.value.value;
412
+ continue;
413
+ }
414
+ ctx.error(
415
+ new Error(
416
+ `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
417
+ )
418
+ );
419
+ }
420
+ const dndArea = {
421
+ name: dndAreaName
422
+ };
423
+ if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
424
+ ctx.error(
425
+ new Error(
426
+ `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
427
+ )
428
+ );
429
+ }
430
+ contentDescriptors.dndAreas[dndArea.name] = dndArea;
431
+ }
432
+ }
433
+ });
434
+ return contentDescriptors;
435
+ }
436
+ function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
437
+ if (Object.hasOwn(result, moduleId)) {
438
+ return result[moduleId];
439
+ }
440
+ const moduleInfo = ctx.getModuleInfo(moduleId);
441
+ let entryPointContentDescriptors = null;
442
+ if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
443
+ entryPointContentDescriptors = {
444
+ ...entryPointContentDescriptors,
445
+ ...moduleInfo.meta[PLUGIN_NAME]
446
+ };
447
+ }
448
+ for (const importedId of [
449
+ ...moduleInfo.importedIds,
450
+ ...moduleInfo.dynamicallyImportedIds
451
+ ]) {
452
+ if (processed.has(importedId)) {
453
+ continue;
454
+ }
455
+ const importedResult = findCmsModuleUsages(
456
+ ctx,
457
+ importedId,
458
+ processed,
459
+ result
460
+ );
461
+ if (importedResult) {
462
+ entryPointContentDescriptors = {
463
+ ...entryPointContentDescriptors,
464
+ ...importedResult
465
+ };
466
+ }
467
+ }
468
+ if (entryPointContentDescriptors) {
469
+ result[moduleId] = entryPointContentDescriptors;
470
+ }
471
+ processed.add(moduleId);
472
+ return entryPointContentDescriptors;
473
+ }
474
+ function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
475
+ processedIslands.add(moduleId);
476
+ if (Object.hasOwn(islandModuleResults, moduleId)) {
477
+ return islandModuleResults[moduleId];
478
+ }
479
+ const moduleInfo = ctx.getModuleInfo(moduleId);
480
+ let resultForModuleId = {};
481
+ if (moduleInfo.id.endsWith("?client-entry")) {
482
+ const mergedDataDependencies = findCmsModuleUsages(
483
+ ctx,
484
+ moduleInfo.id,
485
+ processed,
486
+ results
487
+ );
488
+ if (mergedDataDependencies) {
489
+ resultForModuleId[moduleInfo.id] = mergedDataDependencies;
490
+ }
491
+ }
492
+ for (const importedId of [
493
+ ...moduleInfo.importedIds,
494
+ ...moduleInfo.dynamicallyImportedIds
495
+ ]) {
496
+ if (processedIslands.has(importedId)) {
497
+ continue;
498
+ }
499
+ const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
500
+ ctx,
501
+ importedId,
502
+ processedIslands,
503
+ islandModuleResults,
504
+ processed,
505
+ results
506
+ );
507
+ if (importerCmsModuleUsageResult) {
508
+ resultForModuleId = {
509
+ ...resultForModuleId,
510
+ ...importerCmsModuleUsageResult
511
+ };
512
+ }
513
+ }
514
+ if (Object.keys(resultForModuleId).length > 0) {
515
+ islandModuleResults[moduleId] = resultForModuleId;
516
+ return resultForModuleId;
517
+ }
518
+ return null;
519
+ }
520
+ function filterEntryPointsToModules(entryPointCmsModuleMap) {
521
+ return Object.fromEntries(
522
+ Object.entries(entryPointCmsModuleMap).filter(
523
+ ([entryPoint]) => entryPoint.startsWith("components/modules/")
524
+ )
525
+ );
526
+ }
527
+ var {
528
+ createServerRenderContextV2: createServerRenderContextV22,
529
+ createServerRenderContext: createServerRenderContext2,
530
+ renderServerSidePropsWithAsyncLocalStoreContext
531
+ } = cmsComponents;
532
+
533
+ // src/createViteDevServer.ts
534
+ import { default as mkcert } from "vite-plugin-mkcert";
535
+ import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
536
+
537
+ // src/plugins/devSecretsPlugin.ts
538
+ function devSecretsPlugin(secretNames = []) {
539
+ return {
540
+ name: "dev-secrets",
541
+ config: () => {
542
+ return {
543
+ define: {
544
+ "import.meta.env.secretNames": secretNames
545
+ }
546
+ };
547
+ }
548
+ };
549
+ }
550
+
551
+ // src/plugins/cmsComponentsShimPlugin.ts
552
+ function cmsComponentsShimPlugin() {
553
+ return {
554
+ name: "cms-components-shim",
555
+ resolveId(id) {
556
+ if (id === "@hubspot/cms-components" || id.startsWith("@hubspot/cms-components/")) {
557
+ return `\0${id}`;
558
+ }
559
+ return null;
560
+ },
561
+ load(id) {
562
+ if (id === "\0@hubspot/cms-components") {
563
+ return `
564
+ export const HSEnvironment = {};
565
+ export const Hublet = {};
566
+ export const createEmptyServerRenderContext = () => ({});
567
+ export const buildStaticEnvConfig = () => ({});
568
+ export const initConfigSingletonFromJSON = () => ({});
569
+ export default {};
570
+ `;
571
+ }
572
+ if (id === "\0@hubspot/cms-components/config") {
573
+ return `
574
+ export const EnvironmentConfig = {};
575
+ export const initConfigSingletonFromJSON = () => ({});
576
+ export default {};
577
+ `;
578
+ }
579
+ if (id === "\0@hubspot/cms-components/fields") {
580
+ return `
581
+ export const Field = {};
582
+ export const traverseFieldsJSON = () => ({});
583
+ export default {};
584
+ `;
585
+ }
586
+ if (id.startsWith("\0@hubspot/cms-components/")) {
587
+ return "export default {};";
588
+ }
589
+ return null;
590
+ }
591
+ };
592
+ }
593
+
594
+ // src/plugins/hsStaticAssetPlugin.ts
595
+ import { createProxyMiddleware } from "http-proxy-middleware";
596
+ function hsStaticAssetPlugin() {
597
+ return {
598
+ name: "hsstatic-assets-plugin",
599
+ enforce: "pre",
600
+ configureServer(server) {
601
+ return () => {
602
+ const getDomainInfo = (req) => {
603
+ const { authedPortalId, authedHublet, sslEnabled, authedEnv } = req.app.locals;
604
+ const env = authedEnv === "qa" ? "qa" : "";
605
+ const previewDomain = `${authedPortalId}.hubspotpreview${env}-${authedHublet}.com`;
606
+ const protocol = sslEnabled ? "https" : "http";
607
+ return { previewDomain, protocol };
608
+ };
609
+ server.middlewares.use(
610
+ createProxyMiddleware(
611
+ (__pathname, req) => {
612
+ var _a;
613
+ if (!((_a = req.url) == null ? void 0 : _a.match("^/hs/hsstatic/.*")))
614
+ return false;
615
+ const { authedPortalId, authedHublet, authedEnv } = req.app.locals;
616
+ return !!(authedPortalId && authedHublet && authedEnv);
617
+ },
618
+ {
619
+ changeOrigin: true,
620
+ secure: false,
621
+ xfwd: true,
622
+ logLevel: "silent",
623
+ // This is a placeholder target that gets overridden by the router
624
+ // but is a required parameter for initialization
625
+ target: "https://hubspot.com",
626
+ router: (req) => {
627
+ const { previewDomain, protocol } = getDomainInfo(req);
628
+ return `${protocol}://${previewDomain}`;
629
+ },
630
+ onProxyReq: (proxyReq, req, __res) => {
631
+ const { previewDomain, protocol } = getDomainInfo(req);
632
+ proxyReq.setHeader("X-Forwarded-Proto", protocol);
633
+ proxyReq.setHeader("host", previewDomain);
634
+ proxyReq.setHeader(
635
+ "referer",
636
+ `${protocol}://${previewDomain}/content-rendering/v1/public/_hcms/preview/template/multi`
637
+ );
638
+ }
639
+ }
640
+ )
641
+ );
642
+ };
643
+ }
644
+ };
645
+ }
646
+
647
+ // src/createViteDevServer.ts
648
+ import { readFileSync as readFileSync2 } from "fs";
649
+ import { join as join2 } from "path";
650
+ function getPackageJson(packagePath2) {
651
+ return JSON.parse(readFileSync2(join2(packagePath2, "package.json")).toString());
652
+ }
653
+ function getDepsForPackage(packagePath2) {
654
+ const packageJson = getPackageJson(packagePath2);
655
+ return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];
656
+ }
657
+ function getDepsForPackageIfExists(packagePath2) {
658
+ try {
659
+ return getDepsForPackage(packagePath2);
660
+ } catch (e) {
661
+ console.log("No package.json at ", packagePath2);
662
+ return [];
663
+ }
664
+ }
665
+ async function createViteDevServer(webRoot, port, sslEnabled, domainsToProxy = [], jsRenderingGates, secretNames) {
666
+ const additionalMkcertHosts = domainsToProxy.map((proxyDomain) => [
667
+ `${proxyDomain}.localhost`,
668
+ `${proxyDomain}.hslocal.net`
669
+ ]).flat();
670
+ if (process.env.VITE_ORIGIN) {
671
+ console.log(`
672
+ Custom origin: ${process.env.VITE_ORIGIN}
673
+ `);
674
+ }
675
+ const origin = process.env.VITE_ORIGIN ?? (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);
676
+ const consumerDeps = getDepsForPackageIfExists(webRoot);
677
+ const isProjectWithReact = consumerDeps.includes("@hubspot/cms-components") || process.env.TRANSLATE_ASSET;
678
+ const componentsShimPlugin = isProjectWithReact ? null : cmsComponentsShimPlugin();
679
+ const ssrAndOptimizeDep = isProjectWithReact ? {
680
+ ssr: {
681
+ // TODO: might need more entries here to get things to resolve through
682
+ // resolveWebRootDepsPlugin
683
+ noExternal: "@hubspot/cms-components"
684
+ },
685
+ resolve: {
686
+ conditions: ["server"],
687
+ dedupe: [
688
+ "react",
689
+ "react-dom",
690
+ "@hubspot/cms-components",
691
+ "styled-jsx"
692
+ ]
693
+ },
694
+ optimizeDeps: {
695
+ include: ["react", "react-dom", "react-dom/client"]
696
+ }
697
+ } : {};
698
+ const require2 = createRequire(import.meta.url);
699
+ const reactAndIslandsPlugins = isProjectWithReact || process.env.VITEST ? [
700
+ react({
701
+ babel: {
702
+ plugins: [
703
+ require2.resolve("babel-plugin-styled-components"),
704
+ require2.resolve("styled-jsx/babel"),
705
+ require2.resolve("babel-plugin-macros")
706
+ ]
707
+ }
708
+ }),
709
+ clientIslandEntryPlugin(),
710
+ resolveIslandPlugin(),
711
+ viteCommonjs(),
712
+ devSecretsPlugin(secretNames),
713
+ noncePlaceholderPlugin()
714
+ ] : [];
715
+ const viteConfig = {
716
+ appType: "custom",
717
+ server: {
718
+ middlewareMode: true,
719
+ host: "hslocal.net",
720
+ origin,
721
+ hmr: {
722
+ protocol: sslEnabled ? "wss" : void 0
723
+ },
724
+ allowedHosts: ["localhost", "hslocal.net", ...additionalMkcertHosts]
725
+ },
726
+ root: webRoot,
727
+ ...ssrAndOptimizeDep,
728
+ plugins: [
729
+ hsStaticAssetPlugin(),
730
+ jsRenderingGates.includes("CMS:JSRenderer:AnalyzeCmsModules") ? findCmsModules() : null,
731
+ sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,
732
+ componentsShimPlugin,
733
+ ...reactAndIslandsPlugins
734
+ ],
735
+ css: {
736
+ postcss: webRoot
737
+ },
738
+ envDir: webRoot,
739
+ envPrefix: "HS_",
740
+ define: {
741
+ "process.env": {}
742
+ }
743
+ };
744
+ return createViteServer(viteConfig);
745
+ }
746
+ var createViteDevServer_default = createViteDevServer;
747
+
748
+ // src/lib/renderModuleFieldsJson.ts
749
+ import { join as joinPosix } from "path/posix";
750
+
751
+ // src/lib/packagePath.ts
752
+ import path2 from "path";
753
+ import url from "url";
754
+ import { normalizePath } from "vite";
755
+ function packagePath(metaUrl, projectPath) {
756
+ if (true) {
757
+ return normalizePath(
758
+ path2.resolve(path2.dirname(url.fileURLToPath(metaUrl)), projectPath)
759
+ );
760
+ }
761
+ const parentDirPath = normalizePath(path2.dirname(url.fileURLToPath(metaUrl)));
762
+ const subPath = parentDirPath.replace(/^.+cms-dev-server\/src\//, "");
763
+ const subPathParentDirs = subPath.split("/").map(() => "..");
764
+ return path2.resolve(
765
+ path2.dirname(url.fileURLToPath(metaUrl)),
766
+ path2.join(...subPathParentDirs, projectPath)
767
+ );
768
+ }
769
+
770
+ // src/lib/renderModuleFieldsJson.ts
771
+ var lookForModuleInFolder = async (modulePath, viteServer) => {
772
+ let componentModule;
773
+ const insideFolderPath = joinPosix(modulePath, "index");
774
+ try {
775
+ componentModule = await viteServer.ssrLoadModule(insideFolderPath);
776
+ } catch (e) {
777
+ if (!e.message.includes("Failed to load url")) {
778
+ throw e;
779
+ }
780
+ }
781
+ return [componentModule, insideFolderPath];
782
+ };
783
+ async function renderModuleFieldsJson(viteServer, requestedModulePath) {
784
+ let componentModule;
785
+ try {
786
+ if (!hasComponentExtension(requestedModulePath)) {
787
+ [componentModule] = await lookForModuleInFolder(
788
+ requestedModulePath,
789
+ viteServer
790
+ );
791
+ }
792
+ if (!componentModule) {
793
+ componentModule = await viteServer.ssrLoadModule(requestedModulePath);
794
+ }
795
+ } catch (error) {
796
+ throw new Error(
797
+ `Failed to load module ${requestedModulePath}: ${error.message}`
798
+ );
799
+ }
800
+ if (!componentModule) {
801
+ throw new Error(`Couldn't find module: ${requestedModulePath}`);
802
+ }
803
+ const internalSsrPath = packagePath(import.meta.url, "internalSsr");
804
+ const { renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath);
805
+ const fieldsJson = renderFieldsToJson(
806
+ componentModule.fields,
807
+ requestedModulePath
808
+ );
809
+ return fieldsJson;
810
+ }
811
+ var renderModuleFieldsJson_default = renderModuleFieldsJson;
812
+
813
+ // ../cms-js-internal/dist/buildFieldsTypes.js
814
+ import { writeFileSync } from "fs";
815
+ import ts from "typescript";
816
+ var fieldTypeNameByType = {
817
+ alignment: "AlignmentFieldType",
818
+ audioplayer: "AudioFieldType",
819
+ backgroundimage: "BackgroundImageFieldType",
820
+ blog: "BlogFieldType",
821
+ boolean: "BooleanFieldType",
822
+ border: "BorderFieldType",
823
+ choice: "ChoiceFieldType",
824
+ color: "ColorFieldType",
825
+ crmobject: "CrmObjectFieldType",
826
+ cta: "CtaFieldType",
827
+ date: "DateFieldType",
828
+ datetime: "DateTimeFieldType",
829
+ email: "EmailFieldType",
830
+ embed: "EmbedFieldType",
831
+ file: "FileFieldType",
832
+ followupemail: "FollowUpEmailFieldType",
833
+ font: "FontFieldType",
834
+ form: "FormFieldType",
835
+ gradient: "GradientFieldType",
836
+ group: "GroupFieldType",
837
+ html: "HtmlFieldType",
838
+ hubdbrow: "HubDbRowFieldType",
839
+ hubdbtable: "HubDbTableFieldType",
840
+ hubl: "HublFieldType",
841
+ icon: "IconFieldType",
842
+ image: "ImageFieldType",
843
+ link: "LinkFieldType",
844
+ logo: "LogoFieldType",
845
+ meeting: "MeetingFieldType",
846
+ menu: "MenuFieldType",
847
+ number: "NumberFieldType",
848
+ page: "PageFieldType",
849
+ payment: "PaymentFieldType",
850
+ podcast: "PodcastFieldType",
851
+ richtext: "RichTextFieldType",
852
+ salesforcecampaign: "SfdcCamapaignFieldType",
853
+ simplemenu: "SimpleMenuFieldType",
854
+ spacing: "SpacingFieldType",
855
+ survey: "SurveyFieldType",
856
+ tag: "TagFieldType",
857
+ textalignment: "TextAlignmentFieldType",
858
+ text: "TextFieldType",
859
+ url: "UrlFieldType",
860
+ videoplayer: "VideoFieldType",
861
+ workflow: "WorkflowFieldType"
862
+ };
863
+ function getFieldEntries(fields) {
864
+ if (!Array.isArray(fields)) {
865
+ return void 0;
866
+ }
867
+ return fields.filter((field) => field.name && field.type).map((field) => {
868
+ const { name, type } = field;
869
+ const fieldType = fieldTypeNameByType[type];
870
+ if (!fieldType) {
871
+ return void 0;
872
+ }
873
+ const entry = {
874
+ type: fieldType,
875
+ name,
876
+ isRepeater: "occurrence" in field,
877
+ isRequired: !!field.required,
878
+ choices: (
879
+ // Choices are pair [value, label] but only the value is printed to the page, so flatten it.
880
+ "choices" in field ? field.choices.map(([value, label]) => value) : void 0
881
+ ),
882
+ children: []
883
+ };
884
+ if (fieldType === "GroupFieldType" && "children" in field) {
885
+ const children = getFieldEntries(field.children);
886
+ return { ...entry, children };
887
+ }
888
+ return entry;
889
+ }).filter((entry) => entry !== void 0);
890
+ }
891
+ var INVALID_IMPORTS = ["ChoiceFieldType", "GroupFieldType"];
892
+ var FIELD_GROUP_TYPE = "FieldGroupWithChildren";
893
+ var REPEATER_GROUP_TYPE = "RepeaterGroup";
894
+ var REQUIRED_TYPE = "RequiredField";
895
+ var DEFAULT_VALUES_TYPE = "DefaultValues";
896
+ var CMS_COMPONENTS = "@hubspot/cms-components";
897
+ var CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;
898
+ var AUTO_GEN_COMMENT = "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.";
899
+ var createPropertySignature = (identifier, type, hasQuestionToken = false) => ts.factory.createPropertySignature(
900
+ [],
901
+ identifier,
902
+ hasQuestionToken ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0,
903
+ type
904
+ );
905
+ var createUnionTypeFromArray = (values) => ts.factory.createUnionTypeNode(
906
+ values.map(
907
+ (value) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value))
908
+ )
909
+ );
910
+ var buildTypeFromField = (field, additionalNode) => {
911
+ const imports = [field.type];
912
+ const identifier = ts.factory.createIdentifier(field.name);
913
+ const baseType = ts.factory.createTypeReferenceNode(field.type);
914
+ const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [
915
+ baseType
916
+ ]);
917
+ let finalType = field.isRequired ? requiredType : baseType;
918
+ if (field.choices) {
919
+ finalType = createUnionTypeFromArray(field.choices);
920
+ }
921
+ if (field.isRequired) {
922
+ imports.push(REQUIRED_TYPE);
923
+ }
924
+ if (additionalNode) {
925
+ const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);
926
+ const genericType = field.isRepeater ? REPEATER_GROUP_TYPE : FIELD_GROUP_TYPE;
927
+ imports.push(genericType);
928
+ finalType = ts.factory.createTypeReferenceNode(genericType, [typeLiteral]);
929
+ }
930
+ return {
931
+ type: createPropertySignature(
932
+ identifier,
933
+ finalType,
934
+ !field.isRequired && !additionalNode
935
+ ),
936
+ imports
937
+ };
938
+ };
939
+ var filterUnusedImports = (imports, type) => {
940
+ const usedImports = /* @__PURE__ */ new Set();
941
+ const visit = (node) => {
942
+ if (ts.isTypeReferenceNode(node)) {
943
+ const typeName = node.typeName;
944
+ if ("escapedText" in typeName) {
945
+ usedImports.add(typeName.escapedText.toString());
946
+ }
947
+ }
948
+ ts.forEachChild(node, visit);
949
+ };
950
+ visit(type);
951
+ return imports.filter((name) => usedImports.has(name));
952
+ };
953
+ function getImportDeclaration(imports, moduleSpecifier) {
954
+ const importSpecifiers = Array.from(imports).map(
955
+ (importName) => ts.factory.createImportSpecifier(
956
+ true,
957
+ void 0,
958
+ ts.factory.createIdentifier(importName)
959
+ )
960
+ );
961
+ const namedImports = ts.factory.createNamedImports(importSpecifiers);
962
+ return ts.factory.createImportDeclaration(
963
+ [],
964
+ [],
965
+ ts.factory.createImportClause(false, void 0, namedImports),
966
+ ts.factory.createStringLiteral(moduleSpecifier)
967
+ );
968
+ }
969
+ function getFieldTypes(fields) {
970
+ const imports = [];
971
+ const types = fields.map((field) => {
972
+ if (field.children) {
973
+ const childrenResult = getFieldTypes(field.children);
974
+ imports.push(...childrenResult.imports);
975
+ if (childrenResult.types.length) {
976
+ const subType = ts.factory.createTypeLiteralNode(childrenResult.types);
977
+ const { type: type2, imports: newImports2 } = buildTypeFromField(
978
+ field,
979
+ subType
980
+ );
981
+ imports.push(...newImports2);
982
+ return type2;
983
+ }
984
+ }
985
+ const { type, imports: newImports } = buildTypeFromField(field);
986
+ imports.push(...newImports);
987
+ return type;
988
+ });
989
+ const validImports = Array.from(
990
+ new Set(imports.filter((name) => !INVALID_IMPORTS.includes(name)))
991
+ );
992
+ return { types, imports: validImports };
993
+ }
994
+ function constructFinalType(fields, typeName) {
995
+ const { types, imports } = getFieldTypes(fields);
996
+ const baseType = ts.factory.createTypeAliasDeclaration(
997
+ [],
998
+ [],
999
+ "",
1000
+ void 0,
1001
+ ts.factory.createTypeLiteralNode(types)
1002
+ );
1003
+ const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [
1004
+ baseType.type
1005
+ ]);
1006
+ const finalType = ts.factory.createTypeAliasDeclaration(
1007
+ [],
1008
+ [],
1009
+ typeName,
1010
+ void 0,
1011
+ wrappedType
1012
+ );
1013
+ const filteredImports = filterUnusedImports(imports, finalType);
1014
+ const importDeclaration = getImportDeclaration(
1015
+ [...filteredImports, DEFAULT_VALUES_TYPE],
1016
+ CMS_COMPONENTS_FIELD_TYPES
1017
+ );
1018
+ const defaultExport = ts.factory.createExportDefault(
1019
+ ts.factory.createIdentifier(typeName)
1020
+ );
1021
+ return [importDeclaration, finalType, defaultExport];
1022
+ }
1023
+ function writeFieldsType(fields, fileName, typeName) {
1024
+ const entries = getFieldEntries(fields);
1025
+ if (!entries) {
1026
+ return false;
1027
+ }
1028
+ try {
1029
+ const file = ts.createSourceFile(
1030
+ fileName,
1031
+ "",
1032
+ ts.ScriptTarget.ESNext,
1033
+ false,
1034
+ ts.ScriptKind.TS
1035
+ );
1036
+ const printer = ts.createPrinter();
1037
+ const nodes = constructFinalType(entries, typeName);
1038
+ const comments = [
1039
+ AUTO_GEN_COMMENT,
1040
+ "Removing the above comment will disable type generation for this module",
1041
+ "This file was created by @hubspot/cms-dev-server, for more information see https://github.hubspot.com/cms-react/reference/js-modules.html#module-fields"
1042
+ ].map((comment) => `// ${comment}`);
1043
+ const typeResult = nodes.map(
1044
+ (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)
1045
+ );
1046
+ const result = [...comments, ...typeResult].join("\n");
1047
+ writeFileSync(fileName, result);
1048
+ return true;
1049
+ } catch (e) {
1050
+ console.error(e);
1051
+ return false;
1052
+ }
1053
+ }
1054
+
1055
+ // src/lib/watchFieldsUpdates.ts
1056
+ import fs2 from "fs";
1057
+ import readline from "readline";
1058
+ var formatAsTypeName = (str) => {
1059
+ const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, "_")}FieldsType`;
1060
+ const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));
1061
+ return validFirstChar ? typeName : `_${typeName}`;
1062
+ };
1063
+ var fileContainsAutoGenComment = async (filePath) => {
1064
+ if (!fs2.existsSync(filePath))
1065
+ return true;
1066
+ const stream = fs2.createReadStream(filePath);
1067
+ const reader = readline.createInterface({ input: stream });
1068
+ const firstLine = await new Promise(
1069
+ (resolve) => reader.once("line", (line) => resolve(line.trim()))
1070
+ );
1071
+ reader.close();
1072
+ stream.close();
1073
+ return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;
1074
+ };
1075
+
1076
+ // src/lib/renderModule.ts
1077
+ import * as cmsComponents2 from "@hubspot/cms-components";
1078
+ var VALIDATE_FIELDS_ENDPOINT = "/designmanager/v1/modules/validate-fields";
1079
+ var VALIDATE_META_ENDPOINT = "/designmanager/v1/modules/validate-meta";
1080
+ var { filterToModuleDataDepsIncludedIn, getModuleDataDependecyTypeFrom } = cmsComponents2;
1081
+
1082
+ // src/validateFields.ts
1083
+ import { http as hsCliHttp } from "@hubspot/local-dev-lib/http";
1084
+ import { getConfigDefaultAccount } from "@hubspot/local-dev-lib/config";
1085
+ var EDITOR_VERSION_V2 = "2.0";
1086
+ async function generateAndWriteFieldsJson(absoluteModulePath, modulePath, viteServer) {
1087
+ let fieldsJson;
1088
+ try {
1089
+ fieldsJson = await renderModuleFieldsJson_default(viteServer, absoluteModulePath);
1090
+ } catch {
1091
+ return {
1092
+ severity: "FATAL",
1093
+ errorType: "MODULE_BUILD_ERROR",
1094
+ message: `Failed to SSR-load module at ${modulePath}`
1095
+ };
1096
+ }
1097
+ if (!Array.isArray(fieldsJson)) {
1098
+ return {
1099
+ severity: "FATAL",
1100
+ errorType: "INVALID_FIELDS",
1101
+ message: `renderModuleFieldsJson returned non-array for ${modulePath}`
1102
+ };
1103
+ }
1104
+ const fieldsJsonPath = path3.join(absoluteModulePath, "fields.json");
1105
+ await fs3.writeFile(fieldsJsonPath, JSON.stringify(fieldsJson, null, 2));
1106
+ return { fieldsJson, fieldsJsonPath };
1107
+ }
1108
+ async function generateAndWriteFieldsType(absoluteModulePath, modulePath, moduleDir, fieldsJson) {
1109
+ const fieldsTypePath = path3.join(absoluteModulePath, "fields.type.ts");
1110
+ const hasAutoGenComment = await fileContainsAutoGenComment(fieldsTypePath);
1111
+ if (hasAutoGenComment) {
1112
+ const typeName = formatAsTypeName(moduleDir);
1113
+ const didSucceed = writeFieldsType(fieldsJson, fieldsTypePath, typeName);
1114
+ if (!didSucceed) {
1115
+ return {
1116
+ severity: "FATAL",
1117
+ errorType: "TYPE_GEN_ERROR",
1118
+ message: `Failed to generate fields.type.ts for ${modulePath}`
1119
+ };
1120
+ }
1121
+ }
1122
+ return { fieldsTypePath };
1123
+ }
1124
+ async function extractAndValidateFields(fieldsJson, metaJson, modulePath) {
1125
+ if (!metaJson) {
1126
+ return {
1127
+ fieldErrors: [],
1128
+ metaErrors: [
1129
+ {
1130
+ severity: "FATAL",
1131
+ errorType: "MISSING_META",
1132
+ message: `Module does not have a named meta export: ${modulePath}`
1133
+ }
1134
+ ]
1135
+ };
1136
+ }
1137
+ const portalId = getConfigDefaultAccount().accountId;
1138
+ const [fieldsResult, metaResult] = await Promise.allSettled([
1139
+ hsCliHttp.post(portalId, {
1140
+ url: `${VALIDATE_FIELDS_ENDPOINT}?editorVersion=${metaJson.editor_version ?? EDITOR_VERSION_V2}`,
1141
+ data: fieldsJson
1142
+ }),
1143
+ hsCliHttp.post(portalId, {
1144
+ url: VALIDATE_META_ENDPOINT,
1145
+ data: metaJson
1146
+ })
1147
+ ]);
1148
+ const mapErrors = (entities) => entities.filter((e) => e.severity === "FATAL").map((e) => ({
1149
+ severity: e.severity,
1150
+ errorType: e.errorType,
1151
+ message: e.message,
1152
+ fieldPath: e.errorTokens.path[0]
1153
+ }));
1154
+ return {
1155
+ fieldErrors: fieldsResult.status === "fulfilled" ? mapErrors(fieldsResult.value.data) : [
1156
+ {
1157
+ severity: "FATAL",
1158
+ errorType: "API_UNREACHABLE",
1159
+ message: `Field validation API error: ${fieldsResult.reason}`
1160
+ }
1161
+ ],
1162
+ metaErrors: metaResult.status === "fulfilled" ? mapErrors(metaResult.value.data) : [
1163
+ {
1164
+ severity: "FATAL",
1165
+ errorType: "API_UNREACHABLE",
1166
+ message: `Meta validation API error: ${metaResult.reason}`
1167
+ }
1168
+ ]
1169
+ };
1170
+ }
1171
+ async function validateSingleModule(modulePath, absoluteRoot, viteServer) {
1172
+ const absoluteModulePath = path3.resolve(absoluteRoot, modulePath);
1173
+ const moduleDir = path3.basename(modulePath);
1174
+ let files;
1175
+ try {
1176
+ files = await fs3.readdir(absoluteModulePath);
1177
+ } catch {
1178
+ return {
1179
+ fieldsJsonPath: "",
1180
+ fieldsTypePath: "",
1181
+ fieldErrors: [
1182
+ {
1183
+ severity: "FATAL",
1184
+ errorType: "MODULE_NOT_FOUND",
1185
+ message: `Module directory does not exist: ${modulePath}`
1186
+ }
1187
+ ],
1188
+ metaErrors: []
1189
+ };
1190
+ }
1191
+ const indexFile = files.find((f) => f.startsWith("index."));
1192
+ if (!indexFile) {
1193
+ return {
1194
+ fieldsJsonPath: "",
1195
+ fieldsTypePath: "",
1196
+ fieldErrors: [
1197
+ {
1198
+ severity: "FATAL",
1199
+ errorType: "NO_INDEX_FILE",
1200
+ message: `No index file found in ${modulePath}`
1201
+ }
1202
+ ],
1203
+ metaErrors: []
1204
+ };
1205
+ }
1206
+ const jsonResult = await generateAndWriteFieldsJson(
1207
+ absoluteModulePath,
1208
+ modulePath,
1209
+ viteServer
1210
+ );
1211
+ if ("severity" in jsonResult) {
1212
+ return {
1213
+ fieldsJsonPath: "",
1214
+ fieldsTypePath: "",
1215
+ fieldErrors: [jsonResult],
1216
+ metaErrors: []
1217
+ };
1218
+ }
1219
+ const typeResult = await generateAndWriteFieldsType(
1220
+ absoluteModulePath,
1221
+ modulePath,
1222
+ moduleDir,
1223
+ jsonResult.fieldsJson
1224
+ );
1225
+ if ("severity" in typeResult) {
1226
+ return {
1227
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
1228
+ fieldsTypePath: "",
1229
+ fieldErrors: [typeResult],
1230
+ metaErrors: []
1231
+ };
1232
+ }
1233
+ let mod;
1234
+ try {
1235
+ mod = await viteServer.ssrLoadModule(
1236
+ path3.join(absoluteModulePath, indexFile)
1237
+ );
1238
+ } catch {
1239
+ return {
1240
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
1241
+ fieldsTypePath: typeResult.fieldsTypePath,
1242
+ fieldErrors: [
1243
+ {
1244
+ severity: "FATAL",
1245
+ errorType: "MODULE_BUILD_ERROR",
1246
+ message: `Failed to SSR-load module for meta extraction: ${modulePath}`
1247
+ }
1248
+ ],
1249
+ metaErrors: []
1250
+ };
1251
+ }
1252
+ const { fieldErrors, metaErrors } = await extractAndValidateFields(
1253
+ jsonResult.fieldsJson,
1254
+ mod.meta,
1255
+ modulePath
1256
+ );
1257
+ return {
1258
+ fieldsJsonPath: jsonResult.fieldsJsonPath,
1259
+ fieldsTypePath: typeResult.fieldsTypePath,
1260
+ fieldErrors,
1261
+ metaErrors
1262
+ };
1263
+ }
1264
+ async function validateModuleFields(projectRoot, moduleName) {
1265
+ const absoluteRoot = normalizePath2(path3.resolve(process.cwd(), projectRoot));
1266
+ const viteServer = await createViteDevServer_default(
1267
+ absoluteRoot,
1268
+ 3e3,
1269
+ false,
1270
+ [],
1271
+ [],
1272
+ []
1273
+ );
1274
+ try {
1275
+ if (moduleName) {
1276
+ return [
1277
+ await validateSingleModule(
1278
+ `components/modules/${moduleName}`,
1279
+ absoluteRoot,
1280
+ viteServer
1281
+ )
1282
+ ];
1283
+ }
1284
+ const { moduleNames } = findAllModulesInRoot(absoluteRoot);
1285
+ const modulePaths = moduleNames.map(
1286
+ (name) => `components/modules/${name}`
1287
+ );
1288
+ return await Promise.all(
1289
+ modulePaths.map(
1290
+ (mp) => validateSingleModule(mp, absoluteRoot, viteServer)
1291
+ )
1292
+ );
1293
+ } finally {
1294
+ await viteServer.close();
1295
+ }
1296
+ }
1297
+
1298
+ // src/validateFieldsCli.ts
1299
+ function parseCommandArgs() {
1300
+ const projectPath = process.argv[2];
1301
+ const moduleIdx = process.argv.indexOf("--module");
1302
+ const moduleName = moduleIdx !== -1 ? process.argv[moduleIdx + 1] : void 0;
1303
+ if (!projectPath) {
1304
+ console.error("Usage: validate-fields <path> [--module <name>]");
1305
+ process.exit(1);
1306
+ }
1307
+ return { projectPath, moduleName };
1308
+ }
1309
+ (async () => {
1310
+ try {
1311
+ const { projectPath, moduleName } = parseCommandArgs();
1312
+ const results = await validateModuleFields(projectPath, moduleName);
1313
+ console.log(JSON.stringify(results, null, 2));
1314
+ const hasErrors = results.some(
1315
+ (r) => r.fieldErrors.length > 0 || r.metaErrors.length > 0
1316
+ );
1317
+ process.exit(hasErrors ? 1 : 0);
1318
+ } catch (error) {
1319
+ console.error("An error occurred:", error);
1320
+ process.exit(1);
1321
+ }
1322
+ })().catch((error) => {
1323
+ throw error;
1324
+ });