@hubspot/cms-dev-server 0.18.22 → 0.18.23

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 (43) hide show
  1. package/dist/index.js +6 -6
  2. package/dist/run.js +6 -8
  3. package/package.json +4 -5
  4. package/types/routes/meta.d.ts +2 -0
  5. package/dist/.DS_Store +0 -0
  6. package/dist/App.js +0 -168
  7. package/dist/App.js.map +0 -7
  8. package/dist/_.._/.DS_Store +0 -0
  9. package/dist/_.._/app/serverEntry.js +0 -8
  10. package/dist/_.._/app/serverEntry.js.map +0 -7
  11. package/dist/clientEntry.css +0 -2
  12. package/dist/clientEntry.css.map +0 -7
  13. package/dist/clientEntry.js +0 -168
  14. package/dist/clientEntry.js.map +0 -7
  15. package/dist/components.json +0 -20
  16. package/dist/fonts/LexendDeca-Bold-PSGSBIWW.woff2 +0 -0
  17. package/dist/fonts/LexendDeca-Bold.woff2 +0 -0
  18. package/dist/fonts/LexendDeca-Light-IDG5XLZG.woff2 +0 -0
  19. package/dist/fonts/LexendDeca-Light.woff2 +0 -0
  20. package/dist/fonts/LexendDeca-Medium-ZCTJP7FU.woff2 +0 -0
  21. package/dist/fonts/LexendDeca-Medium.woff2 +0 -0
  22. package/dist/fonts/LexendDeca-SemiBold-LCAJGQDV.woff2 +0 -0
  23. package/dist/fonts/LexendDeca-SemiBold.woff2 +0 -0
  24. package/dist/generateJsonFromJsx.js.map +0 -7
  25. package/dist/index.css +0 -2
  26. package/dist/index.css.map +0 -7
  27. package/dist/index.html +0 -14
  28. package/dist/index.js.map +0 -7
  29. package/dist/internalSsr.js.map +0 -7
  30. package/dist/island-runtime.js.map +0 -7
  31. package/dist/postcss.config.js +0 -6
  32. package/dist/run.js.map +0 -7
  33. package/dist/storybook/index.js.map +0 -7
  34. package/dist/storybook-main/main.js.map +0 -7
  35. package/dist/storybook-main/preview.js.map +0 -7
  36. package/dist/tailwind.config.js +0 -67
  37. package/types/constants/errors.d.ts +0 -5
  38. package/types/createAppViteConfig.d.ts +0 -2
  39. package/types/lib/cli.d.ts +0 -22
  40. package/types/lib/cliUtils.d.ts +0 -14
  41. package/types/routes/api.d.ts +0 -2
  42. package/types/routes/appServerRoutes.d.ts +0 -5
  43. package/types/storybook-main/preview.d.ts +0 -9
package/dist/run.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/lib/cli.ts", "../src/lib/logColors.ts", "../src/lib/cliUtils.ts", "../src/createDevServer.ts", "../src/routes/createDevServerRoutes.ts", "../src/routes/partial.ts", "../src/lib/fullOriginalUrlFromRequest.ts", "../src/lib/renderPartial.ts", "../src/lib/renderComponentWithCSS.ts", "../src/lib/packagePath.ts", "../../cms-js-internal/dist/types-CsJ4tzsl.js", "../../cms-js-internal/dist/index.js", "../src/lib/moduleGraph.ts", "../src/lib/pathHelpers.ts", "../src/lib/renderHelpers.ts", "../src/lib/templates.ts", "../src/lib/criticalDevErrorsToServerMessages.ts", "../src/lib/trackUsage.ts", "../src/lib/debug.ts", "../src/lib/renderModulePreview.ts", "../src/lib/proxyHelpers.ts", "../src/proxyPage/proxyPage.ts", "../src/lib/renderModule.ts", "../src/lib/fetchModuleGraphQLData.ts", "../src/lib/getFieldValuesForModule.ts", "../src/proxyPage/utils.ts", "../src/proxyPage/constants.ts", "../src/proxyPage/renderLocalError.ts", "../src/proxyPage/fetchPreviewInfo.ts", "../src/lib/previewUtils.ts", "../src/api/session.ts", "../src/fileManager.ts", "../src/routes/remoteFsDirtyHandler.ts", "../src/components/PartialsList.tsx", "../src/routes/linksToAllPartialsRouteHandler.tsx", "../src/components/ModulesList.tsx", "../src/routes/linksToAllModulesRouteHandler.tsx", "../src/routes/module.ts", "../src/routes/moduleFieldsJson.ts", "../src/lib/renderModuleFieldsJson.ts", "../src/proxyPage/fetchContentMetadata.ts", "../src/routes/proxyPageRouteHandler.ts", "../src/routes/proxyPageResourceRedirect.ts", "../src/components/HubLModulesList.tsx", "../src/api/designmanager.ts", "../src/components/HubLTemplatesList.tsx", "../src/routes/homeRouteHandler.tsx", "../src/routes/proxyPathPageRouteHandler.tsx", "../src/routes/proxyPathPageResourceRedirect.ts", "../src/routes/proxyServerlessHandler.ts", "../src/routes/modulePreviewRouteHandler.ts", "../src/routes/hublModuleRouteHandler.ts", "../src/routes/hublTemplateRouteHandler.ts", "../src/lib/getDevServerUIData.ts", "../src/routes/createAppServerRoutes.ts", "../src/shadowDevServer/startShadowDevServer.ts", "../src/shadowDevServer/createShadowDevServerRoutes.ts", "../src/createViteDevServer.ts", "../src/plugins/devSecretsPlugin.ts", "../src/createAppServer.ts", "../src/lib/httpsRedirectingServer.ts", "../src/lib/getJSRenderingGates.ts", "../src/lib/gates.ts", "../src/proxyPage/fetchDomains.ts", "../src/lib/errors.ts", "../src/lib/validateHSPlatform.ts", "../../cms-js-internal/dist/buildFieldsTypes.js", "../src/lib/watchFieldsUpdates.ts", "../src/lib/configHelpers.ts", "../src/run.ts"],
4
- "sourcesContent": ["import { resolve, join } from 'path';\nimport { existsSync } from 'fs';\nimport { wrapMessageInColor } from './logColors.js';\nimport cliProgress from 'cli-progress';\nimport { FILE_UPLOAD_RESULT_TYPES } from '@hubspot/local-dev-lib/constants/files';\nimport {\n ApiErrorContext,\n determineSrcAndDest,\n getUploadableFileList,\n logError,\n} from './cliUtils.js';\n\nfunction printHelpMessage() {\n console.log(`\n HubSpot CMS Dev Server\n\nUsage: hs-cms-dev-server <path> [options]\n\nMandatory:\n <path> Path to the directory containing your assets.\n\nOptions:\n -c, --config Path to alternate hubspot.config.yaml configuration.\n -a, --account The account name or id to use for the dev server.\n --ssl Enables SSL for the dev server, serving it over an https:// URL.\n --storybook Launches a Storybook dev server.\n --generateFieldsTypes Generate types for fields.(jsx|json) files in module folders.\n\nFor more information on HubSpot CMS JS Rendering, visit:\n${wrapMessageInColor(\n 'cyan',\n 'https://github.hubspot.com/cms-js-building-block-examples/'\n)}`);\n}\n\nexport function getDevServerCommandLineOptions(argv: NodeJS.Process['argv']) {\n const args = [...argv];\n const webRoot = args[2];\n let hubspotCliConfigPathOption: string | undefined;\n let hubspotCliAccountNameOption: string | undefined;\n\n // Print help if no arguments are provided.\n if (args.length === 2 || args.includes('help') || args.includes('--help')) {\n printHelpMessage();\n process.exit(0);\n }\n\n // Very basic CLI option parsing\n const configOptionIndex = args.findIndex(\n (arg) => arg === '-c' || arg === '--config'\n );\n if (configOptionIndex > 0 && args.length > configOptionIndex) {\n hubspotCliConfigPathOption = resolve(args[configOptionIndex + 1]);\n args.splice(configOptionIndex, 2);\n }\n\n const accountOptionIndex = args.findIndex(\n (arg) => arg === '-a' || arg === '--account'\n );\n if (accountOptionIndex > 0 && args.length > accountOptionIndex) {\n hubspotCliAccountNameOption = args[accountOptionIndex + 1];\n args.splice(accountOptionIndex, 2);\n }\n\n const sslEnabledOption = args.includes('--ssl') && !args.includes('--no-ssl');\n const storybook = args.findIndex((arg) => arg === '--storybook') > 0;\n const fieldGenEnabledOption = args.includes('--generateFieldsTypes');\n const resetSession = args.includes('--resetSession');\n const showUI = args.includes('--showUI');\n\n return {\n hubspotCliConfigPathOption,\n hubspotCliAccountNameOption,\n sslEnabledOption,\n storybook,\n fieldGenEnabledOption,\n webRoot,\n showUI,\n resetSession,\n };\n}\n\nexport async function buildThemePreviewOptions(\n webRoot: string,\n isUsingLocalWorkspace = false\n) {\n const themeJsonPath = join(webRoot, 'theme.json');\n if (!existsSync(themeJsonPath)) {\n return undefined;\n }\n\n const filePaths: string[] = await getUploadableFileList(webRoot, false);\n const { dest } = await determineSrcAndDest(webRoot, isUsingLocalWorkspace);\n const startProgressBar = (numFiles) => {\n const initialUploadProgressBar = new cliProgress.SingleBar(\n {\n gracefulExit: true,\n format: '[{bar}] {percentage}% | {value}/{total} | {label}',\n hideCursor: true,\n },\n cliProgress.Presets.rect\n );\n initialUploadProgressBar.start(numFiles, 0, {\n label: 'Starting...',\n });\n let uploadsHaveStarted = false;\n const uploadOptions = {\n onAttemptCallback: () => {\n /* Intentionally blank */\n },\n onSuccessCallback: () => {\n initialUploadProgressBar.increment();\n if (!uploadsHaveStarted) {\n uploadsHaveStarted = true;\n initialUploadProgressBar.update(0, {\n label: 'Uploading...',\n });\n }\n },\n onFirstErrorCallback: () => {\n /* Intentionally blank */\n },\n onRetryCallback: () => {\n /* Intentionally blank */\n },\n onFinalErrorCallback: () => initialUploadProgressBar.increment(),\n onFinishCallback: (results) => {\n initialUploadProgressBar.update(numFiles, {\n label: 'Complete!',\n });\n initialUploadProgressBar.stop();\n results.forEach((result) => {\n if (result.resultType === FILE_UPLOAD_RESULT_TYPES.FAILURE) {\n console.error(\n 'Uploading file \"%s\" to \"%s\" failed',\n result.file,\n dest\n );\n logError(\n result.error,\n new ApiErrorContext({\n accountId: null,\n request: dest,\n payload: result.file,\n })\n );\n }\n });\n },\n };\n return uploadOptions;\n };\n return {\n filePaths,\n startProgressBar,\n dest,\n };\n}\n", "const CONTROL_CHARACTER = '\\x1b';\nconst DEFAULT_SCHEME = '[0m';\n\ntype ColorMap = {\n [key: string]: number;\n};\n\nexport const ForeGroudANSIColorMap: ColorMap = {\n black: 30,\n red: 31,\n green: 32,\n yellow: 33,\n blue: 34,\n magenta: 35,\n cyan: 36,\n white: 37,\n};\n\nexport function wrapMessageInColor(color: string, message: string) {\n return `${CONTROL_CHARACTER}[${ForeGroudANSIColorMap[color]}m${message}${CONTROL_CHARACTER}${DEFAULT_SCHEME}`;\n}\n", "import fs from 'fs';\nimport path from 'path';\nimport { walk } from '@hubspot/local-dev-lib/fs';\nimport { createIgnoreFilter } from '@hubspot/local-dev-lib/ignoreRules';\nimport { isAllowedExtension } from '@hubspot/local-dev-lib/path';\nimport { isConvertableFieldJs } from '@hubspot/local-dev-lib/cms/handleFieldsJS';\nimport { escapeRegExp } from '@hubspot/local-dev-lib/escapeRegExp';\nimport inquirer from 'inquirer';\nimport { getThemeJSONPath } from '@hubspot/local-dev-lib/cms/themes';\nimport findup from 'findup-sync';\nimport { getCwd, getAbsoluteFilePath } from '@hubspot/local-dev-lib/path';\nimport { logger } from '@hubspot/local-dev-lib/logger';\nimport {\n isHubSpotHttpError,\n isSystemError,\n isFileSystemError,\n isValidationError,\n isMissingScopeError,\n isSpecifiedError,\n} from '@hubspot/local-dev-lib/errors/index';\nimport { getAccountConfig } from '@hubspot/local-dev-lib/config';\nimport { HUBSPOT_ACCOUNT_TYPE_STRINGS } from '@hubspot/local-dev-lib/constants/config';\nimport util from 'util';\nimport { isAxiosError } from 'axios';\nimport chalk from 'chalk';\nimport process from 'process';\nimport os from 'os';\nimport tty from 'tty';\n\nconst COMPONENT_TYPES = Object.freeze({\n privateApp: 'private-app',\n publicApp: 'public-app',\n hublTheme: 'hubl-theme',\n});\nconst CONFIG_FILES = {\n [COMPONENT_TYPES.privateApp]: 'app.json',\n [COMPONENT_TYPES.publicApp]: 'public-app.json',\n [COMPONENT_TYPES.hublTheme]: 'theme.json',\n};\nconst PLATFORM_VERSION_ERROR_TYPES = {\n PLATFORM_VERSION_NOT_SPECIFIED:\n 'PlatformVersionErrorType.PLATFORM_VERSION_NOT_SPECIFIED',\n PLATFORM_VERSION_RETIRED: 'PlatformVersionErrorType.PLATFORM_VERSION_RETIRED',\n PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST:\n 'PlatformVersionErrorType.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST',\n};\n\nfunction previewProjectPrompt(themeComponents) {\n return promptUser([\n {\n name: 'themeComponentPath',\n message: '[--theme] Select which theme to preview.',\n type: 'list',\n choices: themeComponents.map((t) => {\n const themeName = path.basename(t.path);\n return {\n name: themeName,\n value: t.path,\n };\n }),\n },\n ]);\n}\n\nconst getProjectConfig = async (\n _dir: string,\n isUsingLocalWorkspace = false\n) => {\n const getProjectConfigPath = (__dir: string): string | null => {\n const dir = isUsingLocalWorkspace ? __dir : getAbsoluteFilePath(__dir);\n\n if (!dir) {\n return null;\n }\n\n const PROJECT_CONFIG_FILE = 'hsproject.json';\n return findup(PROJECT_CONFIG_FILE, {\n cwd: path.resolve(__dir),\n nocase: true,\n });\n };\n\n const configPath = await getProjectConfigPath(_dir);\n if (!configPath) {\n return { projectConfig: null, projectDir: null };\n }\n\n try {\n const config = fs.readFileSync(configPath, 'utf8');\n const projectConfig = JSON.parse(config);\n return {\n projectDir: path.dirname(configPath),\n projectConfig,\n };\n } catch (e) {\n console.error('Could not read from project config');\n }\n};\n\nfunction loadConfigFile(configPath) {\n if (configPath) {\n try {\n const source = fs.readFileSync(configPath);\n const parsedConfig = JSON.parse(source as any);\n return parsedConfig;\n } catch (e) {\n console.debug(e);\n }\n }\n return null;\n}\nfunction getTypeFromConfigFile(configFile) {\n for (const key in CONFIG_FILES) {\n if (CONFIG_FILES[key] === configFile) {\n return key;\n }\n }\n return null;\n}\nasync function findProjectComponents(projectSourceDir) {\n const components = [];\n let projectFiles = [];\n try {\n projectFiles = await walk(projectSourceDir);\n } catch (e) {\n console.error(e);\n }\n projectFiles.forEach((projectFile) => {\n // Find app components\n\n const { base, dir } = path.parse(projectFile);\n if (Object.values(CONFIG_FILES).includes(base)) {\n const parsedAppConfig = loadConfigFile(projectFile);\n if (parsedAppConfig) {\n const isLegacy = getIsLegacyApp(parsedAppConfig, dir);\n const isHublTheme = base === CONFIG_FILES[COMPONENT_TYPES.hublTheme];\n components.push({\n type: getTypeFromConfigFile(base),\n config: parsedAppConfig,\n runnable: !isLegacy && !isHublTheme,\n path: dir,\n });\n }\n }\n });\n return components;\n}\nfunction getAppCardConfigs(appConfig, appPath) {\n const cardConfigs = [];\n let cards;\n if (appConfig && appConfig.extensions && appConfig.extensions.crm) {\n cards = appConfig.extensions.crm.cards;\n }\n if (cards) {\n cards.forEach(({ file }) => {\n if (typeof file === 'string') {\n const cardConfigPath = path.join(appPath, file);\n const cardConfig = loadConfigFile(cardConfigPath);\n if (cardConfig) {\n cardConfigs.push(cardConfig);\n }\n }\n });\n }\n return cardConfigs;\n}\nfunction getIsLegacyApp(appConfig, appPath) {\n const cardConfigs = getAppCardConfigs(appConfig, appPath);\n if (!cardConfigs.length) {\n // Assume any app that does not have any cards is not legacy\n return false;\n }\n let hasAnyReactExtensions = false;\n cardConfigs.forEach((cardConfig) => {\n if (!hasAnyReactExtensions) {\n const isReactExtension =\n cardConfig &&\n !!cardConfig.data &&\n !!cardConfig.data.module &&\n !!cardConfig.data.module.file;\n hasAnyReactExtensions = isReactExtension;\n }\n });\n return !hasAnyReactExtensions;\n}\n\nexport async function determineSrcAndDest(\n webRoot: string,\n isUsingLocalWorkspace = false\n) {\n let absoluteSrc;\n let dest;\n\n const { projectDir, projectConfig } = await getProjectConfig(\n webRoot,\n isUsingLocalWorkspace\n );\n\n if (projectDir && projectConfig) {\n let themeJsonPath = getThemeJSONPath(webRoot);\n if (!themeJsonPath) {\n const projectComponents = await findProjectComponents(projectDir);\n const themeComponents = projectComponents.filter(\n (c) => c.type === COMPONENT_TYPES.hublTheme\n );\n if (themeComponents.length === 0) {\n console.error(\n 'Your project has no theme components available to preview.'\n );\n process.exit(1);\n }\n const answer = await previewProjectPrompt(themeComponents);\n themeJsonPath = `${answer.themeComponentPath}/theme.json`;\n }\n const { dir: themeDir } = path.parse(themeJsonPath);\n absoluteSrc = themeDir;\n const { base: themeName } = path.parse(themeDir);\n dest = `@projects/${projectConfig.name}/${themeName}`;\n } else {\n console.error('Must be run inside a project directory');\n process.exit(1);\n }\n return { absoluteSrc, dest };\n}\n\n/*\n * Walks the src folder for files, filters them based on ignore filter.\n * If convertFields is true then will check for any JS fields conflicts (i.e., JS fields file and fields.json file) and prompt to resolve\n * From @hubspot/cli\n */\nexport async function getUploadableFileList(src, convertFields) {\n let filePaths = [];\n try {\n filePaths = await walk(src);\n } catch (e) {\n console.error(e);\n }\n const allowedFiles = filePaths\n .filter((file) => {\n if (!isAllowedExtension(file)) {\n return false;\n }\n return true;\n })\n .filter(createIgnoreFilter(true));\n if (!convertFields) {\n return allowedFiles;\n }\n\n const uploadableFiles = [];\n let skipFiles = [];\n for (const filePath of allowedFiles) {\n const fileName = path.basename(filePath);\n if (skipFiles.includes(filePath)) continue;\n const isConvertable = isConvertableFieldJs(src, filePath, convertFields);\n if (isConvertable || fileName === 'fields.json') {\n // This prompt checks if there are multiple field files in the folder and gets user to choose.\n const [choice, updatedSkipFiles] = await fieldsJsPrompt(\n filePath,\n src,\n skipFiles\n );\n skipFiles = updatedSkipFiles;\n // If they chose something other than the current file, move on.\n if (choice !== filePath) continue;\n }\n uploadableFiles.push(filePath);\n }\n return uploadableFiles;\n}\n\nfunction promptUser(promptConfig) {\n const prompt = inquirer.createPromptModule();\n return prompt(promptConfig);\n}\n\nexport async function fieldsJsPrompt(filePath, projectDir, skipFiles = []) {\n const FIELDS_FILES = ['fields.json', 'fields.js', 'fields.cjs', 'fields.mjs'];\n const dirName = path.dirname(filePath);\n\n // Get a list of all field files in the directory, resolve their absolute path, and remove the ones that we already skipped.\n const fileChoices = fs\n .readdirSync(dirName)\n .filter((file) => FIELDS_FILES.includes(file))\n .map((file) => path.resolve(dirName, file))\n .filter((file) => !skipFiles.includes(file));\n\n if (!fileChoices.length) return [filePath, []];\n if (fileChoices.length === 1) return [fileChoices[0], []];\n\n // We get the directory above the project one so that relative paths are printed with the root of the project dir attached.\n projectDir = projectDir.substring(0, projectDir.lastIndexOf('/'));\n const projectDirRegex = new RegExp(`^${escapeRegExp(projectDir)}`);\n const fileDir = path.dirname(fileChoices[0]).replace(projectDirRegex, '');\n\n const selection = [];\n fileChoices.forEach((fileChoice) => {\n selection.push({\n name: fileChoice.replace(projectDirRegex, ''),\n value: fileChoice,\n });\n });\n const promptVal = await promptUser([\n {\n message: `Multiple fields files located in \"${fileDir}\". Please choose which to upload:`,\n type: 'list',\n name: 'filePathChoice',\n choices: selection,\n },\n ]);\n const choice = promptVal.filePathChoice;\n\n // Add the ones that were not picked to skip files array.\n const notPicked = fileChoices.filter((item) => item !== choice);\n skipFiles.push(...notPicked);\n return [choice, skipFiles];\n}\n\nexport function logError(error, context = {}) {\n debugError(error, context);\n\n if (\n shouldSuppressError(error, context) ||\n shouldSuppressError(error, error.context)\n ) {\n return;\n }\n\n if (isHubSpotHttpError(error) && context) {\n error.updateContext(context);\n }\n\n if (isHubSpotHttpError(error) || isFileSystemError(error)) {\n if (isValidationError(error) || isMissingScopeError(error)) {\n // @ts-expect-error from CLI\n logger.error(error.formattedValidationErrors());\n } else {\n logger.error(error.message);\n }\n } else if (isSystemError(error)) {\n logger.error(error.message);\n } else if (error.message || error.reason) {\n const message = [];\n\n [error.message, error.reason].forEach((msg) => {\n if (msg) {\n message.push(msg);\n }\n });\n logger.error(message.join(' '));\n } else {\n // Unknown errors\n logger.error('An unknown error has occurred.');\n }\n}\n\n/**\n * Logs (debug) the error and context objects.\n *\n * @param {Error} error\n * @param {ApiErrorContext} context\n */\nfunction debugError(error, context = {}) {\n if (isHubSpotHttpError(error)) {\n logger.debug(error.toString());\n } else {\n logger.debug(`Error: ${error}`);\n }\n\n if (error.cause) {\n logger.debug(\n `Cause: ${\n isAxiosError(error.cause)\n ? error.cause\n : util.inspect(error.cause, false, null, true)\n }`\n );\n }\n if (context) {\n logger.debug(`Context: ${util.inspect(context, false, null, true)}`);\n }\n}\n\nexport class ApiErrorContext {\n accountId: any;\n request: any;\n payload: any;\n projectName: any;\n constructor(props = {} as any) {\n this.accountId = props.accountId;\n this.request = props.request || '';\n this.payload = props.payload || '';\n this.projectName = props.projectName || '';\n }\n}\n\nfunction createPlatformVersionError(err, subCategory) {\n let translationKey = 'unspecifiedPlatformVersion';\n let platformVersion = 'unspecified platformVersion';\n const errorContext =\n err.response && err.response.data && err.response.data.context;\n\n switch (subCategory) {\n case PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED:\n translationKey = 'platformVersionRetired';\n if (errorContext && errorContext[subCategory]) {\n platformVersion = errorContext[subCategory];\n }\n break;\n case PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST:\n translationKey = 'nonExistentPlatformVersion';\n if (errorContext && errorContext[subCategory]) {\n platformVersion = errorContext[subCategory];\n }\n break;\n default:\n break;\n }\n\n uiLine();\n logger.error('Platform version update required');\n const values = {\n unspecifiedPlatformVersion: `Projects with an {{#bold}}${platformVersion}{{/bold}} are no longer supported.`,\n platformVersionRetired: `Projects with {{#bold}}platformVersion ${platformVersion}{{/bold}} are no longer supported.`,\n nonExistentPlatformVersion: `Projects with {{#bold}}platformVersion ${platformVersion}{{/bold}} are not supported.`,\n };\n logger.log(values[translationKey]);\n logger.log(`Please update your project to the latest version and try again.`);\n logger.log(\n `For more info, see ${uiLink(\n `Projects platform versioning (BETA)`,\n 'https://developers.hubspot.com/docs/platform/platform-versioning'\n )}.`\n );\n uiLine();\n}\n\nfunction shouldSuppressError(err, context = {} as any) {\n if (isMissingScopeError(err)) {\n logger.error(\n `Couldn't execute the ${\n context.request || 'request'\n } because the access key for ${\n context.accountId ? uiAccountDescription(context.accountId) : ''\n } is missing required scopes. To update scopes, run ${uiCommandReference(\n 'hs auth'\n )}. Then deactivate the existing key and generate a new one that includes the missing scopes.`\n );\n return true;\n }\n\n if (\n isSpecifiedError(err, {\n subCategory: PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_NOT_SPECIFIED,\n })\n ) {\n createPlatformVersionError(\n err.data,\n PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_NOT_SPECIFIED\n );\n return true;\n }\n\n if (\n isSpecifiedError(err, {\n subCategory: PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED,\n })\n ) {\n createPlatformVersionError(\n err.data,\n PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_RETIRED\n );\n return true;\n }\n\n if (\n isSpecifiedError(err, {\n subCategory:\n PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST,\n })\n ) {\n createPlatformVersionError(\n err.data,\n PLATFORM_VERSION_ERROR_TYPES.PLATFORM_VERSION_SPECIFIED_DOES_NOT_EXIST\n );\n return true;\n }\n return false;\n}\n\nfunction uiAccountDescription(accountId, bold = true) {\n const account = getAccountConfig(accountId);\n const message = `${account.name} [${\n HUBSPOT_ACCOUNT_TYPE_STRINGS[account.accountType]\n //@ts-expect-error CLI type error\n }] (${account.portalId})`;\n return bold ? chalk.bold(message) : message;\n}\n\nconst { env } = process;\n\n//From: https://github.com/chalk/supports-color/blob/main/index.js (License: https://github.com/chalk/supports-color/blob/main/license)\n\nfunction translateLevel(level) {\n if (level === 0) {\n return {\n level,\n hasBasic: false,\n has256: false,\n has16m: false,\n };\n }\n\n return {\n level,\n hasBasic: true,\n has256: level >= 2,\n has16m: level >= 3,\n };\n}\n\nfunction _supportsColor(haveStream, { streamIsTTY } = {} as any) {\n if (haveStream && !streamIsTTY) {\n return 0;\n }\n\n const min = 0;\n\n if (env.TERM === 'dumb') {\n return min;\n }\n\n if (hasFlag('noColor')) {\n return 0;\n }\n\n if (process.platform === 'win32') {\n // Windows 10 build 10586 is the first Windows release that supports 256 colors.\n // Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n const osRelease = os.release().split('.');\n if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {\n return Number(osRelease[2]) >= 14931 ? 3 : 2;\n }\n\n return 1;\n }\n\n if ('CI' in env) {\n if (\n [\n 'TRAVIS',\n 'CIRCLECI',\n 'APPVEYOR',\n 'GITLAB_CI',\n 'GITHUB_ACTIONS',\n 'BUILDKITE',\n 'DRONE',\n ].some((sign) => sign in env) ||\n env.CI_NAME === 'codeship'\n ) {\n return 1;\n }\n\n return min;\n }\n\n // Check for Azure DevOps pipelines\n if ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n return 1;\n }\n\n if (env.COLORTERM === 'truecolor') {\n return 3;\n }\n\n if ('TERM_PROGRAM' in env) {\n const version = Number.parseInt(\n (env.TERM_PROGRAM_VERSION || '').split('.')[0],\n 10\n );\n\n // eslint-disable-next-line default-case\n switch (env.TERM_PROGRAM) {\n case 'iTerm.app':\n return version >= 3 ? 3 : 2;\n case 'Apple_Terminal':\n return 2;\n // No default\n }\n }\n\n if (/-256(color)?$/i.test(env.TERM)) {\n return 2;\n }\n\n if (\n /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)\n ) {\n return 1;\n }\n\n if ('COLORTERM' in env) {\n return 1;\n }\n\n return min;\n}\n\nfunction createSupportsColor(stream, options = {}) {\n const level = _supportsColor(stream, {\n streamIsTTY: stream && stream.isTTY,\n ...options,\n });\n\n return translateLevel(level);\n}\n\nconst supportsColor = {\n createSupportsColor,\n stdout: createSupportsColor({ isTTY: tty.isatty(1) }),\n stderr: createSupportsColor({ isTTY: tty.isatty(2) }),\n};\n\nconst UI_COLORS = {\n SORBET: '#FF8F59',\n MARIGOLD: '#f5c26b',\n MARIGOLD_DARK: '#dbae60',\n};\n\nfunction getTerminalUISupport() {\n return {\n hyperlinks: supportsHyperlink(process.stdout),\n color: supportsColor.stdout.hasBasic,\n };\n}\nfunction uiLine() {\n logger.log('-'.repeat(50));\n}\nfunction uiLink(linkText, url) {\n const terminalUISupport = getTerminalUISupport();\n const encodedUrl = encodeURI(url);\n\n if (terminalUISupport.hyperlinks) {\n const CLOSE_SEQUENCE = '\\u001B]8;;\\u0007';\n\n const result = [\n '\\u001B]8;;',\n encodedUrl,\n '\\u0007',\n linkText,\n CLOSE_SEQUENCE,\n ].join('');\n\n return terminalUISupport.color ? chalk.cyan(result) : result;\n }\n\n return terminalUISupport.color\n ? `${linkText}: ${chalk.reset.cyan(encodedUrl)}`\n : `${linkText}: ${encodedUrl}`;\n}\nfunction uiCommandReference(command) {\n const terminalUISupport = getTerminalUISupport();\n\n const commandReference = `\\`${command}\\``;\n\n return chalk.bold(\n terminalUISupport.color\n ? chalk.hex(UI_COLORS.MARIGOLD_DARK)(commandReference)\n : commandReference\n );\n}\n\n//See https://github.com/jamestalmage/supports-hyperlinks (License: https://github.com/jamestalmage/supports-hyperlinks/blob/master/license)\nfunction parseVersion(versionString) {\n if (/^\\d{3,4}$/.test(versionString)) {\n // Env var doesn't always use dots. example: 4601 => 46.1.0\n const m = /(\\d{1,2})(\\d{2})/.exec(versionString);\n return {\n major: 0,\n minor: parseInt(m[1], 10),\n patch: parseInt(m[2], 10),\n };\n }\n\n const versions = (versionString || '').split('.').map((n) => parseInt(n, 10));\n return {\n major: versions[0],\n minor: versions[1],\n patch: versions[2],\n };\n}\n\nfunction supportsHyperlink(stream) {\n if (hasFlag('noHyperlinks')) {\n return false;\n }\n\n if (stream && !stream.isTTY) {\n return false;\n }\n\n if (process.platform === 'win32') {\n return false;\n }\n\n if ('CI' in env) {\n return false;\n }\n\n if ('TERM_PROGRAM' in env) {\n const version = parseVersion(env.TERM_PROGRAM_VERSION);\n\n // eslint-disable-next-line default-case\n switch (env.TERM_PROGRAM) {\n case 'iTerm.app':\n if (version.major === 3) {\n return version.minor >= 1;\n }\n\n return version.major > 3;\n // No default\n }\n }\n\n if ('VTE_VERSION' in env) {\n // 0.50.0 was supposed to support hyperlinks, but throws a segfault\n if (env.VTE_VERSION === '0.50.0') {\n return false;\n }\n\n const version = parseVersion(env.VTE_VERSION);\n return version.major > 0 || version.minor >= 50;\n }\n\n return false;\n}\n// See https://github.com/sindresorhus/has-flag/blob/main/index.js (License: https://github.com/sindresorhus/has-flag/blob/main/license)\n\nfunction hasFlag(flag, argv = process.argv) {\n const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';\n const position = argv.indexOf(prefix + flag);\n const terminatorPosition = argv.indexOf('--');\n return (\n position !== -1 &&\n (terminatorPosition === -1 || position < terminatorPosition)\n );\n}\n", "import path from 'path';\nimport url from 'url';\nimport express from 'express';\nimport http from 'http';\nimport https from 'https';\nimport bodyParser from 'body-parser';\nimport { spawn } from 'child_process';\nimport { normalizePath } from 'vite';\nimport { Transform } from 'stream';\nimport createDevServerRoutes from './routes/createDevServerRoutes.js';\nimport startShadowDevServer from './shadowDevServer/startShadowDevServer.js';\nimport { getProjectNameFromHSConfig } from './lib/proxyHelpers.js';\nimport createViteDevServer from './createViteDevServer.js';\nimport createAppServer from './createAppServer.js';\nimport { createHttpsRedirectingServer } from './lib/httpsRedirectingServer.js';\nimport getJsRenderingGates from './lib/getJSRenderingGates.js';\n\nimport {\n getEnv,\n getAccountId,\n getAccountConfig,\n loadConfig,\n validateConfig,\n} from '@hubspot/local-dev-lib/config';\nimport { fetchSecrets } from '@hubspot/local-dev-lib/api/secrets';\nimport { fetchWebsiteDomainNames } from './proxyPage/fetchDomains.js';\nimport { HSEnvironment, Hublet } from '@hubspot/cms-components';\nimport {\n handleSecretsError,\n logMissingScopeWarning,\n MissingScopeError,\n} from './lib/errors.js';\nimport { wrapMessageInColor } from './lib/logColors.js';\nimport { Gate, getCMSAssetConfig } from '@hubspot/cms-js-internal';\nimport sendTrackingRequest, { setTrackingInfo } from './lib/trackUsage.js';\nimport validateHSPlatform, {\n findHSProjectJson,\n} from './lib/validateHSPlatform.js';\nimport { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport { startFieldsTypeGenWatcher } from './lib/watchFieldsUpdates.js';\nimport {\n initiatePreviewSession,\n ThemePreviewOptions,\n} from './lib/previewUtils.js';\nimport { getSecretNamesFromConfig } from './lib/configHelpers.js';\nimport { RequestLocals } from './lib/getDevServerUIData.js';\n\nconst BASE_PATH = '/';\nconst PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;\nconst SHADOW_PORT = 1442;\nconst STORYBOOK_PORT = process.env.STORYBOOK_PORT\n ? parseInt(process.env.STORYBOOK_PORT, 10)\n : 3123;\n\nasync function createDevServer(\n webRoot: string,\n storybook: boolean,\n hubspotCliConfigPathOption?: string,\n hubspotCliAccountNameOption?: string,\n sslEnabledOption?: boolean,\n fieldGenEnabledOption?: boolean,\n themePreviewOptions?: ThemePreviewOptions,\n showUI?: boolean\n) {\n let authedPortalId: number | null = null;\n let authedEnv: HSEnvironment | null = null;\n let jsRenderingGates: Gate[] = [];\n let personalAccessKey: string | null = null;\n let secretNames: Array<string> = [];\n let secretNamesFromConfig: Array<string> = [];\n\n if (hubspotCliConfigPathOption && hubspotCliAccountNameOption) {\n console.log(\n `Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration at: ${hubspotCliConfigPathOption}`\n );\n } else if (hubspotCliConfigPathOption) {\n console.log(\n `Loading HS auth configuration at: ${hubspotCliConfigPathOption}`\n );\n } else if (hubspotCliAccountNameOption) {\n console.log(\n `Loading HS auth (account = ${hubspotCliAccountNameOption}) configuration.`\n );\n }\n\n // If a custom hubspot.config.yaml config path was set, make sure to force load that before\n // any hs config values are read\n loadConfig(hubspotCliConfigPathOption || null, { useEnv: false });\n\n const cmsAssetConfig = getCMSAssetConfig(webRoot);\n secretNamesFromConfig = getSecretNamesFromConfig(cmsAssetConfig);\n\n if (validateConfig()) {\n authedPortalId = getAccountId(hubspotCliAccountNameOption);\n\n const env = getEnv(hubspotCliAccountNameOption);\n\n if (!env) {\n throw new Error(\n `No environment found for account ${hubspotCliAccountNameOption} from hubspot.config.yaml`\n );\n }\n\n authedEnv = env;\n\n personalAccessKey =\n getAccountConfig(authedPortalId) &&\n getAccountConfig(authedPortalId).personalAccessKey;\n\n if (!authedPortalId && hubspotCliAccountNameOption) {\n console.error(\n `Couldn't find ${hubspotCliAccountNameOption} in your hubspot.config.yaml`\n );\n process.exit(1);\n }\n\n if (personalAccessKey) {\n try {\n jsRenderingGates = await getJsRenderingGates(\n authedPortalId,\n authedEnv,\n personalAccessKey\n );\n } catch (e) {\n console.warn(\n `Unable to get gating information. Gated features will not be available in the local dev server.`\n );\n }\n }\n if (cmsAssetConfig) {\n try {\n const secretsResponse = (await fetchSecrets(authedPortalId)).data;\n if (secretNamesFromConfig && secretsResponse) {\n secretNames = secretsResponse.results.filter((secretName: string) =>\n secretNamesFromConfig.includes(secretName)\n );\n\n if (secretNames.length < secretNamesFromConfig.length) {\n const missingSecrets = secretNamesFromConfig.filter(\n (secretName: string) =>\n secretsResponse.results.includes(secretName) === false\n );\n console.error(\n `Secrets ${missingSecrets.join(\n ', '\n )} could not be found as initialized for this account, be sure to use \\`hs secrets add\\``\n );\n }\n }\n } catch (e) {\n handleSecretsError(e);\n console.log(e);\n }\n }\n } else {\n console.warn(\n `Couldn't find an account to use, make sure there is hubspot.config.yaml in this folder (or a parent).\nIf needed you can refer to another config file with --config.\n\nLocal proxy functionality and module preview routes will not work without setting up authentication. You can work purely on modules locally at \"/module/[module_name]\", however the experience may be degraded due to missing account data.`\n );\n\n secretNames = secretNamesFromConfig;\n }\n\n setTrackingInfo(authedPortalId, authedEnv);\n sendTrackingRequest('start-dev-server');\n\n let domainsToProxy: string[] = [];\n\n if (authedPortalId) {\n try {\n const portalDomains = await fetchWebsiteDomainNames(authedPortalId);\n domainsToProxy = (process.env.DOMAINS_TO_PROXY || '')\n .split(',')\n .filter((d) => !!d);\n domainsToProxy = [...domainsToProxy, ...portalDomains];\n } catch (e) {\n if (e instanceof MissingScopeError) {\n logMissingScopeWarning(e);\n } else {\n const failedDomainFetchMessages = [\n \"Failed to fetch the portal's domains, as a result:\",\n \"- HTTPS proxying won't work with them.\",\n \"- Proxying to serverless functions won't work.\",\n ]\n .map((msg) => wrapMessageInColor('yellow', msg))\n .join('\\n');\n console.warn(failedDomainFetchMessages);\n }\n }\n }\n\n let authedHublet: Hublet;\n try {\n const accountInformation = (\n await hsCliHttp.get<any>(authedPortalId, {\n url: '/account-info/v3/details',\n })\n ).data;\n authedHublet = accountInformation.dataHostingLocation;\n } catch (e) {\n authedHublet = 'na1';\n }\n\n const absoluteWebRoot = normalizePath(path.resolve(process.cwd(), webRoot));\n const [__webRootProjectFolder, webRootProjectComponentFolder] =\n absoluteWebRoot.replace(/\\/$/, '').split('/').slice(-2);\n const projectConfigPath = findHSProjectJson(absoluteWebRoot);\n\n if (authedPortalId) {\n await validateHSPlatform(projectConfigPath, authedPortalId);\n }\n\n const isUngatedForUnifiedThemePreview = jsRenderingGates.includes(\n 'CMS:React:UnifiedThemePreview'\n );\n\n let _localPreviewToken: string | null = null;\n let _tokenStatus: 'NEW' | 'REFRESHED';\n if (themePreviewOptions && isUngatedForUnifiedThemePreview) {\n const { localPreviewToken, tokenStatus } = await initiatePreviewSession(\n authedPortalId,\n absoluteWebRoot,\n themePreviewOptions\n );\n _localPreviewToken = localPreviewToken;\n _tokenStatus = tokenStatus;\n }\n\n const viteServer = await createViteDevServer(\n absoluteWebRoot,\n PORT,\n sslEnabledOption,\n domainsToProxy,\n jsRenderingGates,\n secretNames\n );\n\n // Start file watcher for type gen from fields.(jsx|json)\n if (fieldGenEnabledOption) {\n startFieldsTypeGenWatcher(viteServer, absoluteWebRoot);\n }\n\n // Get https key and cert from the vite config set by vite-plugin-mkcert (if it worked )\n const viteHTTPSConfig = viteServer.config.server.https as https.ServerOptions;\n const httpsKey = viteHTTPSConfig ? viteHTTPSConfig.key : null;\n const httpsCert = viteHTTPSConfig ? viteHTTPSConfig.cert : null;\n const projectName = projectConfigPath\n ? getProjectNameFromHSConfig(projectConfigPath)\n : '';\n\n const httpServers = [];\n const expressServer = express();\n expressServer.locals.devServerHost = 'hslocal.net';\n expressServer.locals.devServerPort = PORT;\n expressServer.locals.webRoot = webRoot;\n expressServer.locals.viteServer = viteServer;\n expressServer.locals.authedPortalId = authedPortalId;\n expressServer.locals.authedEnv = authedEnv;\n expressServer.locals.authedHublet = authedHublet;\n expressServer.locals.storybookEnabled = storybook;\n expressServer.locals.storybookPort = STORYBOOK_PORT;\n expressServer.locals.projectName = projectName;\n expressServer.locals.projectComponentPath = webRootProjectComponentFolder;\n expressServer.locals.jsRenderingGates = jsRenderingGates;\n expressServer.locals.domainsToProxy = domainsToProxy;\n expressServer.locals.localPreviewToken = _localPreviewToken;\n\n expressServer.use(bodyParser.json());\n\n const appWebRoot = path.join(\n path.dirname(url.fileURLToPath(import.meta.url)),\n '../app'\n );\n const reqLocals: Omit<RequestLocals, 'viteServer'> = {\n themeWebRoot: absoluteWebRoot,\n authedPortalId,\n authedEnv,\n authedHublet,\n projectName,\n webRootProjectComponentFolder,\n localPreviewToken: _localPreviewToken,\n };\n const appServer = await createAppServer(appWebRoot, PORT, sslEnabledOption);\n\n expressServer.use(\n BASE_PATH,\n await createDevServerRoutes(\n viteServer,\n storybook ? STORYBOOK_PORT : null,\n appServer,\n reqLocals,\n appWebRoot\n )\n );\n\n if (sslEnabledOption) {\n if (httpsKey && httpsCert) {\n const { server, innerHTTPServer, innerHTTPSServer } =\n createHttpsRedirectingServer(\n { key: httpsKey, cert: httpsCert },\n expressServer\n );\n\n server.listen(PORT);\n\n httpServers.push(server);\n // Not sure if we need to worry about closing all of these, but\uD83E\uDD37\n httpServers.push(innerHTTPServer);\n httpServers.push(innerHTTPSServer);\n } else {\n console.error('Failed to start a HTTPS server, try --no-ssl');\n process.exit(1);\n }\n } else {\n const httpServer = http.createServer(expressServer);\n httpServer.listen(PORT);\n httpServers.push(httpServer);\n }\n\n if (!process.env.IN_CODESANDBOX && !process.env.CODESANDBOX_HOST) {\n startShadowDevServer(\n PORT,\n SHADOW_PORT,\n themePreviewOptions ? themePreviewOptions.dest : ''\n );\n }\n\n let extraServerInfo = '';\n const protocol = sslEnabledOption ? 'https' : 'http';\n\n if (authedPortalId) {\n extraServerInfo += `, hubid=${authedPortalId}`;\n }\n\n if (authedEnv && authedEnv !== 'prod') {\n extraServerInfo += `, env=${authedEnv}`;\n }\n\n console.log(\n `\nHubSpot CMS dev server hosting: ${projectName}/${expressServer.locals.projectComponentPath} (at ${protocol}://hslocal.net:${PORT}${extraServerInfo})\n`\n );\n\n // if (showUI) {\n // const appWebRoot = path.join(\n // path.dirname(url.fileURLToPath(import.meta.url)),\n // '../app'\n // );\n // const reqLocals: Omit<RequestLocals, 'viteServer'> = {\n // themeWebRoot: absoluteWebRoot,\n // authedPortalId,\n // authedEnv,\n // authedHublet,\n // projectName,\n // webRootProjectComponentFolder,\n // localPreviewToken: _localPreviewToken,\n // };\n\n // const appServer = await createAppServer(appWebRoot, reqLocals, PORT + 1);\n // httpServers.push(appServer);\n // }\n\n if (storybook) {\n const packageRoot = path.dirname(url.fileURLToPath(import.meta.url));\n\n const configPath = path.resolve(packageRoot, './storybook-main');\n\n sendTrackingRequest('start-storybook');\n\n const storybookProcess = spawn(\n 'sb',\n [\n 'dev',\n '-p',\n STORYBOOK_PORT.toString(),\n '-c',\n configPath,\n '--quiet',\n '--no-open',\n ],\n {\n cwd: process.cwd(),\n env: {\n ...process.env,\n portalId: authedPortalId.toString(),\n hsEnv: authedEnv,\n hublet: authedHublet,\n WEB_ROOT: path.join(webRoot, 'components'),\n },\n }\n );\n\n console.log(\n wrapMessageInColor(\n 'yellow',\n `Starting storybook server on port ${STORYBOOK_PORT}`\n )\n );\n\n storybookProcess.stdout\n .pipe(\n new Transform({\n transform(chunk, _encoding, callback) {\n callback(null, wrapMessageInColor('yellow', chunk.toString()));\n },\n })\n )\n .pipe(process.stdout);\n\n storybookProcess.stderr\n .pipe(\n new Transform({\n transform(chunk, _encoding, callback) {\n callback(null, wrapMessageInColor('red', chunk.toString()));\n },\n })\n )\n .pipe(process.stderr);\n }\n\n // Return hook to shut down server gracefully\n return {\n close: () => {\n const serverClosePromises = httpServers.map(\n (server) =>\n new Promise((resolve) => {\n server.close(() => {\n resolve(null);\n });\n })\n );\n return Promise.allSettled([...serverClosePromises, viteServer.close()]);\n },\n };\n}\n\nexport default createDevServer;\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable require-await */\n\nimport { ViteDevServer } from 'vite';\nimport { Request, Response, Router, urlencoded } from 'express';\nimport { createProxyMiddleware } from 'http-proxy-middleware';\nimport partialRouteHandler from './partial.js';\nimport linksToAllPartialsRouteHandler from './linksToAllPartialsRouteHandler.js';\nimport linksToAllModulesRouteHandler from './linksToAllModulesRouteHandler.js';\nimport moduleRouteHandler from './module.js';\nimport moduleFieldsJsonRouteHandler from './moduleFieldsJson.js';\nimport proxyPageRouteHandler from './proxyPageRouteHandler.js';\nimport proxyPageResourceRedirect from './proxyPageResourceRedirect.js';\nimport homeRouteHandler from './homeRouteHandler.js';\nimport { debug } from '../lib/debug.js';\nimport { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';\nimport proxyPathPageRouteHandler from './proxyPathPageRouteHandler.js';\nimport proxyPathPageResourceRedirect from './proxyPathPageResourceRedirect.js';\nimport proxyServerlessHandler from './proxyServerlessHandler.js';\nimport modulePreviewRouteHandler from './modulePreviewRouteHandler.js';\nimport { hublModuleRouteHandler } from './hublModuleRouteHandler.js';\nimport { templateRouteHandler } from './hublTemplateRouteHandler.js';\nimport { remoteFsDirtyHandler } from './remoteFsDirtyHandler.js';\nimport { RequestLocals } from '../lib/getDevServerUIData.js';\nimport fs from 'node:fs/promises';\nimport getDevServerUIData from '../lib/getDevServerUIData.js';\nimport createAppServerRoutes from './createAppServerRoutes.js';\n\nconst STORYBOOK_DOMAINS = VALID_PROXY_DOMAIN_SUFFIXES.map(\n (domain) => `storybook.${domain}`\n);\n\nconst createDevServerRoutes = async (\n viteServer: ViteDevServer,\n storybookPort?: number,\n appServer?: ViteDevServer,\n reqLocals?: Omit<RequestLocals, 'viteServer'>,\n appWebRoot?: string\n) => {\n const devServerApp = Router();\n\n // Debug incoming requests, enable with the DEBUG=cms-dev-server env variable\n devServerApp.use((request: Request, response: Response, next) => {\n const { method, url, hostname } = request;\n debug(`${method}:${hostname}${url}`);\n next();\n });\n\n if (storybookPort) {\n devServerApp.use(\n createProxyMiddleware(\n (__pathname, req) => STORYBOOK_DOMAINS.includes(req.hostname),\n {\n logLevel: 'warn',\n target: `http://localhost:${storybookPort}`,\n }\n )\n );\n }\n devServerApp.use(appServer.middlewares);\n devServerApp.use(viteServer.middlewares);\n devServerApp.use(urlencoded());\n\n devServerApp.use('/api', createAppServerRoutes());\n devServerApp.get('/', async (req, res) => {\n try {\n const initialProps = await getDevServerUIData({\n ...reqLocals,\n viteServer,\n });\n\n const url = req.originalUrl.replace('/', '');\n let template = await fs.readFile(`${appWebRoot}/index.html`, 'utf-8');\n template = await appServer.transformIndexHtml(url, template);\n const { render } = await appServer.ssrLoadModule(\n `${appWebRoot}/serverEntry.tsx`\n );\n\n const rendered = await render(initialProps);\n\n const html = template\n .replace(`<!--app-head-->`, rendered.head ?? '')\n .replace(`<!--app-html-->`, rendered.html ?? '')\n .replace(\n `<!--app-script-->`,\n `<script>window.__hsInitialProps = ${JSON.stringify(\n initialProps\n )}</script>` ?? ''\n );\n\n res.status(200).set({ 'Content-Type': 'text/html' }).send(html);\n } catch (e) {\n appServer?.ssrFixStacktrace(e);\n console.log(e.stack);\n res.status(500).end(e.stack);\n }\n });\n\n devServerApp.get('/proxy', proxyPathPageRouteHandler);\n devServerApp.get('/partials/', linksToAllPartialsRouteHandler);\n devServerApp.get('/partial/:partial', partialRouteHandler);\n devServerApp.get('/partial/:partial/*', partialRouteHandler);\n devServerApp.get('/remote-fs-dirty', remoteFsDirtyHandler);\n devServerApp.get('/preview/module/:moduleName', modulePreviewRouteHandler);\n devServerApp.get('/modules/', linksToAllModulesRouteHandler);\n devServerApp.get('/module/:moduleName', moduleRouteHandler);\n devServerApp.get(\n '/preview/module/:moduleName/fields.json',\n moduleFieldsJsonRouteHandler\n );\n devServerApp.get('/module/:moduleName/*', moduleRouteHandler);\n devServerApp.post('/preview/module/:moduleName', modulePreviewRouteHandler);\n devServerApp.get('/hublmodule/:modulePath(*)', hublModuleRouteHandler);\n devServerApp.get('/template/:templatePath(*)', templateRouteHandler);\n\n devServerApp.all('/hs/serverless/*', proxyServerlessHandler);\n devServerApp.all('/_hcms/api/*', proxyServerlessHandler);\n\n devServerApp.get('/legacy', homeRouteHandler);\n devServerApp.get('/*', proxyPathPageResourceRedirect);\n devServerApp.get('/*', proxyPageResourceRedirect);\n devServerApp.post('/*', proxyPageResourceRedirect);\n devServerApp.delete('/*', proxyPageResourceRedirect);\n devServerApp.head('/*', proxyPageResourceRedirect);\n devServerApp.put('/*', proxyPageResourceRedirect);\n devServerApp.options('/*', proxyPageResourceRedirect);\n devServerApp.get('/*', proxyPageRouteHandler);\n\n return devServerApp;\n};\n\nexport default createDevServerRoutes;\n", "import path from 'path';\nimport { ModuleNode, normalizePath } from 'vite';\nimport fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';\nimport renderPartial from '../lib/renderPartial.js';\nimport { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';\nimport { buildStaticEnvConfig } from '@hubspot/cms-components';\nimport packagePath from '../lib/packagePath.js';\nimport {\n getEntryPointHash,\n hasComponentExtension,\n} from '@hubspot/cms-js-internal';\nimport { getEntryPointBasePath } from '../lib/pathHelpers.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport {\n renderLocalProjectModulePreview,\n renderRemoteModulePreview,\n} from '../lib/renderModulePreview.js';\nimport { join as joinPosix } from 'path/posix';\n\nconst partialRouteHandler = async (request, response) => {\n sendTrackingRequest('view-partial-route');\n const {\n authedPortalId,\n authedEnv,\n authedHublet,\n webRoot,\n viteServer,\n jsRenderingGates,\n projectName,\n projectComponentPath,\n } = request.app.locals;\n const partialName = request.params.partial;\n\n const baseTemplatePath = packagePath(\n import.meta.url,\n 'html/baseTemplate.html'\n );\n\n // todo: use partial prefix const\n const partialPath = normalizePath(\n path.resolve(webRoot, 'components/partials/', partialName)\n );\n\n const entrypointPath = normalizePath(\n [\n '@projects',\n projectName,\n projectComponentPath,\n 'components/modules/',\n partialName,\n ].join('/')\n );\n\n const basePath = getEntryPointBasePath(partialPath);\n\n const environmentConfig = buildStaticEnvConfig(\n authedPortalId,\n authedHublet,\n authedEnv,\n false,\n jsRenderingGates\n );\n\n try {\n const {\n html: renderedHtml,\n cssNeeded,\n renderContext,\n inlineAssets,\n } = await renderPartial(\n viteServer,\n partialPath,\n {},\n fullOriginalUrlFromRequest(request),\n basePath,\n environmentConfig,\n {\n identifierPrefix: getEntryPointHash(entrypointPath),\n }\n );\n\n let resolvedCss = cssNeeded;\n let resolvedInlineAssets = inlineAssets;\n let partialHtml = renderedHtml;\n\n if (jsRenderingGates.includes('CMS:JSRenderer:AnalyzeCmsModules')) {\n const moduleNode: ModuleNode =\n await viteServer.moduleGraph.getModuleByUrl(\n hasComponentExtension(partialPath)\n ? partialPath\n : joinPosix(partialPath, 'index')\n );\n if (!moduleNode) {\n throw new Error(`Error: could not find partial: ${partialPath}`);\n }\n const moduleInfo = viteServer.pluginContainer.getModuleInfo(\n moduleNode.id\n );\n const cmsModules = moduleInfo.meta.findCmsModules ?? {};\n const localProjectModules: any = Object.values(cmsModules).filter(\n (moduleDescriptor: any) =>\n moduleDescriptor.path.startsWith(\n `@projects/${projectName}/${projectComponentPath}/components/modules/`\n )\n );\n const remoteModules: any = Object.values(cmsModules).filter(\n (moduleDescriptor: any) =>\n !moduleDescriptor.path.startsWith(\n `@projects/${projectName}/${projectComponentPath}/components/modules/`\n )\n );\n const remoteModulePreviewPromises = [];\n const localProjectModulePreviewPromises = [];\n for (const remoteModule of remoteModules) {\n const modulePlaceholder = createModulePlaceholder(remoteModule.name);\n if (!renderedHtml.includes(modulePlaceholder)) continue;\n remoteModulePreviewPromises.push(\n renderRemoteModulePreview(\n remoteModule.path,\n authedPortalId,\n authedEnv,\n request.get('COOKIE')\n ).then((result) => ({\n remoteModule,\n result,\n }))\n );\n }\n for (const localProjectModule of localProjectModules) {\n const modulePlaceholder = createModulePlaceholder(\n localProjectModule.name\n );\n if (!renderedHtml.includes(modulePlaceholder)) continue;\n localProjectModulePreviewPromises.push(\n renderLocalProjectModulePreview(\n path.basename(localProjectModule.path),\n authedPortalId,\n authedEnv,\n authedHublet,\n webRoot,\n viteServer,\n jsRenderingGates,\n projectName,\n projectComponentPath,\n fullOriginalUrlFromRequest(request),\n request.get('COOKIE')\n ).then((result) => ({\n localProjectModule,\n result,\n }))\n );\n }\n const [remoteModuleResults, localProjectModuleResults] =\n await Promise.all([\n Promise.all(remoteModulePreviewPromises),\n Promise.all(localProjectModulePreviewPromises),\n ]);\n\n // replace remote module placeholders\n for (const { remoteModule, result } of remoteModuleResults) {\n const modulePlaceholder = createModulePlaceholder(remoteModule.name);\n partialHtml = partialHtml.replace(modulePlaceholder, result.html);\n resolvedCss = resolvedCss.concat(result.cssNeeded);\n }\n\n // replace local project module placeholders\n for (const { localProjectModule, result } of localProjectModuleResults) {\n const modulePlaceholder = createModulePlaceholder(\n localProjectModule.name\n );\n renderContext.islands.push(...result.renderContext.islands);\n resolvedCss = resolvedCss.concat(result.cssNeeded);\n resolvedInlineAssets = resolvedInlineAssets.concat(result.inlineAssets);\n partialHtml = partialHtml.replace(modulePlaceholder, result.html);\n }\n }\n\n const htmlShell = await createHtmlShellDependingOnRenderContext(\n baseTemplatePath,\n request.originalUrl,\n `Partial: ${partialPath}`,\n renderContext,\n viteServer,\n jsRenderingGates\n );\n\n const html = htmlShell\n .replace(\n '<!--headend-->',\n [\n resolvedCss,\n ...resolvedInlineAssets.map((inlineAsset) => inlineAsset.html),\n ].join('\\n')\n )\n .replace(`<!--ssr-outlet-->`, partialHtml);\n\n response.status(200).set({ 'Content-Type': 'text/html' }).end(html);\n } catch (e) {\n console.error(e);\n viteServer.ssrFixStacktrace(e);\n\n response\n .status(500)\n .end(`Error rendering partial (${partialName})\\n\\n${e.stack}`);\n }\n};\n\nfunction createModulePlaceholder(moduleName: string) {\n return `<!-- hs-module-placeholder-${moduleName} -->`;\n}\n\nexport default partialRouteHandler;\n", "import { Request } from 'express';\n\nexport default function fullOriginalUrlFromRequest(request: Request) {\n return `${request.protocol}://${request.get('host')}${request.originalUrl}`;\n}\n", "import { EnvironmentConfig } from '@hubspot/cms-components/config';\nimport { ViteDevServer } from 'vite';\nimport { join as joinPosix } from 'path/posix';\nimport { RenderToPipeableStreamOptions } from 'react-dom/server';\nimport renderComponentWithCSS from './renderComponentWithCSS.js';\nimport { logPartialInfo } from './renderHelpers.js';\nimport { hasComponentExtension } from '@hubspot/cms-js-internal';\n\nconst lookForModuleInFolder = async (\n modulePath: string,\n viteServer: ViteDevServer\n): Promise<[any, string]> => {\n let componentModule: any;\n const insideFolderPath = joinPosix(modulePath, 'index');\n\n try {\n componentModule = await viteServer.ssrLoadModule(insideFolderPath);\n } catch (e) {\n if (!e.message.includes('Failed to load url')) {\n throw e;\n }\n }\n\n return [componentModule, insideFolderPath];\n};\n\nasync function renderPartial(\n viteServer: ViteDevServer,\n partialPath: string,\n props: any,\n pageUrl: string,\n basePath: string,\n environmentConfig: EnvironmentConfig,\n renderOptions?: RenderToPipeableStreamOptions\n) {\n try {\n logPartialInfo(partialPath, props);\n } catch (e) {\n console.log('unable to log partial prop info');\n console.error(e);\n }\n\n let componentModule: any;\n let resolvedPath: string;\n if (!hasComponentExtension(partialPath)) {\n [componentModule, resolvedPath] = await lookForModuleInFolder(\n partialPath,\n viteServer\n );\n }\n\n if (!componentModule) {\n componentModule = await viteServer.ssrLoadModule(partialPath);\n resolvedPath = componentModule ? partialPath : undefined;\n }\n\n if (!componentModule) {\n throw new Error(`Couldn't find partial: ${partialPath}`);\n }\n\n const Component = componentModule.default;\n\n if (!Component) {\n throw new Error(`Couldn't find default export on partial: ${resolvedPath}`);\n }\n\n return renderComponentWithCSS(\n viteServer,\n resolvedPath,\n Component,\n { props },\n pageUrl,\n basePath,\n undefined, // contextOptions\n environmentConfig,\n renderOptions\n );\n}\n\nexport default renderPartial;\n", "import { ViteDevServer } from 'vite';\nimport { ComponentType } from 'react';\nimport {\n RenderToPipeableStreamOptions,\n renderToStaticMarkup,\n} from 'react-dom/server';\nimport { ServerRenderContextValue } from '@hubspot/cms-components';\nimport { EnvironmentConfig } from '@hubspot/cms-components/config';\nimport { InlineAsset, StaticAsset } from '@hubspot/cms-js-internal';\nimport packagePath from './packagePath.js';\n\nimport { getComponentPaths } from './pathHelpers.js';\n\nexport type RenderResult = {\n html: string;\n inlineAssets?: InlineAsset[];\n cssNeeded: string;\n renderContext: ServerRenderContextValue;\n};\n\nasync function renderComponentWithCSS(\n viteServer: ViteDevServer,\n componentPath: string,\n Component: ComponentType,\n propsAndExtraDeps: any,\n pageUrl: string,\n entryPointBasePath: string,\n contextOptions,\n environmentConfig: EnvironmentConfig,\n renderOptions: RenderToPipeableStreamOptions,\n getServerSideProps?: Function,\n modifyHtmlCallback?: (\n html: string,\n renderContext: ServerRenderContextValue,\n staticAssets: StaticAsset[]\n ) => string\n): Promise<RenderResult> {\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n // Need to make sure rendering happens in Vite SSR context\n const { renderComponentOnServer, collectCssInDev } =\n await viteServer.ssrLoadModule(internalSsrPath);\n\n const [, componentPathWithExtension] = getComponentPaths(\n viteServer,\n componentPath\n );\n\n const renderResult: {\n html: string;\n renderContext: ServerRenderContextValue;\n } = await renderComponentOnServer(\n Component,\n propsAndExtraDeps,\n pageUrl,\n environmentConfig,\n entryPointBasePath,\n contextOptions,\n renderOptions,\n getServerSideProps\n );\n\n let html = renderResult.html;\n const renderContext = renderResult.renderContext;\n\n if (modifyHtmlCallback) {\n html = modifyHtmlCallback(\n html,\n renderContext,\n [] // Build-time generated static asset array is only available when deployed\n );\n }\n\n const cssNeeded = collectCssInDev(componentPathWithExtension, viteServer);\n\n let inlineAssets = [];\n if (renderContext.inlineAssets && Array.isArray(renderContext.inlineAssets)) {\n inlineAssets = renderContext.inlineAssets.map(\n ({ render: staticAssetRenderFunc, ...staticAsset }) => ({\n ...staticAsset,\n html: renderToStaticMarkup(staticAssetRenderFunc()),\n })\n );\n }\n\n return { html, inlineAssets, cssNeeded, renderContext };\n}\n\nexport default renderComponentWithCSS;\n", "import path from 'path';\nimport url from 'url';\nimport { normalizePath } from 'vite';\n\nexport default function packagePath(\n metaUrl: string,\n projectPath: string\n): string {\n if (process.env.DEV_SERVER_ENV === 'production') {\n return normalizePath(\n path.resolve(path.dirname(url.fileURLToPath(metaUrl)), projectPath)\n );\n }\n\n const parentDirPath = normalizePath(path.dirname(url.fileURLToPath(metaUrl)));\n const subPath = parentDirPath.replace(/^.+cms-dev-server\\/src\\//, '');\n const subPathParentDirs = subPath.split('/').map(() => '..');\n\n return path.resolve(\n path.dirname(url.fileURLToPath(metaUrl)),\n path.join(...subPathParentDirs, projectPath)\n );\n}\n", "import path from \"path\";\nimport { createHash } from \"crypto\";\nimport fs, { readFileSync, existsSync, readdirSync, lstatSync } from \"fs\";\nimport { join } from \"path/posix\";\nconst COMPONENT_EXTENSIONS = [\".jsx\", \".tsx\", \".js\", \".ts\"];\nconst ENTRY_POINTS_PATH = \"components/partials/\";\nconst MODULE_FOLDER_PATH = \"components/modules/\";\nconst VIRTUAL_ISLAND_RUNTIME = \"virtual:island-runtime\";\nconst VIRTUAL_CONFIG_SETUP = \"virtual:config-setup\";\nconst CSS_LANGS_RE = /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/;\nconst collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {\n const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(\n modulePathToStartWith\n );\n if (!appModulesForPath || appModulesForPath.size === 0) {\n throw new Error(`No modules at: ${modulePathToStartWith}`);\n } else if (appModulesForPath.size > 1) {\n throw new Error(`More than one module at: ${modulePathToStartWith}`);\n }\n const appModule = Array.from(appModulesForPath.values())[0];\n const allServerSideModulesImported = /* @__PURE__ */ new Set();\n const newCssModules = [];\n const moduleQueue = Array.from(appModule.importedModules);\n for (const importedModule of moduleQueue) {\n if (allServerSideModulesImported.has(importedModule.id)) {\n continue;\n }\n allServerSideModulesImported.add(importedModule.id);\n const isCss = CSS_LANGS_RE.test(importedModule.file);\n const moduleModulesToQueue = Array.from(importedModule.importedModules);\n if (isCss && !cssModulesImported.has(importedModule)) {\n cssModulesImported.add(importedModule);\n newCssModules.push(importedModule);\n }\n moduleQueue.push(...moduleModulesToQueue);\n }\n return newCssModules;\n};\nfunction createPreloadLink(assetPath, basePath = \"\") {\n if (assetPath && assetPath[0] !== \"/\") {\n assetPath = `/${assetPath}`;\n }\n if (assetPath.endsWith(\".js\")) {\n return `<link rel=\"modulepreload\" crossorigin href=\"${basePath}${assetPath}\">`;\n } else if (CSS_LANGS_RE.test(assetPath)) {\n return `<link rel=\"stylesheet\" href=\"${basePath}${assetPath}?css\">`;\n } else if (assetPath.endsWith(\".woff\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"font\" type=\"font/woff\" crossorigin>`;\n } else if (assetPath.endsWith(\".woff2\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"font\" type=\"font/woff2\" crossorigin>`;\n } else if (assetPath.endsWith(\".gif\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/gif\">`;\n } else if (assetPath.endsWith(\".jpg\") || assetPath.endsWith(\".jpeg\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/jpeg\">`;\n } else if (assetPath.endsWith(\".png\")) {\n return ` <link rel=\"preload\" href=\"${basePath}${assetPath}\" as=\"image\" type=\"image/png\">`;\n } else {\n throw new Error(`Unknown preload type for ${assetPath}`);\n }\n}\nconst collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {\n return `${collectCssModules(\n modulePathToStartWith,\n viteServer,\n cssModulesImported\n ).map((cssModule) => createPreloadLink(cssModule.url)).join(\"\\n\")}\n`;\n};\nconst badInlineJsChars = /[\\u2028\\u2029<>/]/g;\nconst inlineJsEscapeChars = {\n \"\\u2028\": \"\\\\u2028\",\n \"\\u2029\": \"\\\\u2029\",\n \"<\": \"\\\\u003C\",\n \">\": \"\\\\u003E\",\n \"/\": \"\\\\u002F\"\n};\nfunction escapeChar(unsafeChar) {\n return inlineJsEscapeChars[unsafeChar];\n}\nfunction escapeForInlineJS(input) {\n return input.replace(badInlineJsChars, escapeChar);\n}\nfunction jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent = 2, prettyPrint = true } = {}) {\n const indentString = \" \".repeat(baseIndent);\n jsonIndent = prettyPrint ? jsonIndent : void 0;\n return escapeForInlineJS(JSON.stringify(input, null, jsonIndent)).replace(\n /\\n/gm,\n `\n${indentString}`\n );\n}\nlet viteRoot;\nlet viteCommand;\nfunction resolveIslandPlugin(islandsSet) {\n return {\n enforce: \"pre\",\n name: \"resolve-islands\",\n configResolved(config) {\n viteRoot = config.root;\n viteCommand = config.command;\n },\n load(id) {\n if (id.endsWith(\"?island\") || id.endsWith(\"?client\")) {\n const [idWithNoParam] = id.split(\"?\");\n const islandModuleImportPath = `${idWithNoParam}?client-entry`;\n const componentExtension = path.extname(idWithNoParam);\n const componentFilenameWithNoExtension = path.basename(\n idWithNoParam,\n componentExtension\n );\n const modulePath = idWithNoParam.replace(`${viteRoot}/`, \"\");\n const moduleId = (viteCommand === \"serve\" ? idWithNoParam : modulePath).concat(\"?client-entry\");\n if (islandsSet) {\n islandsSet.add(moduleId);\n }\n return `\n const moduleId = '${moduleId}';\n\n const lazyComponent = () => import('${islandModuleImportPath}');\n lazyComponent.moduleName = '${componentFilenameWithNoExtension}';\n lazyComponent.moduleId = moduleId;\n\n export default lazyComponent;\n `;\n }\n return null;\n }\n };\n}\nfunction resolveIslandToPlainModulePlugin(enabled = true) {\n return {\n enforce: \"pre\",\n name: \"resolve-islands-to-plain\",\n configResolved(config) {\n viteRoot = config.root;\n viteCommand = config.command;\n },\n async resolveId(id, importer, options) {\n if (enabled && (id.endsWith(\"?island\") || id.endsWith(\"?client\"))) {\n const newId = id.replace(\"?island\", \"\").replace(\"?client\", \"\");\n const resolution = await this.resolve(newId, importer, {\n skipSelf: true,\n ...options\n });\n if (resolution) {\n return resolution;\n }\n }\n return null;\n }\n };\n}\nfunction resolveIslandToPlainModuleNoopPlugin() {\n return resolveIslandToPlainModulePlugin(false);\n}\nconst 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\";\nconst virtualClientRenderIslandModuleId = \"virtual:clientRenderIsland.tsx\";\nfunction clientIslandEntryPlugin() {\n return {\n enforce: \"pre\",\n name: \"client-island-entry-plugin\",\n resolveId(id) {\n if (id === virtualClientRenderIslandModuleId) {\n return virtualClientRenderIslandModuleId;\n }\n return null;\n },\n load(id) {\n if (id.endsWith(\"?client-entry\")) {\n const [idWithNoParam] = id.split(\"?\");\n return `\n import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';\n import Component from '${idWithNoParam}';\n\n export function render(island) {\n return clientRenderIsland(island, Component)\n }\n\n export default Component;\n `;\n }\n if (id === virtualClientRenderIslandModuleId) {\n return clientRenderIsland;\n }\n return null;\n }\n };\n}\nconst scriptTagToLogServerMessages = (messagesForBrowser, groupLabel, nonceAttribute) => {\n if (!messagesForBrowser) {\n return \"\";\n }\n const consoleLines = [];\n for (const message of messagesForBrowser) {\n let funcString = \"console.log\";\n if (message.level === \"error\") {\n funcString = \"console.error\";\n }\n if (message.level === \"warn\") {\n funcString = \"console.warn\";\n }\n const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(\", \");\n consoleLines.push(` ${funcString}(${argString});`);\n }\n let groupStart = \"\";\n let groupEnd = \"\";\n if (groupLabel !== void 0 && groupLabel !== null) {\n groupStart = `\n console.group(${JSON.stringify(groupLabel)});`;\n groupEnd = ` console.groupEnd()\n`;\n }\n return `<script ${nonceAttribute}>${groupStart}\n${consoleLines.join(\"\\n\")}\n${groupEnd}<\\/script>\n`;\n};\nconst getComponentExtension = (componentPath) => {\n const filteredExtensions = COMPONENT_EXTENSIONS.filter(\n (ext) => componentPath.endsWith(ext)\n );\n if (filteredExtensions.length === 1) {\n return filteredExtensions[0];\n }\n return void 0;\n};\nconst hasComponentExtension = (componentPath) => {\n return !!getComponentExtension(componentPath);\n};\nconst isStorybookStory = (componentPath) => {\n return !!path.basename(componentPath, path.extname(componentPath)).endsWith(\".stories\");\n};\nconst removeComponentExtension = (componentPath) => {\n const ext = getComponentExtension(componentPath);\n if (ext == null) {\n return componentPath;\n }\n return componentPath.slice(0, -1 * ext.length);\n};\nfunction getEntryPointHash(entryPoint) {\n return createHash(\"md5\").update(entryPoint).digest(\"hex\").slice(0, 6);\n}\nfunction getEntryPointHashWithIndexSuffix(entryPoint, index) {\n const renderIndexSuffix = index != null ? `i${index}` : \"\";\n return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;\n}\nconst COMBINED_REACT_BASE_PATH = \"https://static.hsappstatic.net/cms-js-static/ex/js/react/v18\";\nconst ISLAND_RUNTIME_CONFIG_BASE_PATH = \"https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1\";\nfunction getCombinedReactUrl() {\n const hsEnv = process.env.HS_ENV;\n const fileVersion = hsEnv === \"prod\" ? `react-combined.mjs` : \"react-combined-qa.mjs\";\n return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;\n}\nfunction getIslandRuntimeConfigUrl() {\n const hsEnv = process.env.HS_ENV;\n const fileVersion = hsEnv === \"prod\" ? `island-runtime.mjs` : \"island-runtime-qa.mjs\";\n return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;\n}\nfunction includesHublDataReference(templateSource) {\n const hublDataPattern = /\\{%\\s+set\\s+(experimentalHublData|hublData)\\s*=/;\n return !!templateSource.match(hublDataPattern);\n}\nconst removeIndexFromPath = (id) => {\n return id.replace(/\\/index\\.[jt]sx?$/, \"\");\n};\nconst removeIndexOrTrailingJsFromPath = (id) => {\n return removeIndexFromPath(id).replace(/\\.[jt]sx?$/, \"\");\n};\nconst HEALTHCHECKS_ENABLED_DEFAULT = true;\nconst HEALTHCHECKS_STRICT_DEFAULT = false;\nfunction getCMSAssetConfig(webRoot) {\n const cmsAssetsPath = path.join(webRoot, \"cms-assets.json\");\n const cmsThemePath = path.join(webRoot, \"theme.json\");\n const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;\n const parsedConfig = JSON.parse(\n fs.readFileSync(configPathToUse).toString()\n );\n return parsedConfig;\n}\nfunction getCMSAssetConfigIfExists(webRoot) {\n try {\n return getCMSAssetConfig(webRoot);\n } catch (e) {\n console.error(\n `Error finding or parsing cms-assets.json in ${webRoot}, but ignoring for now`\n );\n return {};\n }\n}\nfunction areBuildHealthChecksEnabled(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;\n}\nfunction doHealthChecksFailTheBuild(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;\n}\nfunction getServerIncludePrebundleDepPatterns(config) {\n var _a, _b;\n return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];\n}\nconst BUILD_INFO_PATH = \"/build-info.json\";\nfunction getBuildInfo(buildDir) {\n try {\n const buildInfo = JSON.parse(\n readFileSync(path.join(buildDir, BUILD_INFO_PATH)).toString()\n );\n return buildInfo;\n } catch (e) {\n throw new Error(`Error loading build-info.json, path: ${BUILD_INFO_PATH}`);\n }\n}\nfunction getBaseAssetUrlFromBuild(buildDir) {\n return getBuildInfo(buildDir).baseAssetUrl;\n}\nconst GATES = [\n \"CMS:JSRenderer:GetServerSideProps\",\n \"CMS:JSRenderer:ModuleHubl\",\n \"CMS:JSRenderer:RemoveCjsPlugin\",\n \"CMS:JSRenderer:RemoveMockClientEntryPlugin\",\n \"CMS:JSRenderer:AnalyzeCmsModules\",\n \"CMS:JSRenderer:ClientOnlySupplementalFieldSerialization\",\n \"CMS:React:UnifiedThemePreview\"\n];\nconst ENABLED_FEATURES_GATE_MAP = {\n \"cms:jsr:getServerSideProps\": \"CMS:JSRenderer:GetServerSideProps\",\n \"cms:jsr:RemoveCjsPlugin\": \"CMS:JSRenderer:RemoveCjsPlugin\",\n \"cms:jsr:analyzeCmsModules\": \"CMS:JSRenderer:AnalyzeCmsModules\",\n \"cms:jsr:clientOnlySupplementalFieldSerialization\": \"CMS:JSRenderer:ClientOnlySupplementalFieldSerialization\",\n \"cms:react:unifiedThemePreview\": \"CMS:React:UnifiedThemePreview\"\n};\nfunction isUngatedFor(gates, gate) {\n return gates.includes(gate);\n}\nfunction ungatedAtBuildTimeFor(buildDir, gate) {\n try {\n const buildInfo = getBuildInfo(buildDir);\n return isUngatedFor(buildInfo.gates, gate);\n } catch (e) {\n return false;\n }\n}\nconst findAllComponentsIn = (webRoot, componentsFolder) => {\n const fullComponentsFolderPath = join(webRoot, componentsFolder);\n const componentsByName = {};\n if (!existsSync(fullComponentsFolderPath)) {\n return componentsByName;\n }\n readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {\n const fullPath = join(fullComponentsFolderPath, fileOrFolderName);\n const subdirPath = join(componentsFolder, fileOrFolderName);\n const isDirectory = lstatSync(fullPath).isDirectory();\n if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {\n const subdirPathNoExtension = removeComponentExtension(subdirPath);\n componentsByName[subdirPathNoExtension] = subdirPath;\n } else if (isDirectory) {\n for (const potentialExtension of COMPONENT_EXTENSIONS) {\n const potentialIndexModule = join(\n subdirPath,\n `index${potentialExtension}`\n );\n const fullPotentialPath = join(\n fullPath,\n `index${potentialExtension}`\n );\n if (existsSync(fullPotentialPath)) {\n const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);\n componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;\n break;\n }\n }\n }\n });\n return componentsByName;\n};\nfunction findAllModulesInRoot(webRoot) {\n const allModuleComponents = findAllComponentsIn(\n webRoot,\n \"./components/modules\"\n );\n const moduleNames = Object.keys(allModuleComponents).map(\n (moduleSubpath) => moduleSubpath.replace(\"components/modules/\", \"\").replace(\"/index\", \"\")\n );\n const moduleSubpaths = Object.keys(allModuleComponents);\n const moduleExtensions = Object.values(allModuleComponents).map((path2) => {\n if (!path2) return \"\";\n const extension = path2.split(\".\").pop() || \"\";\n return extension;\n });\n const moduleNamesWithExtension = Object.values(allModuleComponents).map(\n (path2) => {\n if (!path2) return \"\";\n const file = path2.replace(\"components/modules/\", \"\");\n return file.includes(\"/index.\") ? file.split(\"/index.\")[0] : file;\n }\n );\n return {\n moduleNames,\n moduleSubpaths,\n moduleNamesWithExtension,\n moduleExtensions\n };\n}\nfunction findAllPartialsInRoot(webRoot) {\n const allPartialComponents = findAllComponentsIn(\n webRoot,\n \"./components/partials\"\n );\n const partialNames = Object.keys(allPartialComponents).map(\n (partialSubpath) => partialSubpath.replace(\"components/partials/\", \"\").replace(\"/index\", \"\")\n );\n const partialSubpaths = Object.keys(allPartialComponents);\n return { partialNames, partialSubpaths };\n}\nfunction namespaceModulePropsShape(props) {\n const {\n dataQueryResult,\n hublParameters,\n fieldValues: passedFieldValues,\n hublData,\n experimentalHublData,\n moduleName,\n supplementalFieldValues\n } = props;\n const oldPropsShape = { ...props };\n if (oldPropsShape.dataQueryResult) {\n delete oldPropsShape.dataQueryResult;\n }\n if (oldPropsShape.hublParameters) {\n delete oldPropsShape.hublParameters;\n }\n const fieldValues = passedFieldValues || oldPropsShape;\n return {\n ...fieldValues,\n dataQueryResult,\n fieldValues,\n hublParameters,\n hublData,\n experimentalHublData,\n moduleName,\n supplementalFieldValues\n };\n}\nfunction setIn(object, nestedKeysArray, value) {\n let curr = object;\n const finalKey = nestedKeysArray.pop();\n for (let index = 0; index < nestedKeysArray.length; index++) {\n const currentKey = nestedKeysArray[index];\n const nextKey = nestedKeysArray[index + 1];\n if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {\n if (curr[currentKey] === void 0) {\n curr[currentKey] = [];\n }\n }\n if (curr[currentKey] === void 0) {\n curr[currentKey] = {};\n }\n curr = curr[currentKey];\n }\n if (value !== void 0) {\n curr[finalKey] = value;\n }\n}\nfunction isStylesheetAsset(staticAsset) {\n return staticAsset.type === \"stylesheet\";\n}\nexport {\n areBuildHealthChecksEnabled as A,\n doHealthChecksFailTheBuild as B,\n getServerIncludePrebundleDepPatterns as C,\n isUngatedFor as D,\n ENABLED_FEATURES_GATE_MAP as E,\n ungatedAtBuildTimeFor as F,\n GATES as G,\n escapeForInlineJS as H,\n jsonStringifyAndEscapeForInlineJS as I,\n COMPONENT_EXTENSIONS as J,\n ENTRY_POINTS_PATH as K,\n VIRTUAL_CONFIG_SETUP as L,\n MODULE_FOLDER_PATH as M,\n CSS_LANGS_RE as N,\n isStylesheetAsset as O,\n getBuildInfo as P,\n getBaseAssetUrlFromBuild as Q,\n VIRTUAL_ISLAND_RUNTIME as V,\n findAllModulesInRoot as a,\n findAllPartialsInRoot as b,\n collectCssInDev as c,\n collectCssModules as d,\n resolveIslandToPlainModulePlugin as e,\n findAllComponentsIn as f,\n resolveIslandToPlainModuleNoopPlugin as g,\n clientIslandEntryPlugin as h,\n getComponentExtension as i,\n hasComponentExtension as j,\n isStorybookStory as k,\n removeComponentExtension as l,\n getEntryPointHash as m,\n namespaceModulePropsShape as n,\n getEntryPointHashWithIndexSuffix as o,\n getCombinedReactUrl as p,\n getIslandRuntimeConfigUrl as q,\n resolveIslandPlugin as r,\n setIn as s,\n scriptTagToLogServerMessages as t,\n includesHublDataReference as u,\n virtualClientRenderIslandModuleId as v,\n removeIndexFromPath as w,\n removeIndexOrTrailingJsFromPath as x,\n getCMSAssetConfig as y,\n getCMSAssetConfigIfExists as z\n};\n", "import { I as jsonStringifyAndEscapeForInlineJS, t as scriptTagToLogServerMessages } from \"./types-CsJ4tzsl.js\";\nimport { J, N, E, K, G, M, L, V, A, h, c, d, B, H, f, a, b, Q, P, y, z, p, i, m, o, q, C, j, u, k, O, D, n, l, w, x, r, g, e, s, F, v } from \"./types-CsJ4tzsl.js\";\nimport * as dotProp from \"dot-prop\";\nimport * as parser from \"@babel/parser\";\nimport _traverse from \"@babel/traverse\";\nimport * as t from \"@babel/types\";\nimport { jsx } from \"react/jsx-runtime\";\nimport stream from \"stream\";\nimport { renderToPipeableStream, renderToStaticMarkup } from \"react-dom/server\";\nimport * as cmsComponents from \"@hubspot/cms-components\";\nimport { ServerRenderContext } from \"@hubspot/cms-components\";\nimport { isValidElement, cloneElement } from \"react\";\nconst { setProperty, getProperty, hasProperty } = dotProp;\nconst serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {\n const islandsArrayToSerialize = tweakedIslandsArray.map(\n ({\n id,\n moduleName,\n moduleId,\n props,\n hydrateOn,\n clientOnly,\n priority,\n url,\n sharedStateID,\n supplementalFieldValues,\n wrapperModuleId,\n wrapperUrl\n }) => {\n const output = {\n id,\n moduleName,\n moduleId,\n hydrateOn,\n clientOnly,\n priority,\n props,\n url\n };\n if (sharedStateID) {\n output.sharedStateID = sharedStateID;\n }\n if (wrapperModuleId) {\n output.wrapperModuleId = wrapperModuleId;\n }\n if (wrapperUrl) {\n output.wrapperUrl = wrapperUrl;\n }\n const filteredSupplementalFieldValues = filterOutUnreadSupplementalFieldValues(\n supplementalFieldValues,\n perServerRequestData.get(\"supplementalFieldValuesRead\")\n );\n if (filteredSupplementalFieldValues) {\n output.supplementalFieldValues = filteredSupplementalFieldValues;\n }\n if (isUngatedForClientOnlySupplementalFieldSerialization && output.clientOnly) {\n output.supplementalFieldValues = supplementalFieldValues;\n }\n if (output.supplementalFieldValues) {\n output.supplementalFieldValues = Object.keys(\n output.supplementalFieldValues\n ).sort().reduce((acc, key) => {\n acc[key] = output.supplementalFieldValues[key];\n return acc;\n }, {});\n }\n return output;\n }\n );\n return jsonStringifyAndEscapeForInlineJS(islandsArrayToSerialize, {\n baseIndent,\n jsonIndent: 2,\n prettyPrint\n });\n};\nfunction filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {\n if (!supplementalFieldValues) {\n return supplementalFieldValues;\n }\n if (!supplementalFieldValuesRead) {\n return supplementalFieldValues;\n }\n const result = {};\n Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {\n if (hasProperty(supplementalFieldValues, fieldPath)) {\n setProperty(\n result,\n fieldPath,\n getProperty(supplementalFieldValues, fieldPath)\n );\n }\n });\n return result;\n}\nconst writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0, prettyPrint) => {\n const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x2) => !!x2);\n if (sharedStateIDs.length > 0) {\n const indentString = \" \".repeat(indent);\n const stateByID = {};\n sharedStateIDs.forEach(\n (id) => stateByID[id] = perServerRequestData.get(id)\n );\n const stringifiedState = jsonStringifyAndEscapeForInlineJS(stateByID, {\n prettyPrint,\n jsonIndent: 2\n });\n return `\n\nvar newState = ${stringifiedState};\nif(window.__hsSSInit) {\n window.__hsSSInit = Object.assign(window.__hsSSInit, newState);\n} else {\n window.__hsSSInit = newState;\n}`.replace(/\\n/gm, `\n${indentString}`);\n }\n return \"\";\n};\nfunction getIslandUrls(roots, viteDevServer) {\n return roots.map((island) => {\n const islandModule = viteDevServer.moduleGraph.getModuleById(\n island.moduleId\n );\n if (!islandModule) {\n throw new Error(`Unknown island moduleId: ${island.moduleId}`);\n }\n let wrapperModule;\n if (island.wrapperModuleId) {\n wrapperModule = viteDevServer.moduleGraph.getModuleById(\n island.wrapperModuleId\n );\n }\n const tweakedIsland = {\n ...island,\n url: islandModule.url,\n wrapperUrl: wrapperModule ? wrapperModule.url : void 0\n };\n return tweakedIsland;\n });\n}\nfunction getPerServerRequestUrls(perServerRequestData, viteDevServer) {\n if (!perServerRequestData.has(\"sharedStateIDs\")) {\n return new Map(perServerRequestData);\n }\n const perServerRequestDataWithUrls = new Map(\n perServerRequestData\n );\n perServerRequestData.get(\"sharedStateIDs\").forEach((id) => {\n const reducer = perServerRequestData.get(id);\n if (reducer.reducerFuncModuleId) {\n const reducerWithUrl = {\n ...reducer,\n reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(\n reducer.reducerFuncModuleId\n ).url\n };\n perServerRequestDataWithUrls.set(id, reducerWithUrl);\n }\n });\n return perServerRequestDataWithUrls;\n}\nconst createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint, isUngatedForClientOnlySupplementalFieldSerialization = false) => {\n const islands = getIslandUrls(roots, viteDevServer);\n const perServerRequestDataWithUrls = getPerServerRequestUrls(\n perServerRequestData,\n viteDevServer\n );\n return `${\" \".repeat(\n indent\n )}window.__islands = ${serializeIslandDataForInlineScript(\n islands,\n perServerRequestData,\n indent,\n prettyPrint,\n isUngatedForClientOnlySupplementalFieldSerialization\n )}${writeSharedStateToJsGlobal(\n islands,\n perServerRequestDataWithUrls,\n indent,\n prettyPrint\n )}`;\n};\nfunction noncePlaceholderPlugin() {\n const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === \"true\";\n return {\n name: \"hs-nonce-placeholder\",\n enforce: \"post\",\n apply() {\n return HS_DEPLOYED;\n },\n transformIndexHtml(html) {\n const regex = /<(style|script|link) (.*)>/gi;\n const replacer = (_, p1, p2) => {\n if (p1 === \"style\" || p1 === \"script\" || // if link, only nonce for stylesheet\n p1 === \"link\" && p2.includes('rel=\"stylesheet\"')) {\n const noncePlaceholderValue = p1 === \"script\" ? \"hs-random-nonce\" : \"hs-random-style-nonce\";\n p2 = `nonce=\"${noncePlaceholderValue}\" ${p2}`;\n }\n return `<${p1} ${p2}>`;\n };\n return html.replace(regex, replacer);\n }\n };\n}\nconst traverse = _traverse.default;\nconst CMS_MODULE_COMPONENT_NAME = \"Module\";\nconst DND_AREA_COMPONENT_NAME = \"DndArea\";\nconst PLUGIN_NAME = \"findCmsModules\";\nfunction findCmsModules(buildContentDescriptors = {}) {\n let config;\n return {\n enforce: \"pre\",\n name: \"findCmsModules\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n },\n transform(code, id) {\n const moduleInfo = this.getModuleInfo(id);\n if (!shouldAnalyzeModule(config, moduleInfo, code)) return null;\n const contentDescriptors = analyzeSourceCodeUsages(\n this,\n moduleInfo,\n config,\n code\n );\n if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {\n return {\n meta: {\n findCmsModules: contentDescriptors\n }\n };\n }\n },\n buildEnd(error) {\n if (error) throw error;\n const entryPoints = getEntryPoints(this, config);\n const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(\n this,\n entryPoints\n );\n const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(\n config,\n entryPointCmsModuleMap\n );\n const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(\n this,\n entryPoints\n );\n const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(\n config,\n entryPointIslandCmsModuleMap\n );\n if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {\n this.error(`\n Error: <Module /> cannot be used within <Island />\n Found invalid usages:\n ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}\n `);\n }\n const modulesWithinModules = filterEntryPointsToModules(\n relativeEntryPointCmsModuleMap\n );\n if (Object.keys(modulesWithinModules).length > 0) {\n this.error(`\n Error: <Module /> can only be used in React Partials\n Found invalid usages:\n ${JSON.stringify(modulesWithinModules, null, 2)}\n `);\n }\n Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);\n }\n };\n}\nfunction convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {\n const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(\n ([entryPointPath, cmsModules]) => {\n return [toRelativePath(config, entryPointPath), cmsModules];\n }\n );\n return Object.fromEntries(relativeEntries);\n}\nfunction convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {\n const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(\n ([entryPointPath, islandContentDescriptors]) => {\n const islandCmsModuleUsage = Object.fromEntries(\n Object.entries(islandContentDescriptors).map(\n ([islandPath, contentDescriptors]) => {\n return [\n toRelativePath(config, islandPath).replace(\"?client-entry\", \"\"),\n contentDescriptors\n ];\n }\n )\n );\n return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];\n }\n );\n return Object.fromEntries(relativeEntries);\n}\nfunction toRelativePath(config, path) {\n return path.replace(`${config.root}/`, \"\");\n}\nfunction shouldAnalyzeModule(config, moduleInfo, code) {\n const [fileId, __] = moduleInfo.id.split(\"?\");\n const isExternal = config.command !== \"serve\" && moduleInfo.isExternal;\n return (\n // analyze customer code only\n !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain \"Module\" / \"DndArea\"\n (fileId.endsWith(\".tsx\") || fileId.endsWith(\".jsx\")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))\n );\n}\nfunction getEntryPoints(ctx, config) {\n return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);\n}\nfunction buildEntryPointsCmsModuleMap(ctx, entryPoints) {\n const entryPointCmsModuleUsage = {};\n for (const entryPoint of entryPoints) {\n const result = findCmsModuleUsages(ctx, entryPoint.id);\n if (result) {\n entryPointCmsModuleUsage[entryPoint.id] = result;\n }\n }\n return entryPointCmsModuleUsage;\n}\nfunction buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {\n const entryPointIslandsCmsModuleMap = {};\n for (const entryPoint of entryPoints) {\n const result = findIslandCmsModuleUsage(ctx, entryPoint.id);\n if (result) {\n entryPointIslandsCmsModuleMap[entryPoint.id] = result;\n }\n }\n return entryPointIslandsCmsModuleMap;\n}\nfunction analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {\n const sourceAst = parser.parse(code, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"]\n });\n const contentDescriptors = { modules: {}, dndAreas: {} };\n let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;\n let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;\n traverse(sourceAst, {\n ImportDeclaration(path) {\n if (t.isStringLiteral(path.node.source, {\n value: \"@hubspot/cms-components\"\n })) {\n for (const specifier of path.node.specifiers) {\n if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {\n name: CMS_MODULE_COMPONENT_NAME\n })) {\n moduleComponentLocalImportName = specifier.local.name;\n }\n if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {\n name: DND_AREA_COMPONENT_NAME\n })) {\n dndAreaComponentLocalImportName = specifier.local.name;\n }\n }\n }\n },\n JSXOpeningElement(path) {\n if (t.isJSXIdentifier(path.node.name, {\n name: moduleComponentLocalImportName\n })) {\n let cmsModuleName;\n let cmsModulePath;\n let cmsModuleLabel;\n for (const prop of path.node.attributes) {\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"name\" }) && t.isStringLiteral(prop.value)) {\n cmsModuleName = prop.value.value;\n continue;\n }\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"path\" }) && t.isStringLiteral(prop.value)) {\n cmsModulePath = prop.value.value;\n continue;\n }\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"label\" }) && t.isStringLiteral(prop.value)) {\n cmsModuleLabel = prop.value.value;\n continue;\n }\n ctx.error(\n new Error(\n `Error: ${moduleInfo.id.replace(config.root, \"\")}:${prop.loc.start.line} \"name\" and \"path\" must be primitive strings`\n )\n );\n }\n const cmsModuleProps = {\n name: cmsModuleName,\n path: cmsModulePath\n };\n if (cmsModuleLabel) {\n cmsModuleProps.label = cmsModuleLabel;\n }\n if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {\n ctx.error(\n new Error(\n `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`\n )\n );\n }\n contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;\n }\n if (t.isJSXIdentifier(path.node.name, {\n name: dndAreaComponentLocalImportName\n })) {\n let dndAreaName;\n for (const prop of path.node.attributes) {\n if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: \"name\" }) && t.isStringLiteral(prop.value)) {\n dndAreaName = prop.value.value;\n continue;\n }\n ctx.error(\n new Error(\n `Error: ${moduleInfo.id.replace(config.root, \"\")}:${prop.loc.start.line} \"name\" must a primitive string`\n )\n );\n }\n const dndArea = {\n name: dndAreaName\n };\n if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {\n ctx.error(\n new Error(\n `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`\n )\n );\n }\n contentDescriptors.dndAreas[dndArea.name] = dndArea;\n }\n }\n });\n return contentDescriptors;\n}\nfunction findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {\n if (Object.hasOwn(result, moduleId)) {\n return result[moduleId];\n }\n const moduleInfo = ctx.getModuleInfo(moduleId);\n let entryPointContentDescriptors = null;\n if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {\n entryPointContentDescriptors = {\n ...entryPointContentDescriptors,\n ...moduleInfo.meta[PLUGIN_NAME]\n };\n }\n for (const importedId of [\n ...moduleInfo.importedIds,\n ...moduleInfo.dynamicallyImportedIds\n ]) {\n if (processed.has(importedId)) {\n continue;\n }\n const importedResult = findCmsModuleUsages(\n ctx,\n importedId,\n processed,\n result\n );\n if (importedResult) {\n entryPointContentDescriptors = {\n ...entryPointContentDescriptors,\n ...importedResult\n };\n }\n }\n if (entryPointContentDescriptors) {\n result[moduleId] = entryPointContentDescriptors;\n }\n processed.add(moduleId);\n return entryPointContentDescriptors;\n}\nfunction findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {\n processedIslands.add(moduleId);\n if (Object.hasOwn(islandModuleResults, moduleId)) {\n return islandModuleResults[moduleId];\n }\n const moduleInfo = ctx.getModuleInfo(moduleId);\n let resultForModuleId = {};\n if (moduleInfo.id.endsWith(\"?client-entry\")) {\n const mergedDataDependencies = findCmsModuleUsages(\n ctx,\n moduleInfo.id,\n processed,\n results\n );\n if (mergedDataDependencies) {\n resultForModuleId[moduleInfo.id] = mergedDataDependencies;\n }\n }\n for (const importedId of [\n ...moduleInfo.importedIds,\n ...moduleInfo.dynamicallyImportedIds\n ]) {\n if (processedIslands.has(importedId)) {\n continue;\n }\n const importerCmsModuleUsageResult = findIslandCmsModuleUsage(\n ctx,\n importedId,\n processedIslands,\n islandModuleResults,\n processed,\n results\n );\n if (importerCmsModuleUsageResult) {\n resultForModuleId = {\n ...resultForModuleId,\n ...importerCmsModuleUsageResult\n };\n }\n }\n if (Object.keys(resultForModuleId).length > 0) {\n islandModuleResults[moduleId] = resultForModuleId;\n return resultForModuleId;\n }\n return null;\n}\nfunction filterEntryPointsToModules(entryPointCmsModuleMap) {\n return Object.fromEntries(\n Object.entries(entryPointCmsModuleMap).filter(\n ([entryPoint]) => entryPoint.startsWith(\"components/modules/\")\n )\n );\n}\nconst promiseForNewWritableStream = () => {\n const chunks = [];\n const writableStream = new stream.Writable();\n writableStream._write = (chunk, encoding, done) => {\n chunks.push(Buffer.from(chunk));\n done();\n };\n const streamDonePromise = new Promise((resolve, reject) => {\n writableStream.on(\"error\", (error) => {\n reject(error);\n });\n writableStream._final = (done) => {\n resolve(Buffer.concat(chunks).toString(\"utf8\"));\n done();\n };\n });\n return { streamDonePromise, writableStream };\n};\nconst renderStreamToPromise = async (reactElements, options) => {\n const { streamDonePromise, writableStream } = promiseForNewWritableStream();\n const {\n pipe\n /* abort */\n } = renderToPipeableStream(reactElements, {\n ...options || {},\n onShellReady() {\n },\n onAllReady() {\n pipe(writableStream);\n if (options == null ? void 0 : options.onAllReady) {\n options.onAllReady();\n }\n }\n });\n return streamDonePromise;\n};\nconst {\n createServerRenderContextV2,\n createServerRenderContext,\n renderServerSidePropsWithAsyncLocalStoreContext\n} = cmsComponents;\nconst bootStrapRenderContext = () => {\n const renderContext = createServerRenderContextV2 ? createServerRenderContextV2(null, {\n environmentConfig: null,\n entryPointBasePath: \"\",\n supplementalFieldValues: {},\n messagesForBrowser: []\n }) : createServerRenderContext(\"\", null);\n return renderContext;\n};\nasync function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {\n const { props } = propsAndDeps;\n const componentDebugName = Component.displayName || Component.name;\n const supplementalFieldValues = contextOptions == null ? void 0 : contextOptions.supplementalFieldValues;\n const messagesForBrowser = contextOptions == null ? void 0 : contextOptions.messagesForBrowser;\n const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {\n environmentConfig,\n entryPointBasePath,\n supplementalFieldValues,\n messagesForBrowser\n }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);\n if (getServerSideProps !== void 0 && typeof getServerSideProps === \"function\") {\n const gSSPResult = await renderServerSidePropsWithAsyncLocalStoreContext(\n getServerSideProps,\n propsAndDeps,\n renderContext\n );\n if (gSSPResult) {\n props.serverSideProps = gSSPResult.serverSideProps;\n }\n }\n return renderOnServer(\n /* @__PURE__ */ jsx(Component, { ...props }),\n renderContext,\n componentDebugName,\n renderOptions\n );\n}\nasync function renderOnServer(elements, renderContext = bootStrapRenderContext(), debugName, renderOptions) {\n let html = await renderStreamToPromise(\n /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }),\n renderOptions\n );\n if (renderContext.messagesForBrowser.length > 0) {\n html = `${html}${scriptTagToLogServerMessages(\n renderContext.messagesForBrowser,\n `Server messages rendering: ${debugName}`\n )}`;\n }\n return { html, renderContext };\n}\nfunction getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {\n if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {\n prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);\n }\n const serializedJson = jsonStringifyAndEscapeForInlineJS(\n environmentConfig.toJSON(),\n { baseIndent: 6, prettyPrint }\n );\n const globals = [`window.__hsEnvConfig = ${serializedJson};`];\n if (hsServerPageUrl) {\n globals.push(\n `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(\n hsServerPageUrl\n )};`\n );\n }\n if (hsBasePath) {\n globals.push(\n `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`\n );\n }\n if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {\n const firstCriticalDevError = criticalDevErrors[0];\n globals.push(`\n customElements.whenDefined('vite-error-overlay').then(() => {\n const ErrorOverlay = customElements.get('vite-error-overlay');\n const error = new Error(${jsonStringifyAndEscapeForInlineJS(\n firstCriticalDevError.message\n )});\n const overlay = new ErrorOverlay(error);\n\n document.body.appendChild(overlay);\n })\n `);\n }\n const nonceAttr = includeNonces && cmsComponents.SCRIPT_NONCE_PLACEHOLDER ? ` nonce=\"${cmsComponents.SCRIPT_NONCE_PLACEHOLDER}\"` : \"\";\n return `\n <script type=\"text/javascript\"${nonceAttr}>\n ${globals.join(\"\\n \")}\n <\\/script>\n `;\n}\nfunction renderFieldsJSX(fieldsJSX) {\n let moduleJson;\n const outputCallback = (callbackJson) => {\n moduleJson = callbackJson;\n };\n renderToStaticMarkup(\n cloneElement(fieldsJSX, {\n outputCallback\n })\n );\n if (!moduleJson) {\n throw new Error(\"couldn't render module fields definition to fields.json\");\n }\n return moduleJson;\n}\nfunction renderFieldsToJson(fields, moduleName) {\n let fieldsJSON;\n try {\n if (isValidElement(fields)) {\n fieldsJSON = renderFieldsJSX(fields);\n } else if (Array.isArray(fields)) {\n fieldsJSON = fields;\n } else {\n throw new Error(\n `Couldn't recognize \\`fields\\` value for module ${moduleName}`\n );\n }\n return fieldsJSON;\n } catch (e2) {\n e2.message = `Error when rendering fields for ${moduleName}: ${e2.message}`;\n throw e2;\n }\n}\nexport {\n J as COMPONENT_EXTENSIONS,\n N as CSS_LANGS_RE,\n E as ENABLED_FEATURES_GATE_MAP,\n K as ENTRY_POINTS_PATH,\n G as GATES,\n M as MODULE_FOLDER_PATH,\n L as VIRTUAL_CONFIG_SETUP,\n V as VIRTUAL_ISLAND_RUNTIME,\n A as areBuildHealthChecksEnabled,\n h as clientIslandEntryPlugin,\n c as collectCssInDev,\n d as collectCssModules,\n createIslandsGlobalJsForClientInDev,\n B as doHealthChecksFailTheBuild,\n H as escapeForInlineJS,\n f as findAllComponentsIn,\n a as findAllModulesInRoot,\n b as findAllPartialsInRoot,\n findCmsModules,\n Q as getBaseAssetUrlFromBuild,\n P as getBuildInfo,\n y as getCMSAssetConfig,\n z as getCMSAssetConfigIfExists,\n p as getCombinedReactUrl,\n i as getComponentExtension,\n m as getEntryPointHash,\n o as getEntryPointHashWithIndexSuffix,\n q as getIslandRuntimeConfigUrl,\n getIslandUrls,\n getServerGlobalsToInject,\n C as getServerIncludePrebundleDepPatterns,\n j as hasComponentExtension,\n u as includesHublDataReference,\n k as isStorybookStory,\n O as isStylesheetAsset,\n D as isUngatedFor,\n jsonStringifyAndEscapeForInlineJS,\n n as namespaceModulePropsShape,\n noncePlaceholderPlugin,\n l as removeComponentExtension,\n w as removeIndexFromPath,\n x as removeIndexOrTrailingJsFromPath,\n renderComponentOnServer,\n renderFieldsToJson,\n renderOnServer,\n renderStreamToPromise,\n r as resolveIslandPlugin,\n g as resolveIslandToPlainModuleNoopPlugin,\n e as resolveIslandToPlainModulePlugin,\n scriptTagToLogServerMessages,\n serializeIslandDataForInlineScript,\n s as setIn,\n F as ungatedAtBuildTimeFor,\n v as virtualClientRenderIslandModuleId\n};\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable consistent-return */\n\nimport { COMPONENT_EXTENSIONS } from '@hubspot/cms-js-internal';\n\nexport const findFullPathInModuleGraph = (\n modulePathNoExtension: string,\n moduleGraph: any\n): string | void => {\n for (const extension of COMPONENT_EXTENSIONS) {\n const pathToTry = `${modulePathNoExtension}${extension}`;\n if (moduleGraph.fileToModulesMap.has(pathToTry)) {\n return pathToTry;\n }\n }\n};\n", "import { ViteDevServer } from 'vite';\n\nimport {\n hasComponentExtension,\n removeComponentExtension,\n ENTRY_POINTS_PATH,\n MODULE_FOLDER_PATH,\n} from '@hubspot/cms-js-internal';\n\nimport { findFullPathInModuleGraph } from './moduleGraph.js';\n\nexport const getComponentPaths = (\n viteServer: ViteDevServer,\n componentPath: string\n): [componentPathNoExtension: string, componentPathWithExtension: string] => {\n let componentPathWithExtension;\n let componentPathNoExtension;\n\n // Support paths with or without an extension (do we need/want both?)\n if (hasComponentExtension(componentPath)) {\n componentPathWithExtension = componentPath;\n componentPathNoExtension = removeComponentExtension(componentPath);\n } else {\n componentPathNoExtension = componentPath;\n }\n\n if (!componentPathWithExtension) {\n componentPathWithExtension = findFullPathInModuleGraph(\n componentPathNoExtension,\n viteServer.moduleGraph\n );\n if (!componentPathWithExtension) {\n throw new Error(\n `Couldn't find full path to component: ${componentPathNoExtension}`\n );\n }\n }\n\n return [componentPathNoExtension, componentPathWithExtension];\n};\n\nexport const getEntryPointBasePath = (componentPath: string): string => {\n if (componentPath.includes(ENTRY_POINTS_PATH)) {\n return `partial/${componentPath.split(ENTRY_POINTS_PATH)[1]}`;\n }\n\n if (componentPath.includes(MODULE_FOLDER_PATH)) {\n return `module/${componentPath.split(MODULE_FOLDER_PATH)[1]}`;\n }\n\n throw new Error('Unknown entry point path type');\n};\n", "function getByteSizeOf(props: any) {\n return Buffer.from(JSON.stringify(props)).length;\n}\n\nfunction formatBytesToString(bytes) {\n if (bytes > 1000000) {\n // If byte size is > 1mb, show size in red\n return ['\\x1b[31m', `${(bytes / 1000000).toFixed(2)}mb`, `\\x1b[0m`];\n } else if (bytes > 10000) {\n // if byte size is between 10kb and 1mb, show size in yellow\n return ['\\x1b[33m', `${(bytes / 1000).toFixed(2)}kb`, `\\x1b[0m`];\n } else {\n // Show size in green\n return ['\\x1b[32m', `${(bytes / 1000).toFixed(2)}kb`, `\\x1b[0m`];\n }\n}\n\nconst getPropsInfo = (\n props,\n reportOptions = { showNestedKeySizeIfGreater: null },\n recursionDepth = 0\n) => {\n if (recursionDepth > 8) {\n return [];\n }\n\n const propsSizeInBytes = getByteSizeOf(props);\n const result = formatBytesToString(propsSizeInBytes);\n\n if (\n !Array.isArray(props) &&\n Object.keys(props).length > 0 &&\n reportOptions.showNestedKeySizeIfGreater != null &&\n propsSizeInBytes > reportOptions.showNestedKeySizeIfGreater\n ) {\n for (const [key, value] of Object.entries(props)) {\n const size = getPropsInfo(value, reportOptions, recursionDepth + 1);\n\n if (Array.isArray(value)) {\n result.push('\\n', `${key}[${value.length}]`, ...size);\n } else {\n result.push('\\n', key, ...size);\n }\n }\n }\n\n return result.flat();\n};\n\nexport const logPartialInfo = (partialPath, props) => {\n console.log('Rendering partial', partialPath);\n console.group();\n console.log(\n 'Props size: ',\n ...getPropsInfo(props, { showNestedKeySizeIfGreater: 1000000 })\n );\n console.groupEnd();\n};\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable @typescript-eslint/no-shadow */\n\nimport { ViteDevServer } from 'vite';\nimport { promises as fsPromises } from 'fs';\nimport {\n createIslandsGlobalJsForClientInDev,\n getServerGlobalsToInject,\n scriptTagToLogServerMessages,\n} from '@hubspot/cms-js-internal';\nimport {\n ServerRenderContextValue,\n isDebugUrlString,\n} from '@hubspot/cms-components';\nimport packagePath from './packagePath.js';\nimport criticalDevErrorsToServerMessages from './criticalDevErrorsToServerMessages.js';\n\nconst { readFile } = fsPromises;\n\nconst getIsUngatedForClientOnlySupplementalFieldSerialization = (\n gates: string[]\n) => {\n return gates.includes(\n 'CMS:JSRenderer:ClientOnlySupplementalFieldSerialization'\n );\n};\n\nconst generateIslandSetupScriptBlock = () => {\n return `\n <script type=\"module\">\n import { initConfigSingletonFromJSON } from '@hubspot/cms-components/config';\n initConfigSingletonFromJSON(window.__hsEnvConfig);\n </script>\n <script type=\"module\">\n import { setupIslandHydration } from '${packagePath(\n import.meta.url,\n 'island-runtime'\n )}';\n setupIslandHydration();\n </script>\n `;\n};\n\nconst createdPlainHtmlTemplate = async (\n baseTemplatePath: string,\n title: string,\n globalScriptBlock: string\n): Promise<string> => {\n const htmlTemplateBase = await readFile(baseTemplatePath, 'utf-8');\n return htmlTemplateBase.replace('<!--title-->', title).replace(\n '<!--bodyend-->',\n `\n ${globalScriptBlock}\n <!--bodyend-->`\n );\n};\n\nconst createIslandHtmlTemplate = async (\n baseTemplatePath: string,\n title: string,\n globalScriptBlock: string\n): Promise<string> => {\n let htmlTemplate = await createdPlainHtmlTemplate(\n baseTemplatePath,\n title,\n globalScriptBlock\n );\n\n htmlTemplate = htmlTemplate.replace(\n '<!--bodyend-->',\n `\n ${generateIslandSetupScriptBlock()}\n <!-- ISLAND_RUNTIME_AND_SETUP_SCRIPT_BLOCK -->\n <!--islandsglobal-->\n `\n );\n\n return htmlTemplate;\n};\n\nexport const createHtmlShellDependingOnRenderContext = async (\n baseTemplatePath: string,\n url: string,\n title: string,\n renderContext: ServerRenderContextValue,\n viteServer: ViteDevServer,\n jsRenderingGates: string[]\n) => {\n let htmlTemplate;\n const prettyPrint = isDebugUrlString(url);\n const serverMessages = criticalDevErrorsToServerMessages(\n renderContext.criticalDevErrors\n );\n const serverLogScript = serverMessages.length\n ? scriptTagToLogServerMessages(\n serverMessages,\n '@hubspot/cms-dev-server messages'\n )\n : '';\n\n if (renderContext.islands.length) {\n const globalScriptBlock = getServerGlobalsToInject(\n renderContext.environmentConfig,\n renderContext.pageUrl,\n renderContext.entryPointBasePath,\n undefined,\n renderContext.criticalDevErrors\n );\n\n htmlTemplate = await createIslandHtmlTemplate(\n baseTemplatePath,\n title,\n `${globalScriptBlock}${serverLogScript}`\n );\n\n const isUngatedForClientOnlySupplementalFieldSerialization =\n getIsUngatedForClientOnlySupplementalFieldSerialization(jsRenderingGates);\n\n htmlTemplate = htmlTemplate.replace(\n '<!--islandsglobal-->',\n `<script>\n ${createIslandsGlobalJsForClientInDev(\n renderContext.islands,\n renderContext.perServerRequestData,\n viteServer,\n 6,\n prettyPrint,\n isUngatedForClientOnlySupplementalFieldSerialization\n )}\n </script>\n `\n );\n } else {\n const globalScriptBlock = getServerGlobalsToInject(\n renderContext.environmentConfig,\n undefined,\n undefined,\n undefined,\n renderContext.criticalDevErrors\n );\n\n htmlTemplate = await createdPlainHtmlTemplate(\n baseTemplatePath,\n title,\n `${globalScriptBlock}${serverLogScript}`\n );\n }\n\n return viteServer.transformIndexHtml(url, htmlTemplate);\n};\n\nexport const getIslandRuntimeAndGlobalToInject = async (\n sortedIslandRoots,\n perServerRequestData,\n viteServer: ViteDevServer,\n gates: string[],\n prettyPrint: boolean\n) => {\n // Loading through vite so all of nested `@hubspot/cms-*` imports work\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n\n const { createIslandsGlobalJsForClientInDev } =\n await viteServer.ssrLoadModule(internalSsrPath);\n\n const islandRuntimeScript = await viteServer.transformIndexHtml(\n '/',\n generateIslandSetupScriptBlock()\n );\n\n const isUngatedForClientOnlySupplementalFieldSerialization =\n getIsUngatedForClientOnlySupplementalFieldSerialization(gates);\n\n return `${islandRuntimeScript}\n <script>${createIslandsGlobalJsForClientInDev(\n sortedIslandRoots,\n perServerRequestData,\n viteServer,\n 4,\n prettyPrint,\n isUngatedForClientOnlySupplementalFieldSerialization\n )}</script>\n `;\n};\n", "import { LogMessage } from '@hubspot/cms-components';\nimport { CriticalDevError } from '@hubspot/cms-components';\n\nconst criticalDevErrorsToServerMessages = (\n criticalDevErrors: Array<CriticalDevError>\n): Array<LogMessage> => {\n const logMessages = criticalDevErrors.map(\n (criticalDevError: CriticalDevError) => {\n return {\n level: criticalDevError.level,\n parameters: [criticalDevError.message],\n };\n }\n );\n\n return logMessages;\n};\n\nexport default criticalDevErrorsToServerMessages;\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport { getAccountConfig } from '@hubspot/local-dev-lib/config';\nimport axios from 'axios'\n\nimport { getAxiosConfig } from '@hubspot/local-dev-lib/http/getAxiosConfig';\n\nimport { HSEnvironment } from '@hubspot/cms-components';\nimport { debug } from './debug.js';\n\nimport { wrapMessageInColor } from './logColors.js';\n\nconst DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED =\n '/cms-dev-server-usage/v1/authenticated';\nconst DEV_SERVER_USAGE_ENDPOINT = '/cms-dev-server-usage/v1';\nconst EVENT_NAME = 'dev-server-interaction';\n\nlet trackingAccountId = null;\nlet trackingEnv = null;\n\nenum EventClass {\n INTERACTION = 'INTERACTION',\n USAGE = 'USAGE',\n VIEW = 'VIEW',\n ACTIVATION = 'ACTIVATION',\n}\n\ntype UsageEvent = {\n portalId: number;\n eventClass: keyof typeof EventClass;\n eventName: 'dev-server-interaction';\n action: string;\n nodeVersion: string;\n os: string;\n version: string;\n};\n\nconst getPlatform = () => {\n switch (process.platform) {\n case 'darwin':\n return 'macos';\n case 'win32':\n return 'windows';\n default:\n return process.platform;\n }\n};\n\nconst getNodeVersionData = () => process.version;\n\nfunction trackUsage(action: string) {\n const accountConfig =\n trackingAccountId && getAccountConfig(trackingAccountId);\n const isAuthedWithPersonalAccessKey =\n accountConfig && accountConfig.authType === 'personalaccesskey';\n\n const usageEvent: UsageEvent = {\n portalId: trackingAccountId,\n eventClass: EventClass.INTERACTION,\n eventName: EVENT_NAME,\n action,\n nodeVersion: getNodeVersionData(),\n version: process.env.APP_VERSION,\n os: getPlatform(),\n };\n\n const url = isAuthedWithPersonalAccessKey\n ? DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED\n : DEV_SERVER_USAGE_ENDPOINT;\n\n const baseRequestOptions = {\n url,\n data: usageEvent,\n };\n\n if (isAuthedWithPersonalAccessKey) {\n return hsCliHttp.post(trackingAccountId, baseRequestOptions);\n }\n\n const config = getAxiosConfig({\n ...baseRequestOptions,\n env: trackingEnv,\n method: 'POST',\n } as any) as any\n\n return axios(config)\n}\n\nexport const setTrackingInfo = (\n accountId: number | null,\n env: HSEnvironment | null\n) => {\n trackingAccountId = accountId;\n trackingEnv = env;\n};\n\nexport default function sendTrackingRequest(action: string) {\n setImmediate(async () => {\n try {\n await trackUsage(action);\n\n debug(\n wrapMessageInColor(\n 'white',\n `Sent usage tracking action event: ${action}`\n )\n );\n } catch (e) {\n debug(wrapMessageInColor('red', `Usage tracking failed: ${e.message}`));\n }\n });\n}\n", "import { default as debugFactory } from 'debug';\n\nexport const debug = debugFactory('cms-dev-server');\n", "import { buildStaticEnvConfig } from '@hubspot/cms-components';\nimport path from 'path';\nimport { normalizePath } from 'vite';\nimport { getEntryPointBasePath } from '../lib/pathHelpers.js';\nimport { findLocalRenderPlaceholders } from '../lib/proxyHelpers.js';\nimport { renderComponentForPlaceholder } from '../proxyPage/proxyPage.js';\nimport packagePath from '../lib/packagePath.js';\nimport { hasComponentExtension } from '@hubspot/cms-js-internal';\nimport { lookForModuleInFolder } from '../lib/renderModule.js';\nimport { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport jsdom from 'jsdom';\nimport { getFieldValuesForModule } from './getFieldValuesForModule.js';\n\nconst { JSDOM } = jsdom;\n\nexport async function renderRemoteModulePreview(\n modulePath: string,\n authedPortalId: any,\n authedEnv: any,\n cookieValue: any\n) {\n const moduleInfoQueryParams = new URLSearchParams({\n portalId: `${authedPortalId}`,\n });\n const moduleInfo = (\n await hsCliHttp.get<any>(authedPortalId, {\n url: `/api/designmanager/v1/modules/by-path/${encodeURIComponent(\n modulePath\n )}?${moduleInfoQueryParams}`,\n headers: {\n ['Accept']: 'application/json',\n referer: `https://app.hubspot${authedEnv === 'qa' ? 'qa' : ''}.com`,\n cookie: cookieValue,\n 'User-Agent': 'HubSpot CMS Dev Server',\n },\n })\n ).data;\n\n const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;\n process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;\n\n const queryParams = new URLSearchParams({\n portalId: `${authedPortalId}`,\n hsLocalProxy: `${true}`,\n localProxySchemaVersion: '2',\n hsLoginVerifyDisabled: `${true}`,\n module_id: moduleInfo.moduleId,\n });\n const modulePreviewHtml = (\n await hsCliHttp.get<string>(authedPortalId, {\n url: `/api/cos-rendering/v1/public/_hcms/preview/template/multi?${queryParams}`,\n headers: {\n ['content-type']: 'application/x-www-form-urlencoded',\n ['Accept']: 'text/html',\n referer: `https://app.hubspot${authedEnv === 'qa' ? 'qa' : ''}.com`,\n cookie: cookieValue,\n 'User-Agent': 'HubSpot CMS Dev Server',\n },\n })\n ).data;\n // reset HUBAPI_DOMAIN_OVERRIDE to previous value\n // clear env variable if none previously set\n if (currentHubApiDomainOverride) {\n process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;\n } else {\n delete process.env.HUBAPI_DOMAIN_OVERRIDE;\n }\n\n // Pick module dom node from full document\n const dom = new JSDOM(modulePreviewHtml);\n const modulePreviewContent = dom.window.document.querySelector(\n 'div[data-hs-cos-type=\"module\"]'\n ).outerHTML;\n const cssNeeded = Array.from(dom.window.document.querySelectorAll('style'))\n .map((element) => element.outerHTML)\n .join('');\n\n return { html: modulePreviewContent, cssNeeded };\n}\n\nexport async function renderLocalProjectModulePreview(\n moduleName: string,\n authedPortalId: any,\n authedEnv: any,\n authedHublet: any,\n webRoot: any,\n viteServer: any,\n jsRenderingGates: any,\n projectName: any,\n projectComponentPath: any,\n fullOriginalUrl: any,\n cookieValue: any,\n fieldOverrides = {}\n) {\n const modulePath = normalizePath(\n path.resolve(webRoot, 'components/modules/', moduleName)\n );\n\n const basePath = `preview/${getEntryPointBasePath(modulePath)}`;\n\n const environmentConfig = buildStaticEnvConfig(\n authedPortalId,\n authedHublet,\n authedEnv,\n false,\n jsRenderingGates\n );\n\n // get local fields.json and hublDataTemplate\n let componentModule: any;\n let foundPath: string;\n if (!hasComponentExtension(modulePath)) {\n [componentModule, foundPath] = await lookForModuleInFolder(\n modulePath,\n viteServer\n );\n }\n\n if (!componentModule) {\n // Look for non-folder module\n componentModule = await viteServer.ssrLoadModule(modulePath);\n foundPath = componentModule ? modulePath : undefined;\n }\n\n if (!componentModule) {\n throw new Error(`Couldn't find module: ${modulePath}`);\n }\n const Component = componentModule.Component;\n const fields = componentModule.fields;\n const meta = componentModule.meta;\n const hublDataTemplate = componentModule.hublDataTemplate;\n\n if (!Component) {\n throw new Error(\n `Module does not have a named Component export: ${foundPath}`\n );\n } else if (!fields) {\n throw new Error(`Module does not have a named fields export: ${foundPath}`);\n } else if (!meta) {\n throw new Error(`Module does not have a named meta export: ${foundPath}`);\n }\n\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n const { renderFieldsToJson } =\n await viteServer.ssrLoadModule(internalSsrPath);\n const localFieldsJson = renderFieldsToJson(fields, modulePath);\n const localFieldValues = getFieldValuesForModule(\n localFieldsJson,\n fieldOverrides\n );\n\n // render template preview using local fields.json and hublDataTemplate\n const localModule = {\n isJsModule: true,\n schemaVersion: 2,\n fields: localFieldsJson,\n id: 1,\n path: `@projects/${projectName}/${projectComponentPath}/components/modules/${moduleName}`,\n hublDataTemplate,\n };\n const queryParams = new URLSearchParams({\n portalId: `${authedPortalId}`,\n hsLocalProxy: `${true}`,\n localProxySchemaVersion: '2',\n hsLoginVerifyDisabled: `${true}`,\n });\n\n // this endpoint does not work with default LB from hs cli\n // override LB with api.hubspot\n const currentHubApiDomainOverride = process.env.HUBAPI_DOMAIN_OVERRIDE;\n process.env.HUBAPI_DOMAIN_OVERRIDE = `api.hubspot`;\n\n const templatePreview = (\n await hsCliHttp.post<string>(authedPortalId, {\n url: `/api/cos-rendering/v1/public/_hcms/preview/template/multiform?${queryParams}`,\n headers: {\n ['content-type']: 'application/x-www-form-urlencoded',\n ['Accept']: 'text/html',\n referer: `https://app.hubspot${authedEnv === 'qa' ? 'qa' : ''}.com`,\n cookie: cookieValue,\n 'User-Agent': 'HubSpot CMS Dev Server',\n },\n data: `module=${encodeURIComponent(JSON.stringify(localModule))}`,\n })\n ).data;\n // reset HUBAPI_DOMAIN_OVERRIDE to previous value\n // clear env variable if none previously set\n if (currentHubApiDomainOverride) {\n process.env.HUBAPI_DOMAIN_OVERRIDE = currentHubApiDomainOverride;\n } else {\n delete process.env.HUBAPI_DOMAIN_OVERRIDE;\n }\n\n const localRenderPlaceholders = findLocalRenderPlaceholders(templatePreview);\n\n // Expect only 1 comment on a specific module preview template\n if (localRenderPlaceholders.length !== 1) {\n throw new Error(\n `Error previewing module (${moduleName}), exception in module preview HTML\\n\\n`\n );\n }\n\n localRenderPlaceholders[0].json.props.fieldValues = localFieldValues;\n\n return await renderComponentForPlaceholder(\n 0,\n localRenderPlaceholders[0],\n webRoot,\n viteServer,\n fullOriginalUrl,\n basePath,\n environmentConfig,\n projectName,\n projectComponentPath\n );\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable consistent-return */\n\nimport fs from 'fs';\nimport { resolve } from 'path';\nimport { ModuleProps } from '@hubspot/cms-components';\nimport { unescape } from 'html-escaper';\n\nconst localJsRenderStartString = '<!-- proxy local render of \"';\n// const localJsRenderStartRegex = /<!-- proxy local render of \"([^\"]+)\"/;\nconst localJsRenderEndString = 'end proxy local render -->';\n\ntype BaseJson = {\n props: Record<string, any>;\n request: Record<string, any>;\n};\n\nexport interface LocalRenderBlockInfo {\n startOffset: number;\n endOffset: number;\n path: string;\n json: {\n props: {\n fieldValues?: Record<string, any>;\n hublParameters?: Record<string, any>;\n supplementalFieldValues?: Record<string, any>;\n hublData?: any;\n } & Record<string, any>;\n request: Record<string, any>;\n };\n}\n\nexport type LocalModuleRenderPlaceholderProps = ModuleProps &\n Record<string, any>;\n\nexport interface LocalModuleRenderBlockInfo extends LocalRenderBlockInfo {\n json: {\n props: LocalModuleRenderPlaceholderProps;\n } & BaseJson;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nexport const findLocalRenderPlaceholders = (\n body: string\n): Array<LocalRenderBlockInfo> => {\n let offsetSoFar = 0;\n const result: Array<LocalRenderBlockInfo> = [];\n\n while (offsetSoFar < body.length && offsetSoFar !== -1) {\n // Get start of local render block\n const startOffset = body.indexOf(localJsRenderStartString, offsetSoFar);\n offsetSoFar = startOffset;\n\n if (startOffset >= 0) {\n const nextNewlineOffset = body.indexOf(\n '\\n',\n startOffset + localJsRenderStartString.length\n );\n const pathEndOffset = body.indexOf(\n '\"',\n startOffset + localJsRenderStartString.length\n );\n const nearestNewlineOrQuoteAfterBlockOpen = Math.min(\n nextNewlineOffset,\n pathEndOffset\n );\n\n // Keep on moving our \"where we've scanned so far\" pointer\n offsetSoFar = nearestNewlineOrQuoteAfterBlockOpen;\n\n if (pathEndOffset >= 0 && pathEndOffset < nextNewlineOffset) {\n // Pull the path out of double quotes after the block opening\n const path = body.substring(\n startOffset + localJsRenderStartString.length,\n pathEndOffset\n );\n offsetSoFar = pathEndOffset + 1;\n\n // console.log(`${startOffset}: path = ${path}`);\n\n // If we're in a valid bloc so far that exists and has a path...\n if (startOffset >= 0 && path) {\n const nextCommentEndOffset = body.indexOf('-->', pathEndOffset);\n const endOffset = body.indexOf(localJsRenderEndString, pathEndOffset);\n offsetSoFar = Math.min(nextCommentEndOffset, endOffset);\n\n // Make sure that there is an ending to the block and there is not another\n // HTML end comment string before it\n if (endOffset >= startOffset && endOffset < nextCommentEndOffset) {\n // Then pull out the JSON in the middle and try to parse it\n const jsonString = body\n .substring(pathEndOffset + 1, endOffset)\n .trim();\n // console.log(`${endOffset}: jsonString = ${jsonString}`);\n\n try {\n let json: any;\n try {\n json = JSON.parse(unescape(jsonString));\n } catch (e) {\n json = JSON.parse(jsonString);\n }\n\n if (!isRecord(json.request)) {\n console.error(\n `Invalid JSON inside <!-- proxy local render .. --> string (missing request key)`\n );\n } else if (!isRecord(json.props)) {\n console.error(\n `Invalid JSON inside <!-- proxy local render .. --> string (missing props key)`\n );\n } else {\n result.push({\n startOffset,\n endOffset: endOffset + localJsRenderEndString.length,\n path,\n json,\n });\n }\n\n offsetSoFar = endOffset + localJsRenderEndString.length;\n } catch (e) {\n console.error(\n `Invalid JSON inside <!-- proxy local render .. --> string (around offset ${pathEndOffset})`\n );\n offsetSoFar = endOffset;\n }\n }\n }\n }\n }\n }\n\n return result;\n};\n\nexport const getHSProjectConfig = (\n hsProjectConfigPath: string\n): Record<string, any> | null => {\n try {\n return JSON.parse(fs.readFileSync(hsProjectConfigPath, 'utf8'));\n } catch (e) {\n console.warn(\n `Missing hsproject.json file (${resolve(hsProjectConfigPath)}): `,\n e.message\n );\n return null;\n }\n};\n\nexport const getProjectNameFromHSConfig = (\n hsProjectConfigPath: string\n): string => {\n const hsProjectConfig = getHSProjectConfig(hsProjectConfigPath);\n if (hsProjectConfig) {\n return hsProjectConfig.name;\n }\n return null;\n};\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-loop-func */\n\nimport path from 'path';\nimport { Request, Response } from 'express';\nimport { normalizePath, ViteDevServer } from 'vite';\nimport { getAccountId, getEnv } from '@hubspot/local-dev-lib/config';\nimport { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport {\n findLocalRenderPlaceholders,\n LocalModuleRenderBlockInfo,\n LocalRenderBlockInfo,\n} from '../lib/proxyHelpers.js';\nimport renderPartial from '../lib/renderPartial.js';\nimport renderModule from '../lib/renderModule.js';\nimport criticalDevErrorsToServerMessages from '../lib/criticalDevErrorsToServerMessages.js';\nimport { RenderResult } from '../lib/renderComponentWithCSS.js';\nimport { getIslandRuntimeAndGlobalToInject } from '../lib/templates.js';\nimport {\n ENTRY_POINTS_PATH,\n MODULE_FOLDER_PATH,\n getServerGlobalsToInject,\n getEntryPointHashWithIndexSuffix,\n Gate,\n scriptTagToLogServerMessages,\n} from '@hubspot/cms-js-internal';\nimport { fakeRenderJsComponent } from './utils.js';\nimport renderLocalError from './renderLocalError.js';\nimport fetchPreviewInfo from './fetchPreviewInfo.js';\nimport {\n buildStaticEnvConfig,\n EnvironmentConfig,\n Hublet,\n isDebugUrlString,\n mergeServerRequestData_internal,\n} from '@hubspot/cms-components';\nimport { addRefreshScript } from '../lib/previewUtils.js';\n\nexport const getEntryPointBasePathFromProxyRequest = (request): string => {\n if (!request) {\n return '';\n }\n\n const { path: requestPath, pathParamDict } = request;\n\n if (!pathParamDict || !pathParamDict.dynamic_slug) {\n return requestPath;\n }\n\n return requestPath.replace(pathParamDict.dynamic_slug, '');\n};\n\n// Use standard placeholder path if DEFAULT_MODULE_PATH_REWRITE is unset\n// DEFAULT_MODULE_PATH_REWRITE example: @hubspot/blog_posts:BlogPosts.tsx\n// Given a renderer comment proxy path: @default-modules/blog-default-modules/@hubspot/blog_posts\n// Use DEFAULT_MODULE_PATH_REWRITE to rewrite to a locally available module\n// e.g. @blog-default-module/cms-assets/components/modules/BlogPosts.tsx\nfunction resolvePlaceholderPath(\n placeholderPath: string,\n projectName: string,\n projectComponent: string\n) {\n if (!process.env.DEFAULT_MODULE_PATH_REWRITE) {\n return placeholderPath;\n }\n const mappedPlaceholderPath = `@projects/${projectName}/${projectComponent}/components/modules/${\n process.env.DEFAULT_MODULE_PATH_REWRITE.split(':')[1]\n }`;\n\n if (\n placeholderPath.startsWith(`@default-modules/${projectName}/`) &&\n placeholderPath.endsWith(\n process.env.DEFAULT_MODULE_PATH_REWRITE.split(':')[0]\n )\n ) {\n return mappedPlaceholderPath;\n }\n return placeholderPath;\n}\n\ntype ProxiedQueryParams = Partial<{\n hs_preview: string;\n hsLocalProxyProject: string;\n localProxySchemaVersion: string;\n hsDebugOverridePublicHost: string;\n hsLoginVerifyDisabled?: string;\n localPreviewToken?: string;\n hsCacheBuster?: string;\n}>;\n\nexport const makeProxyPreviewRequest = (\n accountId: number,\n urlToProxy: string,\n previewKey: string,\n contentId: string,\n projectName: string,\n environmentConfig: EnvironmentConfig,\n __jsRenderingGates: Gate[],\n cookieHeader?: string,\n localPreviewToken?: string\n) => {\n const url = new URL(urlToProxy);\n\n const renderPreviewLocally = url.searchParams.has('renderPreviewLocally');\n let proxiedQueryParams: ProxiedQueryParams = {};\n let baseURL = url.origin;\n let pathname = url.pathname;\n\n // Convert searchParams to object param format hsGet/request expects\n const PARAMS_TO_IGNORE = ['renderPreviewLocally'];\n const queryKeys = Array.from(url.searchParams.keys()).filter(\n (queryKey) => !PARAMS_TO_IGNORE.includes(queryKey)\n );\n\n for (const queryKey of queryKeys) {\n const values = url.searchParams.getAll(queryKey);\n\n if (values.length > 1) {\n proxiedQueryParams[queryKey] = values;\n } else {\n proxiedQueryParams[queryKey] = values[0];\n }\n }\n\n const localProxyProject = process.env.DEFAULT_MODULE_PATH_REWRITE\n ? `@default-modules/${projectName}`\n : `@projects/${projectName}`;\n\n proxiedQueryParams = {\n ...proxiedQueryParams,\n hs_preview: `${previewKey}-${contentId}`,\n hsLocalProxyProject: localProxyProject,\n localProxySchemaVersion: '2',\n hsLoginVerifyDisabled: `${true}`,\n };\n\n if (renderPreviewLocally) {\n proxiedQueryParams.hsDebugOverridePublicHost = url.host;\n baseURL = `http://local.hubspot${\n environmentConfig.getInternalHSEnv() === 'qa' ? 'qa' : ''\n }.com`;\n pathname = `/cos-rendering/v1/public${url.pathname}`;\n }\n\n if (localPreviewToken) {\n proxiedQueryParams = {\n ...proxiedQueryParams,\n localPreviewToken,\n hsCacheBuster: Date.now().toString(),\n };\n delete proxiedQueryParams['hs_preview'];\n }\n\n console.log(\n `Proxying request to ${baseURL}${pathname}?${new URLSearchParams({\n ...proxiedQueryParams,\n previewKey,\n contentId,\n }).toString()}`\n );\n\n try {\n const result = hsCliHttp.get<string>(accountId, {\n baseURL,\n url: pathname,\n params: proxiedQueryParams,\n responseType: 'text',\n headers: {\n COOKIE: cookieHeader,\n },\n })\n return result;\n } catch (error) {\n if (error.status >= 400 && error.status < 500 && !!error.response.data) {\n return error.response.data;\n } else {\n throw error;\n }\n }\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isModulePlaceholder(\n value: unknown\n): value is LocalModuleRenderBlockInfo {\n return (\n isRecord(value) &&\n isRecord(value.json) &&\n isRecord(value.json.props) &&\n isRecord(value.json.props.fieldValues) &&\n isRecord(value.json.props.hublParameters)\n );\n}\n\nexport const renderComponentForPlaceholder = (\n indexForThisRender: number,\n localRenderPlaceholder: LocalRenderBlockInfo,\n webRoot: string,\n viteServer: ViteDevServer,\n pageUrl: string,\n basePath: string,\n environmentConfig: EnvironmentConfig,\n hsProjectJsonProjectName: string,\n webRootProjectComponent: any\n): Promise<RenderResult> => {\n const placeholderPath = resolvePlaceholderPath(\n localRenderPlaceholder.path,\n hsProjectJsonProjectName,\n webRootProjectComponent\n );\n\n const localRenderPlaceholderProps = localRenderPlaceholder.json.props;\n\n const [\n __projectIdentifier,\n projectFolder,\n projectComponentFolder,\n componentFolder,\n componentTypeFolder,\n componentFileName,\n ] = placeholderPath.split('/');\n const partialPath = `${componentFolder}/${componentTypeFolder}/`;\n\n if (projectFolder !== hsProjectJsonProjectName) {\n throw new Error(\n `Unable to render component located outside of the project folder \"${hsProjectJsonProjectName}\". Components should be nested within the project folder. Check that the specified path is correct: ${placeholderPath}.`\n );\n } else if (projectComponentFolder !== webRootProjectComponent) {\n throw new Error(\n `The specified component folder \"${projectComponentFolder}\" does not match the webroot project component folder \"${webRootProjectComponent}/${projectComponentFolder}\" specified to the cms-dev-server. Components must be located within the webroot project folder. Check that the specified path is correct: ${placeholderPath}.`\n );\n }\n\n const resolvedPath = normalizePath(\n path.resolve(webRoot, partialPath, componentFileName)\n );\n const entryPointPath = [\n '@projects',\n webRootProjectComponent,\n projectComponentFolder,\n partialPath,\n componentFileName,\n ].join('/');\n\n if (placeholderPath.startsWith('/fake/path/to/')) {\n return fakeRenderJsComponent(indexForThisRender);\n } else if (partialPath === ENTRY_POINTS_PATH) {\n return renderComponentForPlaceholderPartial(\n viteServer,\n resolvedPath,\n localRenderPlaceholderProps,\n pageUrl,\n basePath,\n environmentConfig,\n entryPointPath,\n indexForThisRender\n );\n } else if (partialPath === MODULE_FOLDER_PATH) {\n if (!isModulePlaceholder(localRenderPlaceholder)) {\n console.error(\n `Skipping local module render of ${componentFileName} <!-- proxy local render .. --> is missing necessary module prop keys (fieldValues? hublParameters?) `\n );\n } else {\n const localModuleRenderPlaceholder: LocalModuleRenderBlockInfo = {\n ...localRenderPlaceholder,\n };\n return renderComponentForPlaceholderModule(\n viteServer,\n resolvedPath,\n localModuleRenderPlaceholder,\n pageUrl,\n basePath,\n environmentConfig,\n entryPointPath,\n indexForThisRender\n );\n }\n } else {\n throw new Error(`Unimplemented render of ${placeholderPath}.`);\n }\n};\n\nfunction renderComponentForPlaceholderPartial(\n viteServer: ViteDevServer,\n resolvedPath: string,\n localRenderPlaceholderProps: Record<string, any>,\n pageUrl: string,\n basePath: string,\n environmentConfig: EnvironmentConfig,\n entryPointPath: string,\n indexForThisRender: number\n): Promise<RenderResult> {\n return renderPartial(\n viteServer,\n resolvedPath,\n localRenderPlaceholderProps,\n pageUrl,\n basePath,\n environmentConfig,\n {\n identifierPrefix: getEntryPointHashWithIndexSuffix(\n entryPointPath,\n indexForThisRender\n ),\n }\n );\n}\n\nfunction renderComponentForPlaceholderModule(\n viteServer: ViteDevServer,\n resolvedPath: string,\n localModuleRenderPlaceholder: LocalModuleRenderBlockInfo,\n pageUrl: string,\n basePath: string,\n environmentConfig: EnvironmentConfig,\n entryPointPath: string,\n indexForThisRender: number\n) {\n return renderModule(\n viteServer,\n resolvedPath,\n localModuleRenderPlaceholder.json.props,\n pageUrl,\n basePath,\n environmentConfig,\n {\n identifierPrefix: getEntryPointHashWithIndexSuffix(\n entryPointPath,\n indexForThisRender\n ),\n }\n );\n}\n\nexport default async function proxySpecificPage(\n request: Request,\n response: Response,\n portalId: number,\n hublet: Hublet,\n contentId: string,\n webRoot: string,\n viteServer: ViteDevServer,\n projectName: string,\n projectComponentPath: string,\n jsRenderingGates: Gate[],\n urlToProxy?: string,\n fullOriginalUrl?: string\n) {\n let accountId;\n let proxyEnv;\n const prettyPrint = isDebugUrlString(urlToProxy);\n\n try {\n accountId = getAccountId(portalId);\n\n if (accountId === null) {\n throw new Error();\n }\n\n proxyEnv = getEnv(accountId);\n } catch (e) {\n response\n .status(500)\n .end(\n `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`\n );\n return;\n }\n\n if (!accountId) {\n response\n .status(500)\n .end(\n `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`\n );\n return;\n }\n\n try {\n const previewInfo = await fetchPreviewInfo(accountId, portalId, contentId);\n const { previewKey } = previewInfo;\n\n const environmentConfig = buildStaticEnvConfig(\n portalId,\n hublet,\n proxyEnv,\n false,\n jsRenderingGates\n );\n\n let pageHtml = (await makeProxyPreviewRequest(\n accountId,\n urlToProxy,\n previewKey,\n contentId,\n projectName,\n environmentConfig,\n jsRenderingGates,\n request.get('COOKIE'),\n request.app.locals.localPreviewToken\n )).data;\n pageHtml = addRefreshScript(pageHtml);\n await infillReactModulesAndWriteResponse(\n response,\n pageHtml,\n webRoot,\n fullOriginalUrl,\n environmentConfig,\n viteServer,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n prettyPrint\n );\n } catch (error) {\n // TODO change error.stack to error.message before we publish\n response\n .status(500)\n .end(\n `Failed proxy render of page id = ${contentId} hub id = ${portalId}\\n\\n${error.stack}`\n );\n return;\n }\n}\n\nexport async function infillReactModulesAndWriteResponse(\n response,\n pageHtml,\n webRoot,\n fullOriginalUrl,\n environmentConfig,\n viteServer,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n prettyPrint\n) {\n // Loading through vite so all of nested `@hubspot/cms-*` imports work\n const { sortIslandRootsByPriority } = await viteServer.ssrLoadModule(\n '@hubspot/cms-components'\n );\n const localRenderPlaceholders = findLocalRenderPlaceholders(pageHtml);\n const numPlaceholders = localRenderPlaceholders.length;\n let numJsRenderFailures = 0;\n let islands = [];\n let mergedPerRequestState = new Map<string, any>();\n let basePath;\n const criticalDevErrors = [];\n const renderPromisesByChunkIndex: Array<Promise<string | void>> = new Array(\n numPlaceholders\n );\n\n if (localRenderPlaceholders.length > 0) {\n let offsetSoFar = 0;\n const pageChunks = new Array(numPlaceholders + 1);\n\n for (\n let indexForThisRender = 0;\n indexForThisRender < numPlaceholders;\n indexForThisRender++\n ) {\n const localRenderPlaceholder =\n localRenderPlaceholders[indexForThisRender];\n pageChunks[indexForThisRender] = pageHtml.slice(\n offsetSoFar,\n localRenderPlaceholder.startOffset\n );\n\n if (basePath === undefined) {\n basePath = getEntryPointBasePathFromProxyRequest(\n localRenderPlaceholder.json.request\n );\n }\n\n const renderPromise = renderComponentForPlaceholder(\n indexForThisRender,\n localRenderPlaceholder,\n webRoot,\n viteServer,\n fullOriginalUrl,\n basePath,\n environmentConfig,\n projectName,\n projectComponentPath\n );\n\n renderPromisesByChunkIndex[indexForThisRender] = renderPromise\n .then((promiseResult) => {\n // eslint-disable-next-line prefer-const\n let { html, cssNeeded, inlineAssets, renderContext } =\n promiseResult;\n\n console.log(\n `Finished render of ${localRenderPlaceholder.path} (i = ${indexForThisRender})`\n );\n\n if (renderContext.criticalDevErrors?.length) {\n criticalDevErrors.push(...renderContext.criticalDevErrors);\n }\n\n if (renderContext.islands.length > 0) {\n islands = islands.concat(renderContext.islands);\n }\n mergedPerRequestState = mergeServerRequestData_internal(\n mergedPerRequestState,\n renderContext.perServerRequestData\n );\n\n let result = html;\n\n if (inlineAssets) {\n result = `${inlineAssets\n .map((inlineAsset) => inlineAsset.html)\n .join('\\n')}\\n${result}`;\n }\n\n if (cssNeeded) {\n result = `${cssNeeded}\\n${result}`;\n }\n\n return result;\n })\n .catch((e) => {\n numJsRenderFailures += 1;\n console.log(\n 'Attempted to render',\n localRenderPlaceholder.path,\n 'with props',\n localRenderPlaceholder.json\n );\n console.error(e);\n return renderLocalError(localRenderPlaceholder.path, e);\n });\n\n offsetSoFar = localRenderPlaceholder.endOffset;\n }\n\n // Last chunk from end of last placeholder to end of HTML\n pageChunks[localRenderPlaceholders.length] = pageHtml.slice(offsetSoFar);\n\n response.writeHead(200);\n\n for (let i = 0; i < localRenderPlaceholders.length; i++) {\n const chunk = pageChunks[i];\n response.write(chunk);\n const foobar = await renderPromisesByChunkIndex[i];\n\n // console.log(\"JS rendered chunk\", i, foobar);\n response.write(foobar);\n }\n\n response.write(\n getServerGlobalsToInject(\n environmentConfig,\n fullOriginalUrl,\n basePath,\n undefined,\n criticalDevErrors\n )\n );\n\n if (criticalDevErrors.length) {\n response.write(\n scriptTagToLogServerMessages(\n criticalDevErrorsToServerMessages(criticalDevErrors),\n '@hubspot/cms-dev-server messages'\n )\n );\n }\n if (islands.length > 0) {\n const sortedIslandRoots = sortIslandRootsByPriority(islands);\n const islandRuntimeAndGlobalScriptHtml = await getIslandRuntimeAndGlobalToInject(\n sortedIslandRoots,\n mergedPerRequestState,\n viteServer,\n jsRenderingGates,\n prettyPrint\n );\n\n response.write(islandRuntimeAndGlobalScriptHtml);\n }\n\n // Write last string chunk located after last placeholder\n response.write(pageChunks[pageChunks.length - 1]);\n\n response.end();\n } else {\n response.writeHead(200);\n\n response.write(pageHtml);\n response.end();\n }\n}\n", "import { ViteDevServer } from 'vite';\nimport { join as joinPosix } from 'path/posix';\nimport { RenderToPipeableStreamOptions } from 'react-dom/server';\nimport { EnvironmentConfig } from '@hubspot/cms-components/config';\nimport { LogMessage, ModuleProps } from '@hubspot/cms-components';\nimport * as cmsComponents from '@hubspot/cms-components';\nimport { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport {\n hasComponentExtension,\n isUngatedFor,\n namespaceModulePropsShape,\n} from '@hubspot/cms-js-internal';\n\nimport renderComponentWithCSS, {\n RenderResult,\n} from '../lib/renderComponentWithCSS.js';\n\nimport fetchModuleGraphQLData from './fetchModuleGraphQLData.js';\nimport packagePath from './packagePath.js';\nimport { getFieldValuesForModule } from './getFieldValuesForModule.js';\n\nexport const VALIDATE_FIELDS_ENDPOINT =\n '/designmanager/v1/modules/validate-fields';\nexport const VALIDATE_META_ENDPOINT = '/designmanager/v1/modules/validate-meta';\n\nconst { filterToModuleDataDepsIncludedIn, getModuleDataDependecyTypeFrom } =\n cmsComponents;\n\ntype FieldValidationResponseBody = {\n errorType: string;\n message: string;\n severity: string;\n succeeded: boolean;\n status: string;\n errorTokens: {\n field: Array<string>;\n path: Array<string>;\n type: Array<string>;\n uiattribute: Array<string>;\n value: Array<string>;\n };\n};\n\nconst handleValidationApiError = (\n result: PromiseSettledResult<FieldValidationResponseBody[]>,\n type: 'Field' | 'Meta',\n renderContext: any,\n requestedModulePath: string\n): void => {\n // If API has non-200 status, push generic validation error\n if (result.status === 'rejected') {\n const errorMessage = result.reason\n ? `${result.reason.name}: ${result.reason.message}`\n : '';\n if (errorMessage) {\n renderContext.criticalDevErrors.push({\n message: `Failed request to validate module for ${requestedModulePath} - ${type} Validation Error`,\n error: new Error(errorMessage),\n level: 'error',\n });\n }\n }\n};\nconst handleModuleValidationErrors = (\n validationErrors: FieldValidationResponseBody[] | [] = [],\n type: 'Field' | 'Meta',\n renderContext: any,\n requestedModulePath: string\n) => {\n const validationSeverityToLogLevel = {\n FATAL: 'error',\n WARNING: 'warn',\n };\n if (!Array.isArray(validationErrors)) {\n return;\n }\n validationErrors.forEach((validationError: FieldValidationResponseBody) => {\n renderContext.criticalDevErrors.push({\n message: `${type} Validation Error in ${requestedModulePath}: ${validationError.message}`,\n error: new Error(validationError.message),\n level: validationSeverityToLogLevel[validationError.severity] || 'info',\n });\n });\n};\n\nexport const getApplyValidationToRenderContext = (\n portalId,\n fieldsJSON,\n metaJSON,\n requestedModulePath\n) => {\n return async (renderResult: RenderResult): Promise<RenderResult> => {\n const { renderContext } = renderResult;\n\n let fieldsValidationResponse: FieldValidationResponseBody[] | null;\n let metaValidationResponse: FieldValidationResponseBody[] | null;\n\n try {\n // @ts-expect-error local-dev-lib doesn't play nice here for some reason\n const [fieldsResult, metaResult]: [\n PromiseSettledResult<FieldValidationResponseBody[]>,\n PromiseSettledResult<FieldValidationResponseBody[]>,\n ] = await Promise.allSettled([\n hsCliHttp.post<FieldValidationResponseBody[]>(portalId, {\n url: VALIDATE_FIELDS_ENDPOINT,\n data: fieldsJSON,\n resolveWithFullResponse: true,\n }),\n hsCliHttp.post<FieldValidationResponseBody[]>(portalId, {\n url: VALIDATE_META_ENDPOINT,\n data: metaJSON,\n resolveWithFullResponse: true,\n }),\n ]);\n\n [fieldsResult, metaResult].forEach((result, index) =>\n handleValidationApiError(\n result,\n index === 0 ? 'Field' : 'Meta',\n renderContext,\n requestedModulePath\n )\n );\n fieldsValidationResponse =\n fieldsResult.status === 'fulfilled' ? fieldsResult.value : null;\n metaValidationResponse =\n metaResult.status === 'fulfilled' ? metaResult.value : null;\n } catch {\n console.log('Failed to validate module for', requestedModulePath);\n }\n\n [fieldsValidationResponse, metaValidationResponse].forEach(\n (response, index) => {\n handleModuleValidationErrors(\n response,\n index === 0 ? 'Field' : 'Meta',\n renderContext,\n requestedModulePath\n );\n }\n );\n\n return renderResult;\n };\n};\n\nexport const lookForModuleInFolder = async (\n modulePath: string,\n viteServer: ViteDevServer\n): Promise<[any, string]> => {\n let componentModule;\n const insideFolderPath = joinPosix(modulePath, 'index');\n\n try {\n componentModule = await viteServer.ssrLoadModule(insideFolderPath);\n } catch (e) {\n if (!e.message.includes('Failed to load url')) {\n throw e;\n }\n }\n\n return [componentModule, insideFolderPath];\n};\n\nasync function renderModule(\n viteServer: ViteDevServer,\n requestedModulePath: string,\n moduleProps: ModuleProps,\n pageUrl: string,\n basePath: string,\n environmentConfig: EnvironmentConfig,\n renderOptions?: RenderToPipeableStreamOptions\n) {\n console.log('Rendering module', requestedModulePath);\n\n const {\n fieldValues: fieldOverrides = {},\n hublParameters,\n supplementalFieldValues,\n experimentalHublData,\n hublData,\n moduleName,\n } = moduleProps;\n\n const ungatedForServerSideProps = isUngatedFor(\n environmentConfig.getGates(),\n 'CMS:JSRenderer:GetServerSideProps'\n );\n\n const messagesForBrowser: LogMessage[] = [];\n let componentModule;\n let dataQueryResult;\n let foundPath: string;\n let getServerSideProps;\n let extraDeps;\n\n if (!hasComponentExtension(requestedModulePath)) {\n [componentModule, foundPath] = await lookForModuleInFolder(\n requestedModulePath,\n viteServer\n );\n }\n\n if (!componentModule) {\n // Look for non-folder module\n componentModule = await viteServer.ssrLoadModule(requestedModulePath);\n foundPath = componentModule ? requestedModulePath : undefined;\n }\n\n if (!componentModule) {\n throw new Error(`Couldn't find module: ${requestedModulePath}`);\n }\n\n const Component = componentModule.Component;\n const fields = componentModule.fields;\n const meta = componentModule.meta;\n\n if (!Component) {\n throw new Error(\n `Module does not have a named Component export: ${foundPath}`\n );\n } else if (!fields) {\n throw new Error(`Module does not have a named fields export: ${foundPath}`);\n } else if (!meta) {\n throw new Error(`Module does not have a named meta export: ${foundPath}`);\n }\n\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n const { renderFieldsToJson } =\n await viteServer.ssrLoadModule(internalSsrPath);\n const fieldsJSON = renderFieldsToJson(fields, requestedModulePath);\n const fieldValues = getFieldValuesForModule(fieldsJSON, fieldOverrides);\n\n const applyFieldsValidationToRenderContext =\n getApplyValidationToRenderContext(\n environmentConfig.getPortalID(),\n fieldsJSON,\n meta,\n requestedModulePath\n );\n\n if (componentModule.query && typeof componentModule.query === 'string') {\n try {\n dataQueryResult = await fetchModuleGraphQLData(\n environmentConfig.getHubID(),\n componentModule.query,\n requestedModulePath,\n pageUrl\n );\n\n if (dataQueryResult.errors && dataQueryResult.errors.length) {\n const errorString = `GraphQL query for ${requestedModulePath} had errors.`;\n messagesForBrowser.push({\n level: 'error',\n parameters: [errorString],\n });\n\n dataQueryResult.errors.forEach((graphQLError) => {\n console.error(graphQLError);\n messagesForBrowser.push({\n level: 'error',\n parameters: [graphQLError.message, graphQLError],\n });\n });\n }\n } catch (error) {\n const errorString = `Failed to execute query for ${requestedModulePath}.`;\n\n console.error(errorString);\n console.error(error.message);\n\n messagesForBrowser.push({\n level: 'error',\n parameters: [errorString, error.message],\n });\n }\n }\n\n const namespacedModuleProps = namespaceModulePropsShape({\n fieldValues,\n hublParameters,\n dataQueryResult,\n supplementalFieldValues,\n experimentalHublData,\n hublData,\n moduleName,\n });\n\n if (ungatedForServerSideProps && componentModule.getServerSideProps) {\n if (!getModuleDataDependecyTypeFrom || !filterToModuleDataDepsIncludedIn) {\n throw new Error(\n `Need to upgrade to @hubspot/cms-components 0.15.x or higher to use getServerSideProps`\n );\n }\n\n getServerSideProps = componentModule.getServerSideProps;\n\n const depType = getModuleDataDependecyTypeFrom(\n componentModule.getServerSideProps\n );\n\n extraDeps = filterToModuleDataDepsIncludedIn(depType, {\n url: new URL(pageUrl),\n contact: undefined, // TODO\n request: undefined, // TODO\n });\n }\n\n return renderComponentWithCSS(\n viteServer,\n foundPath,\n Component,\n { props: namespacedModuleProps, extraDeps },\n pageUrl,\n basePath,\n { supplementalFieldValues, messagesForBrowser },\n environmentConfig,\n renderOptions,\n getServerSideProps,\n componentModule.unstable_modifyHtml\n ).then(applyFieldsValidationToRenderContext);\n}\n\nexport default renderModule;\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\n\ntype DataQueryPoints = {\n count: number;\n weight: number;\n used_points: number;\n};\n\ntype DataQueryResult = {\n extensions: {\n query_complexity: {\n max_points: number;\n used_points: number;\n points_for_internal_api_requests: DataQueryPoints;\n points_for_objects_retrieved: DataQueryPoints;\n points_for_properties_with_value: DataQueryPoints;\n points_for_properties_without_value: DataQueryPoints;\n };\n };\n data?: {\n CRM?: any;\n HUBDB?: any;\n };\n};\n\nconst graphQLCache = new Map();\n\nexport function clearGraphQLDataCache() {\n graphQLCache.clear();\n}\n\nexport default async function fetchModuleGraphQLData(\n accountId: number,\n query: string,\n requestedModulePath: string,\n pageUrl: string\n): Promise<DataQueryResult> {\n const { searchParams } = new URL(pageUrl);\n const hsLocalQueryKey = searchParams.get('hsLocalQueryKey');\n const compositeQueryKey = `${hsLocalQueryKey}:${query}`;\n let dataQueryResult: DataQueryResult;\n\n if (graphQLCache.has(compositeQueryKey)) {\n console.log(`Using cached GraphQL Query for ${requestedModulePath}`);\n\n return Promise.resolve(graphQLCache.get(compositeQueryKey));\n }\n\n try {\n // @ts-expect-error doesn't conform to DataQueryResult (missing extensions prop)?\n dataQueryResult = (await hsCliHttp.post(accountId, {\n url: '/collector/v3/graphql',\n data: {\n query,\n },\n })).data;\n } catch (e) {\n throw new Error(e);\n }\n\n graphQLCache.set(compositeQueryKey, dataQueryResult);\n\n return dataQueryResult;\n}\n", "import { Field, traverseFieldsJSON } from '@hubspot/cms-components/fields';\nimport { setIn } from '@hubspot/cms-js-internal';\n\nexport function getFieldValuesForModule(\n fieldsJSON: Field[],\n fieldOverrides = {}\n) {\n const props: object = {};\n\n traverseFieldsJSON(fieldsJSON, fieldOverrides, (fieldPathArray, value) => {\n setIn(props, fieldPathArray, value);\n });\n\n return props;\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable prefer-promise-reject-errors */\n\nimport { createEmptyServerRenderContext } from '@hubspot/cms-components';\nimport { RenderResult } from '../lib/renderComponentWithCSS.js';\nimport { VALID_PROXY_DOMAIN_SUFFIXES } from './constants.js';\n\nexport const getSubDomainFromValidLocalDomain = (hostname) => {\n for (const validProxyDomainSuffix of VALID_PROXY_DOMAIN_SUFFIXES) {\n if (hostname.endsWith(`.${validProxyDomainSuffix}`)) {\n return hostname.slice(0, -1 * validProxyDomainSuffix.length - 1);\n }\n }\n return undefined;\n};\n\nconst randomStringWithLotsOf = (char: string, maxLength: number): string => {\n return new Array(Math.floor(Math.random() * maxLength)).fill(char).join('');\n};\n\nexport const fakeRenderJsComponent = (\n indexForThisRender\n): Promise<RenderResult> => {\n return new Promise((resolve, reject) => {\n const randomTimeout =\n Math.floor(Math.random() * 200) + indexForThisRender * 1000;\n\n setTimeout(() => {\n try {\n const fakeJsRenderedOutput = `<div data-js-rendered>JS render #${\n indexForThisRender + 1\n } (${randomTimeout}ms delay) ${randomStringWithLotsOf(\n '?',\n 100\n )}</div>\\n`;\n\n resolve({\n html: fakeJsRenderedOutput,\n cssNeeded: '',\n renderContext: createEmptyServerRenderContext(),\n inlineAssets: [],\n });\n } catch (e) {\n console.log('Error with JS render...');\n console.error(e);\n reject();\n }\n }, randomTimeout);\n });\n};\n\nexport const consoleWarn = (message) => {\n console.warn('\\x1b[33m%s\\x1b[0m', 'WARNING:', message);\n};\n", "export const VALID_PROXY_DOMAIN_SUFFIXES = ['localhost', 'hslocal.net'];\n", "import AnsiToHtmlConverter from 'ansi-to-html';\n\n// Custom ansi colors pulled from tfinley's terminal theme\nconst customColors = [\n // Normal colors\n '#000', // black\n '#ec392c', // red\n '#b3e439', // green\n '#fea525', // yellow\n '#76dff3', // blue\n '#fd4285', // magenta\n '#cfa3ff', // cyan\n '#f4f4f4', // White\n\n // Bright colors (mostly identical to ^)\n '#646464',\n '#ec392c',\n '#fea525',\n '#76dff3',\n '#fd4285',\n '#cfa3ff',\n '#f4f4f4',\n];\n\nconst Converter = new AnsiToHtmlConverter({ colors: customColors });\n\nconst darkErrorStyles = `background-color: #222; color: #ccc; padding: 0.5em; font-family: ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace;`;\n\nexport default (path: string, error: Error): string => {\n const stackWithColorClasses = Converter.toHtml(error.stack);\n return `<div data-js-rendered=\"error\" style=\"${darkErrorStyles}\">Error rendering ${path}<br/><br/><code><pre>${stackWithColorClasses}</pre></code></div>`;\n};\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\n\nexport interface PreviewInfoResponse {\n previewDomain: string;\n previewKey: string;\n templatePath: string;\n}\n\nexport default async (\n accountId: number,\n portalId: number,\n contentId: string\n): Promise<PreviewInfoResponse> => {\n if (!contentId) {\n throw new Error(\n `Invalid contentId when attempting to fetch preview info: ${contentId}`\n );\n }\n\n try {\n // Works with oauth if any scopes present [blog-access, landingpages-access, service-knowledge-access, sitepages-access, pages-access]\n const content = (\n await hsCliHttp.get<Record<string, any>>(accountId, {\n url: `/content/api/v4/contents/${contentId}`,\n params: { portalId },\n responseType: 'json',\n })\n ).data;\n\n return {\n previewDomain: content.previewDomain ?? content.resolvedDomain,\n previewKey: content.previewKey,\n templatePath: content.templatePath,\n };\n } catch (error) {\n if (\n error.statusCode === 403 &&\n error.error.message.match(\n /^This oauth-token \\([\\w]+\\) does not have proper permissions!/\n )\n ) {\n const errorMessagePrefix = `Your personal access key is missing required scopes to preview a CMS page.\\nYou may need to re-generate a new personal access key with the required scopes and re-run \\`hs-auth\\`, or you may not have this functionality enabled in your account\\n`;\n console.error('Error: ', errorMessagePrefix);\n console.error(error.error.message);\n throw new Error(`${errorMessagePrefix}\\n${error.error.message}`);\n } else {\n console.log(`fetchPreviewInfo Error`, error);\n if (error.options) {\n console.log(`error.options`, error.options);\n }\n if (error.response && error.response.headers) {\n console.log(`error.response.headers`, error.response.headers);\n }\n throw error;\n }\n }\n};\n", "import { stringify } from 'querystring';\nimport { readFileSync } from 'fs';\nimport crypto from 'crypto';\nimport { relative, join } from 'path';\nimport { diffDeveloperFileHashes, initiateSession } from '../api/session.js';\nimport {\n initialPreviewBufferUpload,\n startPreviewWatcher,\n} from '../fileManager.js';\nimport path from 'path';\n\nexport const removePreviewPrefix = (t: string) =>\n t.split('/').slice(2).join('/');\n\nexport const getPreviewUrl = (request: any, queryParams: any) => {\n const { authedPortalId, authedEnv, authedHublet } = request.app.locals;\n\n return `http://${authedPortalId}.hubspotpreview${\n authedEnv === 'qa' ? 'qa' : ''\n }-${authedHublet}.com/_hcms/preview/template/multi?${stringify(queryParams)}`;\n};\nexport const buildHTMLResponse = (content: any) => {\n return `\n <!DOCTYPE html>\n <head>\n </head>\n <body>\n ${content}\n </body>\n `;\n};\nconst insertAtEndOfBody = (html: string, script: any) => {\n const insertAt = (baseStr: any, index: any, insertStr: any) => {\n return `${baseStr.slice(0, index)}${insertStr}${baseStr.slice(index)}`;\n };\n const endOfBodyIndex = html.lastIndexOf('</body>');\n return insertAt(html, endOfBodyIndex, script);\n};\n\nexport const addRefreshScript = (html: string) => {\n const refreshScript = `\n <script>\n (() => {\n const MAX_WAIT = 16000;\n const NORMAL_WAIT_MS = 1000;\n const BACKOFF_RATIO = 2;\n let nextWait = NORMAL_WAIT_MS;\n let timeWaited = 0;\n\n setInterval(() => {\n timeWaited += NORMAL_WAIT_MS;\n if (timeWaited !== nextWait) return;\n timeWaited = 0;\n const res = fetch(window.location.origin + '/remote-fs-dirty')\n .then(async (res) => {\n const hsServerState = await res.json();\n if (hsServerState[\"REMOTE_FS_IS_DIRTY\"]) {\n location.reload();\n }\n nextWait = NORMAL_WAIT_MS;\n })\n .catch(err => {\n if (nextWait * BACKOFF_RATIO <= MAX_WAIT) {\n nextWait *= BACKOFF_RATIO;\n }\n console.log('Disconnected from local server... (retrying in ' + nextWait / 1000 + 's)');\n });\n }, NORMAL_WAIT_MS);\n })();\n </script>\n `;\n return insertAtEndOfBody(html, refreshScript);\n};\n\nexport function buildDevFileHashTable(\n src: string,\n dest: string,\n filePaths: string[]\n) {\n return filePaths.reduce((acc, filePath) => {\n const relativePath = relative(src, filePath);\n const destPath = join(dest, relativePath).replaceAll(\n path.sep,\n path.posix.sep\n );\n // Files stored in BE have a preceding /\n acc[`/${destPath}`] = getMd5Hash(filePath);\n return acc;\n }, {});\n}\n\n// Get md5 hash of file given its path\nfunction getMd5Hash(filePath: string) {\n const fileContent = readFileSync(filePath);\n const hash = crypto.createHash('md5');\n hash.update(fileContent);\n return hash.digest('hex');\n}\n\nexport type ThemePreviewOptions = {\n filePaths: string[];\n startProgressBar: (number) => {\n onAttemptCallback: Function;\n onSuccessCallback: Function;\n onFirstErrorCallback: Function;\n onRetryCallback: Function;\n onFinalErrorCallback: Function;\n onFinishCallback: Function;\n };\n resetSession: boolean;\n dest: string;\n};\n\nexport async function initiatePreviewSession(\n authedPortalId: number | null,\n absoluteWebRoot: string,\n themePreviewOptions: ThemePreviewOptions\n) {\n let res;\n try {\n res = (\n await initiateSession(authedPortalId, themePreviewOptions.resetSession)\n ).data;\n } catch (err) {\n console.error(`Failed to initiate session: ${err}`);\n return;\n }\n const { token, tokenStatus } = res;\n if (token) {\n const { dest, filePaths, startProgressBar } = themePreviewOptions;\n const absoluteDest = `@preview/${token}/${dest}`;\n const nonJSRFilePaths = filePaths.filter(\n (filePath) =>\n !filePath.startsWith(path.join(absoluteWebRoot, 'components'))\n );\n\n if (tokenStatus === 'NEW') {\n console.log('Uploading for a new session...');\n const uploadOptions = startProgressBar(nonJSRFilePaths.length);\n await initialPreviewBufferUpload(\n authedPortalId,\n absoluteWebRoot,\n absoluteDest,\n nonJSRFilePaths,\n uploadOptions\n );\n } else if (tokenStatus === 'REFRESHED') {\n console.log('Comparing files for refreshed session...');\n const hashes = await buildDevFileHashTable(\n absoluteWebRoot,\n absoluteDest,\n nonJSRFilePaths\n );\n let diffRes;\n try {\n diffRes = (await diffDeveloperFileHashes(authedPortalId, token, hashes))\n .data;\n } catch (err: any) {\n console.error(\n `Failed to diff developer file hashes: ${JSON.stringify(err)}`\n );\n return;\n }\n const { changedFiles, addedFiles /*, deletedFiles */ } = diffRes;\n const filesToUpload = [...changedFiles, ...addedFiles].map((filePath) => {\n // Strip the preceding / that BE adds\n const relPath = path.relative(absoluteDest, filePath.substring(1));\n return path.join(absoluteWebRoot, relPath);\n });\n if (filesToUpload.length) {\n const uploadOptions = startProgressBar(filesToUpload.length);\n await initialPreviewBufferUpload(\n authedPortalId,\n absoluteWebRoot,\n absoluteDest,\n filesToUpload,\n uploadOptions\n );\n }\n }\n\n await startPreviewWatcher(authedPortalId, absoluteWebRoot, absoluteDest);\n }\n return { localPreviewToken: token, tokenStatus };\n}\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\n\nconst PREVIEW_API_PATH = `local-preview/v1`;\n\ntype SessionInitiationResponse = {\n id: string,\n token: string,\n createdAt: number,\n updatedAt: number,\n expiresAt: number,\n tokenStatus: \"NEW\" | \"REFRESHED\"\n}\n\nexport function initiateSession(accountId: number, resetSession=false): any {\n return hsCliHttp.post<SessionInitiationResponse>(accountId, {\n url: `${PREVIEW_API_PATH}/session/create`,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n data: {\n resetSession\n }\n });\n}\n\nexport function diffDeveloperFileHashes(accountId: number, token: string, fileHashes: Record<string, string>): any {\n return hsCliHttp.post<any>(accountId, {\n url: `${PREVIEW_API_PATH}/developer-file-hashes/diff`,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n data: {\n token,\n fileHashes\n }\n })\n}\n", "import { uploadFolder } from '@hubspot/local-dev-lib/cms/uploadFolder';\nimport chokidar from 'chokidar';\nimport path from 'path';\nimport { shouldIgnoreFile } from '@hubspot/local-dev-lib/ignoreRules';\nimport {\n convertToUnixPath,\n isAllowedExtension,\n} from '@hubspot/local-dev-lib/path';\nimport { getExt, splitLocalPath } from '@hubspot/local-dev-lib/path';\nimport { upload, deleteFile } from '@hubspot/local-dev-lib/api/fileMapper';\nimport { MODULE_EXTENSION } from '@hubspot/local-dev-lib/constants/extensions';\nimport { escapeRegExp } from '@hubspot/local-dev-lib/escapeRegExp';\nimport { markRemoteFsDirty } from './routes/remoteFsDirtyHandler.js';\n\nexport async function initialPreviewBufferUpload(\n accountId: any,\n src: any,\n dest: any,\n filePaths: any,\n uploadOptions: any\n) {\n const { onFinishCallback, ...rest } = uploadOptions;\n\n const results = await uploadFolder(\n accountId,\n src,\n dest,\n {},\n rest,\n filePaths.map((filePath: string) =>\n filePath.replaceAll(path.sep, path.posix.sep)\n )\n );\n onFinishCallback(results);\n}\n\nexport const startPreviewWatcher = async (\n accountId: any,\n src: string,\n dest: string\n) => {\n let watcherIsReady = false;\n\n const watcher = chokidar.watch(src, {\n ignoreInitial: true, // makes initial addition of files not trigger the watcher\n ignored: (file) => shouldIgnoreFile(file),\n });\n\n const addFileCallback = buildUploadFileToPreviewBufferCallback(\n accountId,\n src,\n dest\n );\n const changeFileCallback = buildUploadFileToPreviewBufferCallback(\n accountId,\n src,\n dest\n );\n const deleteFileCallback = buildDeleteFileFromPreviewBufferCallback(\n accountId,\n src,\n dest,\n 'file'\n );\n const deleteFolderCallback = buildDeleteFileFromPreviewBufferCallback(\n accountId,\n src,\n dest,\n 'folder'\n );\n\n watcher.on('ready', () => {\n watcherIsReady = true;\n });\n watcher.on('add', addFileCallback);\n watcher.on('change', changeFileCallback);\n watcher.on('error', (error) =>\n console.error(`An error occurred while watching files: ${error}`)\n );\n\n watcher.on('unlink', deleteFileCallback);\n watcher.on('unlinkDir', deleteFolderCallback);\n\n function sleep(ms: any) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n while (!watcherIsReady) {\n await sleep(1);\n // do nothing... surely there's a better way to do this...\n }\n return watcher;\n};\n\nfunction buildUploadFileToPreviewBufferCallback(\n accountId: any,\n src: string,\n dest: string\n) {\n return (filePath: any) => {\n if (!isAllowedExtension(filePath)) {\n console.debug(`Skipping ${filePath} due to unsupported extension`);\n return;\n }\n if (shouldIgnoreFile(filePath)) {\n console.debug(`Skipping ${filePath} due to an ignore rule`);\n return;\n }\n if (\n path.dirname(filePath) === src &&\n ['theme.json', 'fields.json'].includes(path.basename(filePath))\n ) {\n console.warn(`Editing of theme fields or meta is not yet supported.`);\n return;\n }\n const destPath = getDesignManagerPath(src, dest, filePath);\n return uploadFile(accountId, filePath, destPath);\n };\n}\n\nfunction buildDeleteFileFromPreviewBufferCallback(\n accountId: any,\n src: string,\n dest: string,\n type: any\n) {\n return (filePath: any) => {\n if (shouldIgnoreFile(filePath)) {\n console.debug(`Skipping ${filePath} due to an ignore rule`);\n return;\n }\n if (type === 'file') {\n const moduleChild = isModuleFolderChild(filePath);\n const filename = path.basename(filePath);\n if (moduleChild && filename === 'meta.json') {\n return;\n }\n }\n\n const remotePath = getDesignManagerPath(src, dest, filePath);\n return deleteRemoteFile(accountId, remotePath);\n };\n}\n\nfunction getDesignManagerPath(src: any, dest: any, file: any) {\n const regex = new RegExp(`^${escapeRegExp(src)}`);\n const relativePath = file.replace(regex, '');\n return convertToUnixPath(path.join(dest, relativePath));\n}\n\nasync function uploadFile(accountId: any, src: any, dest: any) {\n console.debug(`Attempting to upload file \"${src}\" to \"${dest}\"`);\n\n try {\n await upload(accountId, src, dest);\n console.log(`Uploaded file ${src} to ${dest}`);\n markRemoteFsDirty();\n } catch {\n const uploadFailureMessage = `Uploading file ${src} to ${dest} failed`;\n console.debug(uploadFailureMessage);\n console.debug(`Retrying to upload file \"${src}\" to \"${dest}\"`);\n try {\n await upload(accountId, src, dest);\n markRemoteFsDirty();\n } catch (error: any) {\n console.error(uploadFailureMessage);\n }\n }\n}\n\nasync function deleteRemoteFile(accountId: any, remoteFilePath: any) {\n console.debug(`Attempting to delete file \"${remoteFilePath}\"`);\n\n try {\n await deleteFile(accountId, remoteFilePath);\n console.log(`Deleted file ${remoteFilePath}`);\n markRemoteFsDirty();\n } catch (error) {\n console.error(`Deleting file ${remoteFilePath} failed`);\n console.debug(`Retrying deletion of file ${remoteFilePath}`);\n try {\n await deleteFile(accountId, remoteFilePath);\n markRemoteFsDirty();\n } catch (err) {\n console.error(`Deleting file ${remoteFilePath} failed`);\n }\n }\n}\n\nexport function isModuleFolderChild(filePath: string) {\n const pathParts = splitLocalPath(filePath);\n if (pathParts.length <= 1) return false;\n return pathParts\n .slice(0, pathParts.length - 1)\n .some((part) => getExt(path.normalize(part)) === MODULE_EXTENSION);\n}\n", "let REMOTE_FS_IS_DIRTY = false;\n\nexport const remoteFsDirtyHandler = (req: any, res: any) => {\n res.json({ REMOTE_FS_IS_DIRTY});\n REMOTE_FS_IS_DIRTY = false;\n};\n\nexport const markRemoteFsDirty = () => {\n REMOTE_FS_IS_DIRTY = true;\n};\n", "function EmptyPartialsList({ webRoot }) {\n return (\n <p>\n No partials in <code>{webRoot}components/partials</code>\n </p>\n );\n}\n\nfunction PartialLinkInLI({ partialName }) {\n return (\n <li>\n <a href={`/partial/${partialName}`}>{partialName}</a>\n </li>\n );\n}\n\nexport default function PartialsList({ webRoot, partialNames }) {\n if (partialNames.length === 0) {\n return <EmptyPartialsList webRoot={webRoot} />;\n }\n\n return (\n <ul>\n {partialNames.map((partialName) => (\n <PartialLinkInLI partialName={partialName} key={partialName} />\n ))}\n </ul>\n );\n}\n", "import {\n findAllPartialsInRoot,\n renderOnServer,\n} from '@hubspot/cms-js-internal';\nimport PartialsList from '../components/PartialsList.js';\n\nconst linksToAllPartialRouteHandler = async (request, response) => {\n const { webRoot } = request.app.locals;\n const { partialNames } = findAllPartialsInRoot(webRoot);\n const { html: responseHtml } = await renderOnServer(\n <PartialsList webRoot={webRoot} partialNames={partialNames} />\n );\n response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);\n};\n\nexport default linksToAllPartialRouteHandler;\n", "function EmptyModulesList({ webRoot }) {\n return (\n <p>\n No modules in <code>{webRoot}components/modules</code>\n </p>\n );\n}\n\nfunction ModuleLinkInLI({ moduleName }) {\n return (\n <li>\n <a href={`/preview/module/${moduleName}`}>{moduleName}</a>\n {' / '}\n <a href={`/module/${moduleName}`}>Local Version</a>\n </li>\n );\n}\n\nfunction ModulesList({ webRoot, moduleNames }) {\n if (moduleNames.length === 0) {\n return <EmptyModulesList webRoot={webRoot} />;\n }\n\n return (\n <ul>\n {moduleNames.map((moduleName) => (\n <ModuleLinkInLI moduleName={moduleName} key={moduleName} />\n ))}\n </ul>\n );\n}\n\nexport default ModulesList;\n", "import { findAllModulesInRoot, renderOnServer } from '@hubspot/cms-js-internal';\nimport ModulesList from '../components/ModulesList.js';\n\nconst linksToAllModuleRouteHandler = async (request, response) => {\n const { webRoot } = request.app.locals;\n const { moduleNames } = findAllModulesInRoot(webRoot);\n\n const { html: responseHtml } = await renderOnServer(\n <ModulesList webRoot={webRoot} moduleNames={moduleNames} />\n );\n response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);\n};\n\nexport default linksToAllModuleRouteHandler;\n", "import { buildStaticEnvConfig } from '@hubspot/cms-components';\nimport path from 'path';\nimport { normalizePath } from 'vite';\nimport { Request } from 'express';\nimport fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';\nimport renderModule from '../lib/renderModule.js';\nimport { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';\nimport packagePath from '../lib/packagePath.js';\nimport { getEntryPointHash } from '@hubspot/cms-js-internal';\nimport { getEntryPointBasePath } from '../lib/pathHelpers.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\n\nconst moduleRouteHandler = async (request: Request, response) => {\n sendTrackingRequest('view-module-route');\n const {\n authedPortalId,\n authedEnv,\n authedHublet,\n webRoot,\n viteServer,\n jsRenderingGates,\n projectName,\n projectComponentPath,\n } = request.app.locals;\n const moduleName = request.params.moduleName;\n const baseTemplatePath = packagePath(\n import.meta.url,\n 'html/baseTemplate.html'\n );\n\n // todo: use partial prefix const\n const modulePath = normalizePath(\n path.resolve(webRoot, 'components/modules/', moduleName)\n );\n const entrypointPath = normalizePath(\n [\n '@projects',\n projectName,\n projectComponentPath,\n 'components/modules/',\n moduleName,\n ].join('/')\n );\n\n let fieldOverrides = null;\n\n if (request.query.fields) {\n try {\n if (typeof request.query.fields === 'string') {\n fieldOverrides = JSON.parse(\n decodeURIComponent(request.query.fields.replace(/\\+/g, '%20'))\n );\n }\n } catch (e) {\n console.error(\n `Error parsing field param for module ${moduleName}: ${request.query.fields}`\n );\n }\n }\n\n const basePath = getEntryPointBasePath(modulePath);\n\n const environmentConfig = buildStaticEnvConfig(\n authedPortalId,\n authedHublet,\n authedEnv,\n false,\n jsRenderingGates\n );\n\n try {\n const {\n html: renderedHtml,\n cssNeeded,\n renderContext,\n inlineAssets,\n } = await renderModule(\n viteServer,\n modulePath,\n {\n fieldValues: fieldOverrides,\n hublParameters: {},\n moduleName: `local-${moduleName}`,\n },\n fullOriginalUrlFromRequest(request),\n basePath,\n environmentConfig,\n {\n identifierPrefix: getEntryPointHash(entrypointPath),\n }\n );\n\n const htmlShell = await createHtmlShellDependingOnRenderContext(\n baseTemplatePath,\n request.originalUrl,\n `Module: ${modulePath}`,\n renderContext,\n viteServer,\n jsRenderingGates\n );\n\n const html = htmlShell\n .replace(\n '<!--headend-->',\n [\n cssNeeded,\n ...inlineAssets.map((inlineAsset) => inlineAsset.html),\n ].join('\\n')\n )\n .replace(`<!--ssr-outlet-->`, renderedHtml);\n\n response.status(200).set({ 'Content-Type': 'text/html' }).end(html);\n } catch (e) {\n console.error(e);\n viteServer.ssrFixStacktrace(e);\n\n response\n .status(500)\n .end(`Error rendering module (${moduleName})\\n\\n${e.stack}`);\n }\n};\n\nexport default moduleRouteHandler;\n", "import path from 'path';\nimport { normalizePath } from 'vite';\nimport { Request } from 'express';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport renderModuleFieldsJson from '../lib/renderModuleFieldsJson.js';\n\nconst moduleFieldsJsonRouteHandler = async (request: Request, response) => {\n try {\n sendTrackingRequest('fields-json-route');\n const { webRoot, viteServer } = request.app.locals;\n const { moduleName } = request.params;\n\n const modulePath = normalizePath(\n path.resolve(webRoot, 'components/modules/', moduleName)\n );\n\n const fieldsJson = await renderModuleFieldsJson(viteServer, modulePath);\n\n return response\n .status(200)\n .set({ 'Content-Type': 'application/json' })\n .json(fieldsJson);\n } catch (error) {\n console.error('Error processing module fields.json:', error);\n return response.status(500).json({\n error: 'Failed to process module fields',\n });\n }\n};\n\nexport default moduleFieldsJsonRouteHandler;\n", "import { ViteDevServer } from 'vite';\nimport { join as joinPosix } from 'path/posix';\nimport { hasComponentExtension } from '@hubspot/cms-js-internal';\nimport packagePath from './packagePath.js';\n\nexport const lookForModuleInFolder = async (\n modulePath: string,\n viteServer: ViteDevServer\n): Promise<[any, string]> => {\n let componentModule;\n const insideFolderPath = joinPosix(modulePath, 'index');\n\n try {\n componentModule = await viteServer.ssrLoadModule(insideFolderPath);\n } catch (e) {\n if (!e.message.includes('Failed to load url')) {\n throw e;\n }\n }\n\n return [componentModule, insideFolderPath];\n};\n\nasync function renderModuleFieldsJson(\n viteServer: ViteDevServer,\n requestedModulePath: string\n) {\n let componentModule;\n\n try {\n if (!hasComponentExtension(requestedModulePath)) {\n [componentModule] = await lookForModuleInFolder(\n requestedModulePath,\n viteServer\n );\n }\n\n if (!componentModule) {\n componentModule = await viteServer.ssrLoadModule(requestedModulePath);\n }\n } catch (error) {\n throw new Error(\n `Failed to load module ${requestedModulePath}: ${error.message}`\n );\n }\n\n if (!componentModule) {\n throw new Error(`Couldn't find module: ${requestedModulePath}`);\n }\n\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n const { renderFieldsToJson } =\n await viteServer.ssrLoadModule(internalSsrPath);\n const fieldsJson = renderFieldsToJson(\n componentModule.fields,\n requestedModulePath\n );\n\n return fieldsJson;\n}\n\nexport default renderModuleFieldsJson;\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable require-await */\n\nimport { Hublet } from '@hubspot/cms-components';\nimport http from 'http';\nimport https from 'https';\nimport { getAccountId } from '@hubspot/local-dev-lib/config';\nimport { debug } from '../lib/debug.js';\n\nexport type PortalContentIdAndHublet = {\n portalId: number;\n contentId: string;\n hublet: Hublet;\n};\n\nasync function requestPage(\n url: string,\n redirects = 0,\n originalUrl?: string\n): Promise<{\n portalIdHeader: string | string[];\n contentId: string | string[];\n res: http.IncomingMessage;\n}> {\n if (redirects > 5) {\n throw new Error(\n `Hit too many redirects to HEAD requests for ${originalUrl}`\n );\n }\n\n return new Promise((resolve, reject) => {\n const protocolAPI = url.startsWith('https://') ? https : http;\n protocolAPI\n .request(\n url,\n {\n method: 'HEAD',\n headers: {\n // Keep this user agent, so we don't get 403s from the request\n ['User-Agent']: 'cms-dev-server',\n },\n },\n async (res) => {\n let portalIdHeader: string | string[];\n let contentId: string | string[];\n const isContentMembershipRedirect = Boolean(\n res.headers['x-hs-content-membership-redirect']\n );\n\n if (isContentMembershipRedirect) {\n debug('Content Membership Redirect', res.headers);\n\n portalIdHeader = res.headers['x-hs-portal-id'];\n contentId = res.headers['x-hs-content-id'];\n\n if (portalIdHeader && contentId) {\n // assume we have what we need.\n return resolve({\n portalIdHeader,\n contentId,\n res,\n });\n }\n }\n\n // Use a lib to better follow various redirects?\n if (\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n console.log(`Redirecting to ${res.headers.location} (from ${url})`);\n return resolve(\n requestPage(\n res.headers.location,\n redirects + 1,\n originalUrl ?? url\n )\n );\n }\n\n portalIdHeader = res.headers['x-hs-hub-id'];\n contentId = res.headers['x-hs-content-id'];\n\n return resolve({\n res,\n portalIdHeader,\n contentId,\n });\n }\n )\n .on('error', (err) => {\n console.error(err);\n reject(err);\n })\n .end();\n });\n}\n\nexport default async function fetchContentMetadata(\n url: string,\n portalId: number\n): Promise<PortalContentIdAndHublet> {\n const { portalIdHeader, contentId, res } = await requestPage(url);\n\n if (Array.isArray(portalIdHeader) || Array.isArray(contentId)) {\n throw new Error(\n `There were multiple hub ID or content ID headers in the HEAD request to ${url}`\n );\n } else {\n const portalIdFromResponse = parseInt(portalIdHeader, 10);\n const pageAccount = await getAccountId(portalIdFromResponse);\n\n if (!pageAccount) {\n throw new Error(\n `No CLI auth for portal ${portalIdFromResponse} found, please run \\`hs auth\\``\n );\n }\n\n if (\n res.statusCode !== 200 &&\n !(portalIdFromResponse && pageAccount && contentId)\n ) {\n throw new Error(\n `${res.statusCode} ${\n res.statusMessage\n } - Unable to obtain HEAD information from ${url}. ${\n res.statusCode === 429 && res.headers['retry-after']\n ? `Retry after ${res.headers['retry-after']} seconds.`\n : ''\n }`\n );\n } else if (!portalId || !contentId) {\n throw new Error(\n `Missing hub ID or content ID headers on HEAD request to ${url}`\n );\n } else if (isNaN(portalId)) {\n throw new Error(\n `Hub ID from the HEAD request is not a number: '${portalId}' (${url})`\n );\n }\n\n // TODO, the hubs-hublets/hublets/find/<portalId> API is internal auth only.\uD83E\uDD14...\n // Prior implementation of fetchHubletForPortalId that would work execept for an internal auth issue:\n // https://git.hubteam.com/HubSpot/cms-js-platform/blob/ef6e8029df6c09fe30d65a80073606f41ca324a6/cms-dev-server/src/proxyPage/fetchHubletForPortalId.ts\n //\n // const hublet = await fetchHubletForPortalId(portalId);\n\n const hublet = 'na1';\n\n return { portalId, contentId, hublet };\n }\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable consistent-return */\n\nimport { Request, Response } from 'express';\nimport fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';\nimport proxyPage from '../proxyPage/proxyPage.js';\nimport {\n getSubDomainFromValidLocalDomain,\n consoleWarn,\n} from '../proxyPage/utils.js';\nimport { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';\nimport fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\n\nexport default async function proxyPageRouteHandler(\n request: Request,\n response: Response,\n next: Function\n) {\n sendTrackingRequest('view-proxy-page-route');\n const {\n viteServer,\n webRoot,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n } = request.app.locals;\n\n if (!request.accepts().includes('text/html')) {\n return response.sendStatus(404);\n }\n\n const fullOriginalUrl = fullOriginalUrlFromRequest(request);\n\n const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);\n const urlToProxy = `http://${domainToProxy}${request.originalUrl}`;\n\n if (!domainToProxy) {\n if (VALID_PROXY_DOMAIN_SUFFIXES.includes(request.hostname)) {\n const message = `Can't make a proxy request, you need to prepend the real page's domain to '${request.hostname}' (i.e. your.page.com.${request.hostname})`;\n consoleWarn(message);\n return response.status(400).send(message);\n } else {\n const message = `Can't make a proxy request, the domain '${request.hostname}' is not a valid proxy-able domain`;\n consoleWarn(message);\n return response.status(400).send(message);\n }\n }\n\n try {\n const { portalId, contentId, hublet } = await fetchContentMetadata(\n urlToProxy,\n request.app.locals.authedPortalId\n );\n await proxyPage(\n request,\n response,\n portalId,\n hublet,\n contentId,\n webRoot,\n viteServer,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n urlToProxy,\n fullOriginalUrl\n );\n } catch (e) {\n next(e);\n }\n}\n", "import { Request, Response } from 'express';\nimport request from 'request';\nimport { getSubDomainFromValidLocalDomain } from '../proxyPage/utils.js';\nimport { VALID_PROXY_DOMAIN_SUFFIXES } from '../proxyPage/constants.js';\n\n// From(ish) https://git.hubteam.com/HubSpot/cloudflare-workers/blob/master/worker-lib/src/Constants.ts\nconst HCMS_PATH = '/_hcms/';\nconst HS_FS_PATH = '/hs-fs/';\nconst HUB_FS_PATH = '/hubfs/';\n\nconst isInternalCMSRoute = (req: Request) =>\n req.path.startsWith(HCMS_PATH) ||\n req.path.startsWith(HS_FS_PATH) ||\n req.path.startsWith(HUB_FS_PATH);\n\nexport default function proxyPageResourceRedirect(\n req: Request,\n res: Response,\n next\n) {\n const isAHtmlRequest = req.accepts().includes('text/html');\n\n if (\n (isAHtmlRequest && !isInternalCMSRoute(req)) ||\n VALID_PROXY_DOMAIN_SUFFIXES.includes(req.hostname)\n ) {\n next();\n return;\n }\n\n const domainToProxy = getSubDomainFromValidLocalDomain(req.hostname);\n const pathToProxy = req.originalUrl;\n const urlToProxy = `https://${domainToProxy}${pathToProxy}`;\n\n if (req.method === 'GET') {\n request(urlToProxy).pipe(res);\n } else {\n const contentType = req.headers['content-type'];\n const isSendingJSON =\n contentType && /\\bjson\\b/.test(req.headers['content-type'].toString());\n\n const headerEntries = Object.entries(req.headers).filter(([header]) => {\n if (\n // Need to reset these headers for https (and recompression/encoding?) to work properly\n ['host', 'origin', 'connection', 'content-length'].includes(\n header.toLowerCase()\n ) ||\n header.startsWith('sec-')\n ) {\n return false;\n }\n return true;\n });\n\n let body = undefined;\n\n if (req.body) {\n if (isSendingJSON) {\n body = JSON.stringify(req.body);\n } else {\n body = req.body.toString();\n }\n }\n\n request({\n url: urlToProxy,\n method: req.method,\n headers: Object.fromEntries(headerEntries),\n body,\n }).pipe(res);\n }\n}\n", "import { HubLModule } from '../api/designmanager.js';\nimport { removePreviewPrefix } from '../lib/previewUtils.js';\n\nexport default function HubLModulesList ({ modules }: { modules: HubLModule[] }) {\n return modules.length === 0 ? (\n <p>No modules found.</p>\n ) : (\n <ul>\n {\n modules.map((module) => (\n <li key={module.moduleId}>\n <a href={`/hublmodule/${removePreviewPrefix(module.path)}`}>{removePreviewPrefix(module.path)}</a>\n </li>\n ))\n }\n </ul>\n )\n}\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\n\nconst DESIGN_MANAGER_API_PATH = 'designmanager/v1';\n\ninterface PaginatedApiResponse<T> {\n limit: number;\n objects: T[];\n offset: number;\n total: number;\n totalCount: number;\n}\n\nexport interface HubLModule {\n moduleId: number;\n name: string;\n path: string;\n previewKey: string;\n filename: string;\n fields: any[];\n folderPath: string;\n}\nexport interface HubLTemplate {\n path: string;\n label: string;\n previewKey: string;\n filename: string;\n displayName: string;\n}\nexport interface HubLTemplateData {\n previewKey: string;\n}\nexport interface HubLModuleData {\n previewKey: string;\n moduleId: string;\n}\nexport interface ModulePageDependencyData {\n id: string;\n label: string;\n errors?: string[];\n portalId: number;\n subType: string;\n}\n\nexport async function fetchHubLModules(accountId, previewToken) {\n return (\n await hsCliHttp.get<PaginatedApiResponse<HubLModule>>(accountId, {\n url: `${DESIGN_MANAGER_API_PATH}/modules/local-preview?previewToken=${previewToken}`,\n })\n ).data;\n}\nexport async function fetchPreviewTemplates(accountId, previewToken) {\n return (\n await hsCliHttp.get<PaginatedApiResponse<HubLTemplate>>(accountId, {\n url: `${DESIGN_MANAGER_API_PATH}/templates/local-preview?previewToken=${previewToken}`,\n })\n ).data;\n}\nexport async function fetchModuleByPath(\n accountId: number,\n path: string\n): Promise<any> {\n return (\n await hsCliHttp.get<HubLModuleData>(accountId, {\n url: `${DESIGN_MANAGER_API_PATH}/modules/by-path/${path}?portalId=${accountId}`,\n })\n ).data;\n}\nexport async function fetchTemplateByPath(accountId: number, path: string) {\n return (\n await hsCliHttp.get<HubLTemplateData>(accountId, {\n url: `${DESIGN_MANAGER_API_PATH}/templates/by-path/${path}?portalId=${accountId}`,\n })\n ).data;\n}\nexport async function fetchModulePageDependencies(\n accountId: number,\n path: string\n) {\n const url = `${DESIGN_MANAGER_API_PATH}/modules/list-pages?modulePath=${path}`;\n return (await hsCliHttp.get<ModulePageDependencyData[]>(accountId, { url }))\n .data;\n}\n", "import { HubLTemplate } from '../api/designmanager.js';\nimport { removePreviewPrefix } from '../lib/previewUtils.js';\n\nexport default function HubLTemplatesList ({ templates }: { templates: HubLTemplate[] }) {\n return templates.length === 0 ? (\n <p>No templates found {JSON.stringify(templates)}</p>\n ) : (\n <ul>\n {\n templates.filter(t => isCodedFile(t.filename)).map((template) => (\n <li key={template.previewKey}>\n <a href={`/template/${removePreviewPrefix(template.path)}`}>{removePreviewPrefix(template.path)}</a>\n </li>\n ))\n }\n </ul>\n )\n}\n\nconst TEMPLATE_EXTENSION_REGEX = new RegExp(/(?<!module)\\.html$/);\nexport function isCodedFile(filePath: string): boolean {\n return TEMPLATE_EXTENSION_REGEX.test(filePath);\n}\n", "import {\n findAllModulesInRoot,\n findAllPartialsInRoot,\n renderOnServer,\n} from '@hubspot/cms-js-internal';\nimport { Request, Response } from 'express';\nimport ModulesList from '../components/ModulesList.js';\nimport PartialsList from '../components/PartialsList.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport { getSubDomainFromValidLocalDomain } from '../proxyPage/utils.js';\nimport HubLModulesList from '../components/HubLModulesList.js';\nimport {\n fetchHubLModules,\n fetchPreviewTemplates,\n} from '../api/designmanager.js';\nimport HubLTemplatesList from '../components/HubLTemplatesList.js';\n\nconst homeRouteHandler = async (\n request: Request,\n response: Response,\n next: Function\n) => {\n const domainToProxy = getSubDomainFromValidLocalDomain(request.hostname);\n\n // If this is a request to the root of a _subdomain_ pass through and let the\n // proxy code handle this later (i.e. something.hslocal.net/ instead of hslocal.net/ or localhost/)\n if (domainToProxy) {\n next();\n return;\n }\n\n sendTrackingRequest('view-home-route');\n\n const {\n authedPortalId,\n webRoot,\n storybookEnabled,\n devServerPort,\n localPreviewToken,\n jsRenderingGates,\n } = request.app.locals;\n const isUngatedForUnifiedThemePreview = jsRenderingGates.includes(\n 'CMS:React:UnifiedThemePreview'\n );\n const { partialNames } = findAllPartialsInRoot(webRoot);\n const { moduleNames } = findAllModulesInRoot(webRoot);\n const hublModuleData = await fetchHubLModules(\n authedPortalId,\n localPreviewToken\n );\n const hublTemplateData = await fetchPreviewTemplates(\n authedPortalId,\n localPreviewToken\n );\n\n const { html: responseHtml } = await renderOnServer(\n <>\n {storybookEnabled ? (\n <h2>\n <a href={`//storybook.${request.hostname}:${devServerPort}`}>\n Storybook\n </a>\n </h2>\n ) : null}\n\n <h2>Partials</h2>\n <PartialsList webRoot={webRoot} partialNames={partialNames} />\n <h2>React modules</h2>\n <ModulesList webRoot={webRoot} moduleNames={moduleNames} />\n {isUngatedForUnifiedThemePreview && (\n <>\n <h2>HubL modules</h2>\n <HubLModulesList modules={hublModuleData.objects} />\n <h2>HubL templates</h2>\n <HubLTemplatesList templates={hublTemplateData.objects} />\n </>\n )}\n </>\n );\n response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);\n};\n\nexport default homeRouteHandler;\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable consistent-return */\n\nimport { renderOnServer } from '@hubspot/cms-js-internal';\nimport { Request, Response } from 'express';\nimport fetchContentMetadata from '../proxyPage/fetchContentMetadata.js';\nimport proxyPage from '../proxyPage/proxyPage.js';\nimport { consoleWarn } from '../proxyPage/utils.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\n\nexport default async function proxyPathPageRouteHandler(\n request: Request,\n response: Response,\n next: Function\n) {\n sendTrackingRequest('view-proxy-path-route');\n const {\n viteServer,\n webRoot,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n } = request.app.locals;\n if (!request.accepts().includes('text/html')) {\n return response.sendStatus(404);\n }\n\n // render proxy index page if not supplied with query param\n if (!request.query.page) {\n const { html: responseHtml } = await renderOnServer(\n <div>\n <h2>Local Proxy</h2>\n <form action=\"/proxy\">\n <label htmlFor=\"page\" style={{ display: 'block' }}>\n Page URL\n </label>\n <input\n style={{ width: '300px' }}\n name=\"page\"\n type=\"text\"\n placeholder=\"https://somecmspage.com/path\"\n />\n <button style={{ display: 'block' }}>Proxy</button>\n </form>\n </div>\n );\n response.status(200).set({ 'Content-Type': 'text/html' }).end(responseHtml);\n return;\n }\n // parse proxy page URL from query param\n let proxyPageUrl: URL;\n try {\n proxyPageUrl = new URL(request.query.page as string);\n } catch (e) {\n const message =\n 'Please provide a valid page query parameter, e.g., http://localhost:3000/proxy?page=https://yourdomain.com/path';\n consoleWarn(message);\n response.status(400).send(message);\n return;\n }\n\n // validate proxy page URL query params\n if (proxyPageUrl.searchParams.has('hs_preview')) {\n const message = `Can't make a proxy request, you cannot proxy URLs that include internal query params like hs_preview`;\n consoleWarn(message);\n return response.status(400).send(message);\n }\n\n try {\n const { portalId, contentId, hublet } = await fetchContentMetadata(\n proxyPageUrl.href,\n request.app.locals.authedPortalId\n );\n await proxyPage(\n request,\n response,\n portalId,\n hublet,\n contentId,\n webRoot,\n viteServer,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n proxyPageUrl.href,\n proxyPageUrl.href\n );\n } catch (e) {\n next(e);\n }\n}\n", "import { NextFunction, Request, Response } from 'express';\nimport fetch from 'node-fetch';\n\nconst HCMS_PATH = '/_hcms/';\nconst HS_FS_PATH = '/hs-fs/';\nconst HUB_FS_PATH = '/hubfs/';\n\n// From(ish) https://git.hubteam.com/HubSpot/cloudflare-workers/blob/master/worker-lib/src/Constants.ts\nconst isInternalCMSRoute = (req: Request) =>\n req.path.startsWith(HCMS_PATH) ||\n req.path.startsWith(HS_FS_PATH) ||\n req.path.startsWith(HUB_FS_PATH);\n\nexport default function proxyPathPageResourceRedirect(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const isAHtmlRequest = req.accepts().includes('text/html');\n\n // only proxy when referer's path is /proxy && has page query param\n let proxyPageUrl: URL;\n let refererUrl: URL;\n try {\n refererUrl = new URL(req.headers.referer);\n proxyPageUrl = new URL(\n new URL(req.headers.referer).searchParams.get('page')\n );\n } catch (e) {\n next();\n return;\n }\n if (!refererUrl.pathname.startsWith('/proxy')) {\n next();\n return;\n }\n\n // handle anchor links, unless internal CMS route\n if (isAHtmlRequest && !isInternalCMSRoute(req)) {\n const encodedPageUrl = encodeURIComponent(\n `${proxyPageUrl.origin}${req.url}`\n );\n res.redirect(`/proxy?page=${encodedPageUrl}`);\n return;\n }\n\n const urlToProxy = `https://${proxyPageUrl.host}${req.url}`;\n fetch(urlToProxy)\n .then((response) => response.body.pipe(res))\n .catch((err) => console.log(err));\n}\n", "import { NextFunction, Request, Response } from 'express';\nimport fetch from 'node-fetch';\n\nconst localDomains = ['localhost', 'hslocal.net'];\n\nexport default function proxyServerlessRequest(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const { method, headers } = req;\n\n let refererUrl: URL;\n let domainToProxy: string;\n let body;\n\n if (!req.headers.referer) {\n console.log('unable to proxy serverless request, no referer header found');\n next();\n return;\n }\n\n try {\n refererUrl = new URL(req.headers.referer);\n\n const referrerDomain = refererUrl.hostname;\n\n if (localDomains.includes(referrerDomain)) {\n // pulling off the first domain to proxy for serverless requests because\n // a portals serverless endpoints are supported at all domains\n domainToProxy = req.app.locals.domainsToProxy[0];\n } else {\n domainToProxy = referrerDomain.replace(/\\.localhost|\\.hslocal\\.net/, '');\n }\n } catch (e) {\n console.log('Error parsing referer URL:', e);\n next();\n }\n\n if (!domainToProxy) {\n console.log('No domain to proxy for serverless request, skipping...');\n next();\n return;\n }\n\n const urlToProxy = `${refererUrl.protocol}//${domainToProxy}${req.url}`;\n const contentType = headers['content-type'];\n const cookie = headers.cookie;\n\n if (req.body) {\n body = JSON.stringify(req.body);\n }\n\n const headersToPass: HeadersInit = {\n ...(contentType ? { 'Content-Type': contentType } : {}),\n ...(cookie ? { COOKIE: cookie } : {}),\n };\n\n const proxyLogArgs = [\n `attempting to proxy a ${method} serverless request to domain:`,\n domainToProxy,\n 'for resource:',\n req.url,\n ];\n\n if (body) {\n proxyLogArgs.push('with body:', body);\n }\n\n console.log(...proxyLogArgs);\n\n switch (method) {\n case 'POST':\n case 'DELETE':\n case 'PUT':\n fetch(urlToProxy, {\n method,\n body,\n headers: headersToPass,\n })\n .then((response) => response.body.pipe(res))\n .catch((err) => console.log(err));\n break;\n\n default:\n fetch(urlToProxy, {\n headers: headersToPass,\n })\n .then((response) => response.body.pipe(res))\n .catch((err) => console.log(err));\n }\n}\n", "import path from 'path';\nimport { normalizePath } from 'vite';\nimport { Request, Response } from 'express';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport { createHtmlShellDependingOnRenderContext } from '../lib/templates.js';\nimport packagePath from '../lib/packagePath.js';\nimport fullOriginalUrlFromRequest from '../lib/fullOriginalUrlFromRequest.js';\nimport { renderLocalProjectModulePreview } from '../lib/renderModulePreview.js';\n\nasync function modulePreviewRouteHandler(request: Request, response: Response) {\n sendTrackingRequest('view-module-preview-route');\n const {\n authedPortalId,\n authedEnv,\n authedHublet,\n webRoot,\n viteServer,\n jsRenderingGates,\n projectName,\n projectComponentPath,\n } = request.app.locals;\n const moduleName = request.params.moduleName;\n\n const modulePath = normalizePath(\n path.resolve(webRoot, 'components/modules/', moduleName)\n );\n\n const PREVIEWER_APP_PARAM = 'hsPreviewerApp';\n let fieldOverrides: Record<string, any> = {};\n\n if (request.method === 'POST' && request.body) {\n // If it is a POST from the DesignPreviewer pull off of `module_data` key\n if (\n request.query[PREVIEWER_APP_PARAM] === 'module' &&\n request.body.module_data\n ) {\n fieldOverrides = request.body.module_data;\n } else {\n fieldOverrides = request.body;\n }\n\n try {\n if (typeof fieldOverrides === 'string') {\n const parsedFieldOverrides = JSON.parse(fieldOverrides);\n if (\n parsedFieldOverrides &&\n typeof parsedFieldOverrides === 'object' &&\n !Array.isArray(parsedFieldOverrides)\n ) {\n fieldOverrides = parsedFieldOverrides;\n } else {\n throw new Error('Parsed field overrides must be an object');\n }\n }\n } catch (e) {\n console.error(\n `Error parsing field for module \"${moduleName}\": ${e.message}`,\n '\\nReceived value:',\n fieldOverrides\n );\n }\n } else if (request.query.fields) {\n try {\n if (typeof request.query.fields === 'string') {\n fieldOverrides = JSON.parse(\n decodeURIComponent(request.query.fields.replace(/\\+/g, '%20'))\n );\n }\n } catch (e) {\n console.error(\n `Error parsing field param for module ${moduleName}: ${request.query.fields}`\n );\n }\n }\n\n try {\n // render component from comment placeholder\n const {\n html: renderedHtml,\n cssNeeded,\n renderContext,\n inlineAssets,\n } = await renderLocalProjectModulePreview(\n moduleName,\n authedPortalId,\n authedEnv,\n authedHublet,\n webRoot,\n viteServer,\n jsRenderingGates,\n projectName,\n projectComponentPath,\n fullOriginalUrlFromRequest(request),\n request.get('COOKIE'),\n fieldOverrides\n );\n\n // inject rendered component into Vite base development template\n const baseTemplatePath = packagePath(\n import.meta.url,\n 'html/baseTemplate.html'\n );\n const htmlShell = await createHtmlShellDependingOnRenderContext(\n baseTemplatePath,\n request.originalUrl,\n `Module: ${modulePath}`,\n renderContext,\n viteServer,\n jsRenderingGates\n );\n\n const html = htmlShell\n .replace(\n '<!--headend-->',\n [\n cssNeeded,\n ...inlineAssets.map((inlineAsset) => inlineAsset.html),\n ].join('\\n')\n )\n .replace(`<!--ssr-outlet-->`, renderedHtml);\n\n response.status(200).set({ 'Content-Type': 'text/html' }).end(html);\n } catch (e) {\n console.error(e);\n viteServer.ssrFixStacktrace(e);\n return response\n .status(500)\n .end(`Error rendering module (${moduleName})\\n\\n${e.stack}`);\n }\n}\n\nexport default modulePreviewRouteHandler;\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport { Request } from 'express';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport { addRefreshScript, buildHTMLResponse, getPreviewUrl } from '../lib/previewUtils.js';\nimport { fetchModuleByPath } from '../api/designmanager.js';\n\nexport const hublModuleRouteHandler = async (request: Request, response) => {\n sendTrackingRequest('view-hubl-module-route');\n const { authedPortalId, localPreviewToken } = request.app.locals;\n const { modulePath } = request.params;\n\n if (!modulePath) {\n response.status(200).set({ 'Content-Type': 'text/html' }).end(buildModuleIndex());\n return;\n }\n\n const calculatedPath = `@preview/${localPreviewToken}/${modulePath}.module`;\n let customWidgetInfo;\n try {\n customWidgetInfo = await fetchModuleByPath(authedPortalId, calculatedPath);\n } catch (err) {\n console.log(`Failed to fetch module data for ${calculatedPath}`);\n }\n\n const params = {\n module_id: customWidgetInfo.moduleId,\n hs_preview_key: customWidgetInfo.previewKey,\n updated: Date.now(),\n ...request.query\n }\n const previewUrl = new URL(getPreviewUrl(request, params)) ;\n try {\n const result = (await hsCliHttp.get<string>(authedPortalId, {\n baseURL: previewUrl.origin,\n url: previewUrl.pathname,\n params,\n })).data;\n const html = addRefreshScript(result);\n response.status(200).set({ 'Content-Type': 'text/html' }).end(html);\n } catch (err) {\n console.log(err)\n response.status(500).set({ 'Content-Type': 'text/html' }).end(buildErrorIndex(err));\n }\n}\n\nconst buildErrorIndex = (err) => buildHTMLResponse(`\n <div>\n <h2>Module</h2>\n <p>ERROR</p>\n </div>\n`);\n\nconst buildModuleIndex = () => buildHTMLResponse(`\n <div>\n <h2>Module</h2>\n <p>Please provide a module path in the request</p>\n </div>\n`);\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport { addRefreshScript, buildHTMLResponse, getPreviewUrl } from '../lib/previewUtils.js';\nimport sendTrackingRequest from '../lib/trackUsage.js';\nimport { Request } from 'express';\nimport { fetchTemplateByPath } from '../api/designmanager.js';\nimport {\n infillReactModulesAndWriteResponse,\n} from '../proxyPage/proxyPage.js';\nimport {\n buildStaticEnvConfig,\n} from '@hubspot/cms-components';\nimport { getEnv } from '@hubspot/local-dev-lib/config';\n\nexport const templateRouteHandler = async (request: Request, response) => {\n sendTrackingRequest('view-template-route');\n const {\n authedPortalId,\n localPreviewToken,\n projectName,\n viteServer,\n webRoot,\n projectComponentPath,\n jsRenderingGates\n } = request.app.locals;\n\n const environmentConfig = buildStaticEnvConfig(\n authedPortalId,\n 'na1',\n getEnv(authedPortalId) as any,\n false,\n jsRenderingGates\n );\n\n const { templatePath } = request.params;\n\n if (!templatePath) {\n response.status(200).set({ 'Content-Type': 'text/html' }).end(buildTemplateIndex());\n return;\n }\n\n const calculatedPath = `@preview/${localPreviewToken}/${templatePath}`;\n let templateInfo;\n try {\n templateInfo = await fetchTemplateByPath(authedPortalId, calculatedPath);\n } catch(err) {\n console.error(`Failed to fetch template data for ${calculatedPath}: ${err}`);\n }\n if (!templateInfo || !('previewKey' in templateInfo)) {\n response.status(500).set({ 'Content-Type': 'text/html' }).end(buildErrorIndex());\n return;\n }\n const localProxyProject = process.env.DEFAULT_MODULE_PATH_REWRITE\n ? `@default-modules/${projectName}`\n : `@projects/${projectName}`;\n\n const params = {\n template_file_path: calculatedPath,\n hs_preview_key: templateInfo.previewKey,\n localPreviewToken,\n hsLocalProxyProject: localProxyProject,\n localProxySchemaVersion: '2',\n hsLoginVerifyDisabled: `${true}`,\n ...request.query\n }\n const previewUrl = new URL(getPreviewUrl(request, params));\n try {\n const result = (await hsCliHttp.get<string>(authedPortalId, {\n baseURL: previewUrl.origin,\n url: previewUrl.pathname,\n params,\n })).data;\n const pageHtml = addRefreshScript(result);\n infillReactModulesAndWriteResponse(\n response,\n pageHtml,\n webRoot,\n 'fullOriginalUrl',\n environmentConfig,\n viteServer,\n projectName,\n projectComponentPath,\n jsRenderingGates,\n false,\n )\n } catch (err) {\n response.status(500).set({ 'Content-Type': 'text/html' }).end(buildErrorIndex());\n }\n}\n\n\nfunction buildErrorIndex () {\n return buildHTMLResponse(`\n <div>\n <h2>Error</h2>\n <p>Failed to fetch template data.</p>\n </div>\n `);\n}\n\nfunction buildTemplateIndex (){\n return buildHTMLResponse(`\n <div>\n <h2>Template</h2>\n <p>Please provide a template path in the request</p>\n </div>\n `);\n}\n", "import path from 'path';\nimport { normalizePath } from 'vite';\nimport {\n findAllModulesInRoot,\n findAllPartialsInRoot,\n} from '@hubspot/cms-js-internal';\nimport renderModuleFieldsJson from './renderModuleFieldsJson.js';\nimport { isCodedFile } from '../components/HubLTemplatesList.js';\nimport {\n fetchHubLModules,\n fetchPreviewTemplates,\n HubLModule,\n HubLTemplate,\n} from '../api/designmanager.js';\n\nexport enum ModuleType {\n REACT = 'react',\n HUBL = 'hubl',\n}\n\nexport interface ModuleData {\n name: string;\n type: ModuleType;\n nameWithExtension?: string;\n subPath?: string;\n extension?: string;\n fieldsJson?: any;\n}\n\nexport interface PartialData {\n name: string;\n subPath: string;\n}\nexport interface TemplateData {\n name: string;\n subPath: string;\n}\n\nexport interface DevServerUIData {\n authedPortalId: number;\n projectName: string;\n modulesData: ModuleData[];\n hubLModules: ModuleData[];\n partialsData: PartialData[];\n hubLTemplates: TemplateData[];\n themeWebRoot: string;\n [key: string]: any;\n}\nexport interface RequestLocals {\n themeWebRoot: string;\n authedPortalId: number;\n authedEnv: string;\n authedHublet: string;\n projectName: string;\n webRootProjectComponentFolder: string;\n localPreviewToken: string;\n viteServer: any;\n}\n\ntype ModulesData = ReturnType<typeof findAllModulesInRoot>;\nfunction mapReactModules(\n modules: ModulesData,\n themeWebRoot,\n viteServer\n): Promise<ModuleData[]> {\n return Promise.all(\n modules.moduleNames.map(async (name, index) => {\n const modulePath = normalizePath(\n path.resolve(themeWebRoot, 'components/modules/', name)\n );\n const fieldsJson = await renderModuleFieldsJson(viteServer, modulePath);\n return {\n name,\n type: ModuleType.REACT,\n subPath: modules.moduleSubpaths[index],\n nameWithExtension: modules.moduleNamesWithExtension[index],\n extension: modules.moduleExtensions[index],\n fieldsJson,\n };\n })\n );\n}\n\nfunction normalizeHubLModules(modules: HubLModule[]): ModuleData[] {\n return modules.map((module) => ({\n name: module.name,\n type: ModuleType.HUBL,\n subPath: `@projects/${module.path.split('/@projects/')[1] || module.path}`,\n nameWithExtension: module.filename,\n fieldsJson: module.fields,\n }));\n}\n\ntype PartialsData = ReturnType<typeof findAllPartialsInRoot>;\nfunction normalizePartialsData(partialData: PartialsData): PartialData[] {\n return partialData.partialNames.map((name, index) => ({\n name,\n subPath: partialData.partialSubpaths[index],\n }));\n}\nfunction normalizeTemplatesData(templates: HubLTemplate[]): TemplateData[] {\n return templates.map((template) => ({\n name: template.displayName || template.label,\n subPath: `@projects/${\n template.path.split('/@projects/')[1] || template.path\n }`,\n }));\n}\n\nexport async function getDevServerUIData(\n reqLocals: RequestLocals\n): Promise<DevServerUIData> {\n const {\n themeWebRoot,\n authedEnv,\n authedPortalId,\n projectName,\n localPreviewToken,\n webRootProjectComponentFolder,\n viteServer,\n } = reqLocals;\n const modulesData = findAllModulesInRoot(themeWebRoot);\n const partialsData = findAllPartialsInRoot(themeWebRoot);\n const reactModules = await mapReactModules(\n modulesData,\n themeWebRoot,\n viteServer\n );\n\n let hubLModuleData = { objects: [] };\n let hubLTemplateData = { objects: [] };\n if (authedPortalId) {\n // @todo: make all the async data use Promise.all, especially API calls\n hubLModuleData = await fetchHubLModules(authedPortalId, localPreviewToken);\n hubLTemplateData = await fetchPreviewTemplates(\n authedPortalId,\n localPreviewToken\n );\n }\n const hubLTemplates =\n hubLTemplateData?.objects.filter((template) =>\n isCodedFile(template.filename)\n ) || [];\n\n const mappedHubLModules = normalizeHubLModules(hubLModuleData?.objects || []);\n\n return {\n authedPortalId,\n authedEnv,\n projectName,\n modulesData: reactModules,\n partialsData: normalizePartialsData(partialsData),\n hubLModules: mappedHubLModules || [],\n hubLTemplates: normalizeTemplatesData(hubLTemplates),\n themeWebRoot,\n webRootProjectComponentFolder,\n };\n}\n\nexport default getDevServerUIData;\n", "import { Router, Request, Response, NextFunction } from 'express';\nimport { spawn } from 'child_process';\nimport { fetchModulePageDependencies } from '../api/designmanager.js';\n\nfunction getOpenCommand() {\n switch (process.platform) {\n case 'darwin':\n return 'open';\n case 'win32':\n return 'start';\n default:\n return 'xdg-open';\n }\n}\n\nexport async function handleGetModulePages(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const { path, portalId } = req.query;\n\n if (!path || !portalId) {\n return res.status(400).json({ error: 'Missing required parameters' });\n }\n\n try {\n const data = await fetchModulePageDependencies(\n Number(portalId),\n path as string\n );\n res.json(data);\n } catch (err) {\n next(err);\n }\n}\n\nexport function handleOpenFile(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const { path } = req.query;\n\n if (!path) {\n return res.status(400).json({ error: 'Missing required parameters' });\n }\n\n try {\n const command = getOpenCommand();\n spawn(command, [path as string], { detached: true }).unref();\n res.sendStatus(200);\n } catch (err) {\n next(err);\n }\n}\n\nexport function createAppServerRoutes() {\n const router = Router();\n\n router.get('/module-pages', handleGetModulePages);\n router.get('/open-file', handleOpenFile);\n\n return router;\n}\n\nexport default createAppServerRoutes;\n", "import net from 'net';\nimport express from 'express';\n\nimport createShadowDevServerRoutes from './createShadowDevServerRoutes.js';\n\nconst testNetServer = net.createServer();\n\nexport default async function startShadowDevServer(\n devServerPort: number,\n shadowPort: number,\n themePath: string\n) {\n const portIsTaken = await new Promise((res, rej) => {\n console.log(`Starting proxy link server on port ${shadowPort}`);\n\n testNetServer.once('error', (err) => {\n if (err['code'] === 'EADDRINUSE') {\n console.error(\n `Port ${shadowPort} is in use. HubSpot is unable to automatically create proxy links in the Sprocket Menu`\n );\n res(true);\n } else {\n rej(err);\n }\n });\n\n testNetServer.once('listening', () => {\n testNetServer.close();\n });\n\n testNetServer.once('close', () => {\n res(false);\n });\n\n testNetServer.listen(shadowPort);\n });\n\n if (portIsTaken) {\n return;\n }\n\n const shadowDevServer = express();\n\n shadowDevServer.listen(shadowPort);\n\n shadowDevServer.use(\n '/',\n await createShadowDevServerRoutes(devServerPort, themePath)\n );\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable require-await */\n\nimport { Router, Request, Response } from 'express';\nimport { ParsedQs } from 'qs';\nimport { getAccountId } from '@hubspot/local-dev-lib/config';\nimport cors from 'cors';\n\nimport fetchPreviewInfo from '../proxyPage/fetchPreviewInfo.js';\n\ninterface CheckHandlerQuery extends ParsedQs {\n hostName: string;\n pathName: string;\n protocol: string;\n contentId: string;\n portalId: string;\n}\n\nfunction getShadowDevServerCheckHandler(\n devServerPort: number,\n themePath: string\n) {\n return async function shadowDevServerCheckHandler(\n request: Request,\n response: Response\n ) {\n const { query } = request;\n\n if (query) {\n const {\n hostName,\n pathName,\n contentId,\n portalId: portalIdString,\n } = query as CheckHandlerQuery;\n const portalId = parseInt(portalIdString, 10);\n\n let accountId: number;\n let isTemplateFromDevTheme = false;\n let localProxyUrl: string;\n\n try {\n accountId = getAccountId(portalId);\n\n if (accountId === null) {\n throw new Error();\n }\n } catch (e) {\n response\n .status(500)\n .end(\n `Unable to find account for hubid = ${portalId}. Please check your hubspot.config.yaml`\n );\n\n return;\n }\n\n try {\n const { templatePath } = await fetchPreviewInfo(\n accountId,\n portalId,\n contentId\n );\n\n if (templatePath.startsWith(themePath)) {\n isTemplateFromDevTheme = true;\n localProxyUrl = `http://${hostName}.hslocal.net:${devServerPort}${pathName}`;\n }\n\n response.status(200).set({ 'Content-Type': 'application/json' }).json({\n isTemplateFromDevTheme,\n localProxyUrl,\n });\n } catch (error) {\n response\n .status(500)\n .end(\n `Failed proxy render of page id = ${contentId} hub id = ${portalId}\\n\\n${error.stack}`\n );\n return;\n }\n } else {\n response\n .status(500)\n .end(\n `Missing pageUrl param, cannot check for proxied page without a pageUrl`\n );\n }\n };\n}\n\nexport default async function createShadowDevServerRoutes(\n devServerPort: number,\n themePath: string\n) {\n const shadowDevServerRoutes = Router();\n\n shadowDevServerRoutes.get(\n '/check-if-local-dev-server',\n cors(),\n getShadowDevServerCheckHandler(devServerPort, themePath)\n );\n\n return shadowDevServerRoutes;\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable require-await */\n\nimport { createServer as createViteServer, InlineConfig } from 'vite';\nimport { default as react } from '@vitejs/plugin-react';\nimport {\n Gate,\n clientIslandEntryPlugin,\n resolveIslandPlugin,\n noncePlaceholderPlugin,\n findCmsModules,\n} from '@hubspot/cms-js-internal';\nimport { default as mkcert } from 'vite-plugin-mkcert';\nimport { viteCommonjs } from '@originjs/vite-plugin-commonjs';\nimport devSecretsPlugin from './plugins/devSecretsPlugin.js';\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\n\nexport function getPackageJson(packagePath: string) {\n return JSON.parse(readFileSync(join(packagePath, 'package.json')).toString());\n}\n\nexport function getDepsForPackage(packagePath: string): string[] {\n const packageJson = getPackageJson(packagePath);\n\n return packageJson.dependencies ? Object.keys(packageJson.dependencies) : [];\n}\n\nexport function getDepsForPackageIfExists(packagePath: string): string[] {\n try {\n return getDepsForPackage(packagePath);\n } catch (e) {\n console.log('No package.json at ', packagePath);\n return [];\n }\n}\n\n\nasync function createViteDevServer(\n webRoot: string,\n port,\n sslEnabled: boolean,\n domainsToProxy = [],\n jsRenderingGates: Gate[],\n secretNames: string[]\n) {\n const additionalMkcertHosts = domainsToProxy\n .map((proxyDomain) => [\n `${proxyDomain}.localhost`,\n `${proxyDomain}.hslocal.net`,\n ])\n .flat();\n\n if (process.env.VITE_ORIGIN) {\n console.log(`\\nCustom origin: ${process.env.VITE_ORIGIN}\\n`);\n }\n\n const origin =\n process.env.VITE_ORIGIN ??\n (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);\n\n const consumerDeps = getDepsForPackageIfExists(webRoot);\n const isProjectWithReact = consumerDeps.includes('@hubspot/cms-components')\n const ssrAndOptimizeDep = isProjectWithReact ? {\n ssr: {\n // TODO: might need more entries here to get things to resolve through\n // resolveWebRootDepsPlugin\n noExternal: '@hubspot/cms-components',\n },\n resolve: {\n conditions: ['server'],\n dedupe: ['react', 'react-dom', '@hubspot/cms-components', 'styled-jsx'],\n },\n optimizeDeps: {\n include: ['react', 'react-dom', 'react-dom/client'],\n },\n } : {};\n const reactAndIslandsPlugins = (isProjectWithReact || process.env.VITEST) ? [\n react({\n babel: {\n plugins: [\n 'babel-plugin-styled-components',\n 'styled-jsx/babel',\n 'macros',\n ],\n },\n }),\n clientIslandEntryPlugin(),\n resolveIslandPlugin(),\n jsRenderingGates.includes('CMS:JSRenderer:RemoveCjsPlugin')\n ? null\n : viteCommonjs(),\n devSecretsPlugin(secretNames),\n noncePlaceholderPlugin()\n ] : [];\n const viteConfig: InlineConfig = {\n appType: 'custom',\n server: {\n middlewareMode: true,\n host: 'hslocal.net',\n origin,\n hmr: {\n protocol: sslEnabled ? 'wss' : undefined,\n },\n },\n root: webRoot,\n ...ssrAndOptimizeDep,\n plugins: [\n jsRenderingGates.includes('CMS:JSRenderer:AnalyzeCmsModules')\n ? findCmsModules()\n : null,\n sslEnabled ? mkcert({ hosts: additionalMkcertHosts }) : null,\n ...reactAndIslandsPlugins\n ],\n css: {\n postcss: webRoot,\n },\n envDir: webRoot,\n envPrefix: 'HS_',\n };\n\n return createViteServer(viteConfig);\n}\n\nexport default createViteDevServer;\n", "import { Plugin } from 'vite';\n\nexport default function devSecretsPlugin(\n secretNames: Array<string> = []\n): Plugin {\n return {\n name: 'dev-secrets',\n config: () => {\n return {\n define: {\n 'import.meta.env.secretNames': secretNames,\n },\n };\n },\n };\n}\n", "/* hs-eslint ignored failing-rules */\n/* eslint-disable require-await */\nimport {\n createServer as createViteServer,\n InlineConfig,\n ViteDevServer,\n} from 'vite';\nimport { default as react } from '@vitejs/plugin-react';\nimport {\n clientIslandEntryPlugin,\n resolveIslandPlugin,\n} from '@hubspot/cms-js-internal';\n\nasync function createAppServer(\n webRoot,\n port,\n sslEnabled\n): Promise<ViteDevServer> {\n const origin =\n process.env.VITE_ORIGIN ??\n (sslEnabled ? `https://hslocal.net:${port}` : `http://hslocal.net:${port}`);\n\n const viteConfig: InlineConfig = {\n server: {\n middlewareMode: true,\n host: 'hslocal.net',\n origin,\n hmr: {\n protocol: sslEnabled ? 'wss' : undefined,\n },\n },\n appType: 'custom',\n root: webRoot,\n ssr: {\n noExternal: '@hubspot/cms-components',\n },\n resolve: {\n conditions: ['server'],\n dedupe: ['react', 'react-dom', '@hubspot/cms-components', 'styled-jsx'],\n alias: {\n '@': webRoot,\n },\n },\n optimizeDeps: {\n include: ['react', 'react-dom', 'react-dom/client'],\n },\n plugins: [\n react({\n babel: {\n plugins: [\n 'babel-plugin-styled-components',\n 'styled-jsx/babel',\n 'macros',\n ],\n },\n }),\n clientIslandEntryPlugin(),\n resolveIslandPlugin(),\n ],\n css: {\n postcss: webRoot,\n },\n envDir: webRoot,\n envPrefix: 'HS_',\n };\n const viteServer = await createViteServer(viteConfig);\n\n // app.use('/api', createAppServerRoutes());\n\n // app.use(viteServer.middlewares);\n\n // app.get('/*', async (req, res) => {\n // try {\n // const initialProps = await getDevServerUIData({\n // ...reqLocals,\n // viteServer,\n // });\n\n // const url = req.originalUrl.replace('/', '');\n // let template = await fs.readFile(`${webRoot}/index.html`, 'utf-8');\n // template = await viteServer.transformIndexHtml(url, template);\n // const { render } = await viteServer.ssrLoadModule(\n // `${webRoot}/serverEntry.tsx`\n // );\n\n // const rendered = await render(initialProps);\n\n // const html = template\n // .replace(`<!--app-head-->`, rendered.head ?? '')\n // .replace(`<!--app-html-->`, rendered.html ?? '')\n // .replace(\n // `<!--app-script-->`,\n // `<script>window.__hsInitialProps = ${JSON.stringify(\n // initialProps\n // )}</script>` ?? ''\n // );\n\n // res.status(200).set({ 'Content-Type': 'text/html' }).send(html);\n // } catch (e) {\n // viteServer?.ssrFixStacktrace(e);\n // console.log(e.stack);\n // res.status(500).end(e.stack);\n // }\n // });\n\n // app.use((err, req, res, __next) => {\n // console.error('API Error:', err);\n // res.status(500).json({ error: 'Internal server error' });\n // });\n\n // app.listen(port, () => {\n // console.log(`Server started at http://localhost:${port}`);\n // });\n return viteServer;\n}\n\nexport default createAppServer;\n", "import net from 'net';\nimport http from 'http';\nimport https from 'https';\n\nfunction requireHTTPS(\n message: http.IncomingMessage,\n response: http.ServerResponse\n) {\n const newLocation = `https://${message.headers.host}${message.url}`;\n\n response\n .writeHead(302, {\n Location: newLocation,\n })\n .end();\n}\n\n// Running http and https servers on the same port pulled from https://stackoverflow.com/a/42019773\nexport function createHttpsRedirectingServer(opts, handler) {\n const innerHTTPServer = http.createServer(requireHTTPS);\n const innerHTTPSServer = https.createServer(opts, handler);\n\n const server = net.createServer((socket) => {\n socket.once('data', (buffer) => {\n // Pause the socket\n socket.pause();\n\n // Determine if this is an HTTP(s) request\n const byte = buffer[0];\n\n let protocol: string;\n if (byte === 22) {\n protocol = 'https';\n } else if (32 < byte && byte < 127) {\n protocol = 'http';\n } else {\n throw new Error(\n 'Unknown issue with incoming data, unknown if http or https'\n );\n }\n\n const proxy = protocol === 'http' ? innerHTTPServer : innerHTTPSServer;\n if (proxy) {\n // Push the buffer back onto the front of the data stream\n socket.unshift(buffer);\n\n // Emit the socket to the HTTP(s) server\n proxy.emit('connection', socket);\n }\n\n // As of NodeJS 10.x the socket must be\n // resumed asynchronously or the socket\n // connection hangs, potentially crashing\n // the process. Prior to NodeJS 10.x\n // the socket may be resumed synchronously.\n process.nextTick(() => socket.resume());\n });\n });\n\n return { server, innerHTTPServer, innerHTTPSServer };\n}\n", "import { fetchAccessToken } from '@hubspot/local-dev-lib/api/localDevAuth';\nimport { Gate, ENABLED_FEATURES_GATE_MAP } from '@hubspot/cms-js-internal';\nimport { getGatesFromEnv } from './gates.js';\nimport { HSEnvironment } from '@hubspot/cms-components';\n\ntype EnabledFeatures = {\n [name: string]: number;\n};\n\nexport const mapEnabledFeaturesToGates = (\n enabledFeatures: EnabledFeatures\n): Gate[] => {\n return Object.keys(enabledFeatures).reduce((gates, enabledFeature) => {\n if (enabledFeatures[enabledFeature]) {\n gates.push(ENABLED_FEATURES_GATE_MAP[enabledFeature]);\n }\n\n return gates;\n }, []);\n};\n\nexport default async function getJsRenderingGates(\n portalId: number,\n env: HSEnvironment,\n personalAccessKey: string\n): Promise<Gate[]> {\n const {\n data: { enabledFeatures },\n } = await fetchAccessToken(personalAccessKey, env, portalId);\n\n const envGates = getGatesFromEnv();\n const gates = mapEnabledFeaturesToGates(enabledFeatures);\n const mergedGates = [...envGates, ...gates];\n\n process.env.GATES = mergedGates.join(',');\n\n return mergedGates;\n}\n", "import { Gate } from '@hubspot/cms-js-internal';\n\nexport function getGatesFromEnv(): Gate[] {\n const gates = process.env.GATES ? process.env.GATES.split(',') : [];\n\n return gates as Gate[];\n}\n", "import { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\nimport { isMissingScopeError, MissingScopeError } from '../lib/errors.js';\n\ninterface DomainResult {\n domain: string;\n isUsedForBlogPost: boolean;\n isUsedForSitePage: boolean;\n isUsedForLandingPage: boolean;\n}\n\ninterface DomainsResponse {\n total: number;\n results: DomainResult[];\n}\n\nexport async function fetchDomains(portalId: number): Promise<DomainResult[]> {\n try {\n // Works with oauth if content-custom-domain-read scope present (from cms.domains.read scope group)\n const result = (await hsCliHttp.get(portalId, {\n url: `/cms/v3/domains`,\n params: { portalId },\n responseType: 'json',\n })).data as DomainsResponse;\n\n return result.results;\n } catch (error) {\n if (isMissingScopeError(error)) {\n throw new MissingScopeError(error);\n }\n throw error;\n }\n}\n\nexport async function fetchWebsiteDomainNames(portalId: number) {\n const domains = await fetchDomains(portalId);\n\n const filteredDomains = domains.filter((domain) => {\n return (\n domain.isUsedForBlogPost ||\n domain.isUsedForSitePage ||\n domain.isUsedForLandingPage\n );\n });\n\n const domainNames = filteredDomains.map((r) => r.domain);\n return domainNames;\n}\n", "const MISSING_SCOPE_ERROR_PREFIX = `Your personal access key is missing required scopes fetch domains.\\nYou may need to re-generate a new personal access key with the required scopes and re-run \\`hs-auth\\`, or you may not have this functionality enabled in your account\\n`;\nconst OAUTH_ERROR_REGEX =\n /^This oauth-token \\([\\w]+\\) does not have proper permissions!/;\nconst NOT_PUBLIC_USE_ERROR = `The scope needed for this API call isn't available for public use`;\n\nexport class MissingScopeError extends Error {\n constructor(error) {\n let messageEnd = '';\n if (error.error.message.match(OAUTH_ERROR_REGEX)) {\n messageEnd = error.error.message;\n }\n\n super(`${MISSING_SCOPE_ERROR_PREFIX}\\n${messageEnd}`);\n\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, MissingScopeError.prototype);\n }\n}\n\nexport function logMissingScopeWarning(error: MissingScopeError) {\n console.warn(error.message);\n}\n\nexport function isMissingScopeError(error) {\n return (\n error.statusCode === 403 &&\n (error.error.message.match(OAUTH_ERROR_REGEX) ||\n error.error.message.startsWith(NOT_PUBLIC_USE_ERROR))\n );\n}\n\nexport function handleSecretsError(error) {\n if (error && error.statusCode && error.error) {\n const { statusCode, error: errorDetails } = error;\n\n if (errorDetails?.category === 'MISSING_SCOPES') {\n console.log(\n '\\nMissing scopes for secrets.',\n '\\nSecrets require Serverless functions which are scoped to Enterprise portals.\\n'\n );\n } else {\n console.error(`Error ${statusCode}: ${errorDetails.message}`);\n\n if (errorDetails.correlationId) {\n console.error(`Correlation ID: ${errorDetails.correlationId}`);\n }\n\n if (errorDetails.category) {\n console.error(`Category: ${errorDetails.category}`);\n }\n\n if (errorDetails.links) {\n if (errorDetails.links.support) {\n console.error(`Support URL: ${errorDetails.links.support}`);\n }\n\n if (errorDetails.links.forum) {\n console.error(`Forum URL: ${errorDetails.links.forum}`);\n }\n }\n }\n } else {\n console.error('Unexpected error structure:', error);\n }\n}\n", "import path from 'path';\nimport fs from 'fs';\nimport select from '@inquirer/select';\n\nimport { http as hsCliHttp } from '@hubspot/local-dev-lib/http';\n\nconst HSPROJECT_JSON = 'hsproject.json';\n\nexport function checkFileExists(filePath: string) {\n return fs.existsSync(filePath) && fs.statSync(filePath).isFile();\n}\n\nexport function findHSProjectJson(startPath): string | null {\n let currentDir = startPath;\n let dirLevel = 0;\n const maxDirLevel = 4;\n\n while (path.dirname(currentDir) !== currentDir && dirLevel < maxDirLevel) {\n const filePath = path.join(currentDir, HSPROJECT_JSON);\n\n if (checkFileExists(filePath)) {\n return filePath;\n }\n\n currentDir = path.dirname(currentDir);\n dirLevel++;\n }\n\n console.log(\n `'${HSPROJECT_JSON}' not found in any parent of dev server target`\n );\n return null;\n}\n\nexport default async function validateHSPlatform(\n projectConfigPath: string,\n portalId: number\n): Promise<Boolean> {\n if (projectConfigPath === null) {\n console.log(\n `Unable to find local ${HSPROJECT_JSON}, skipping platform version validation.`\n );\n return false;\n }\n\n const hsProjectJSONContents = fs.readFileSync(projectConfigPath, 'utf8');\n const hsProjectJSONData = JSON.parse(hsProjectJSONContents);\n\n const { platformVersion } = hsProjectJSONData;\n\n let platformVersionResult;\n\n try {\n platformVersionResult = (await hsCliHttp.get(portalId, {\n url: `developer/projects/v1/platformVersion`,\n responseType: 'json',\n })).data;\n } catch (e) {\n console.error(e.message);\n console.log(\n 'Unable to find active platform versions, skipping platform version validation.'\n );\n\n return false;\n }\n\n if (\n platformVersion === undefined ||\n !platformVersionResult.activePlatformVersions.includes(platformVersion)\n ) {\n const answer = await select({\n message:\n 'Your local \"hsproject.json\" does not have a valid platform version, please select a valid platform version. You can read more about Platform Versioning here https://developers.hubspot.com/docs/platform/platform-versioning',\n choices: platformVersionResult.activePlatformVersions.map(\n (versionNumber) => ({\n name: versionNumber,\n value: versionNumber,\n })\n ),\n });\n\n hsProjectJSONData.platformVersion = answer;\n\n try {\n fs.writeFileSync(\n projectConfigPath,\n JSON.stringify(hsProjectJSONData, undefined, 2),\n 'utf8'\n );\n\n return true;\n } catch (e) {\n console.error(\n `unable to write updated valid platform version, please make sure platformVersion in \"${HSPROJECT_JSON}\" is one of ${platformVersionResult.activePlatformVersions}`\n );\n\n return false;\n }\n }\n\n return true;\n}\n", "import { writeFileSync } from \"fs\";\nimport ts from \"typescript\";\nconst fieldTypeNameByType = {\n alignment: \"AlignmentFieldType\",\n audioplayer: \"AudioFieldType\",\n backgroundimage: \"BackgroundImageFieldType\",\n blog: \"BlogFieldType\",\n boolean: \"BooleanFieldType\",\n border: \"BorderFieldType\",\n choice: \"ChoiceFieldType\",\n color: \"ColorFieldType\",\n crmobject: \"CrmObjectFieldType\",\n cta: \"CtaFieldType\",\n date: \"DateFieldType\",\n datetime: \"DateTimeFieldType\",\n email: \"EmailFieldType\",\n embed: \"EmbedFieldType\",\n file: \"FileFieldType\",\n followupemail: \"FollowUpEmailFieldType\",\n font: \"FontFieldType\",\n form: \"FormFieldType\",\n gradient: \"GradientFieldType\",\n group: \"GroupFieldType\",\n html: \"HtmlFieldType\",\n hubdbrow: \"HubDbRowFieldType\",\n hubdbtable: \"HubDbTableFieldType\",\n hubl: \"HublFieldType\",\n icon: \"IconFieldType\",\n image: \"ImageFieldType\",\n link: \"LinkFieldType\",\n logo: \"LogoFieldType\",\n meeting: \"MeetingFieldType\",\n menu: \"MenuFieldType\",\n number: \"NumberFieldType\",\n page: \"PageFieldType\",\n payment: \"PaymentFieldType\",\n podcast: \"PodcastFieldType\",\n richtext: \"RichTextFieldType\",\n salesforcecampaign: \"SfdcCamapaignFieldType\",\n simplemenu: \"SimpleMenuFieldType\",\n spacing: \"SpacingFieldType\",\n survey: \"SurveyFieldType\",\n tag: \"TagFieldType\",\n textalignment: \"TextAlignmentFieldType\",\n text: \"TextFieldType\",\n url: \"UrlFieldType\",\n videoplayer: \"VideoFieldType\",\n workflow: \"WorkflowFieldType\"\n};\nfunction getFieldEntries(fields) {\n if (!Array.isArray(fields)) {\n return void 0;\n }\n return fields.filter((field) => field.name && field.type).map((field) => {\n const { name, type } = field;\n const fieldType = fieldTypeNameByType[type];\n if (!fieldType) {\n return void 0;\n }\n const entry = {\n type: fieldType,\n name,\n isRepeater: \"occurrence\" in field,\n isRequired: !!field.required,\n choices: (\n // Choices are pair [value, label] but only the value is printed to the page, so flatten it.\n \"choices\" in field ? field.choices.map(([value, label]) => value) : void 0\n ),\n children: []\n };\n if (fieldType === \"GroupFieldType\" && \"children\" in field) {\n const children = getFieldEntries(field.children);\n return { ...entry, children };\n }\n return entry;\n }).filter((entry) => entry !== void 0);\n}\nconst INVALID_IMPORTS = [\"ChoiceFieldType\", \"GroupFieldType\"];\nconst FIELD_GROUP_TYPE = \"FieldGroupWithChildren\";\nconst REPEATER_GROUP_TYPE = \"RepeaterGroup\";\nconst REQUIRED_TYPE = \"RequiredField\";\nconst DEFAULT_VALUES_TYPE = \"DefaultValues\";\nconst CMS_COMPONENTS = \"@hubspot/cms-components\";\nconst CMS_COMPONENTS_FIELD_TYPES = `${CMS_COMPONENTS}/fields`;\nconst AUTO_GEN_COMMENT = \"THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.\";\nconst createPropertySignature = (identifier, type, hasQuestionToken = false) => ts.factory.createPropertySignature(\n [],\n identifier,\n hasQuestionToken ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0,\n type\n);\nconst createUnionTypeFromArray = (values) => ts.factory.createUnionTypeNode(\n values.map(\n (value) => ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(value))\n )\n);\nconst buildTypeFromField = (field, additionalNode) => {\n const imports = [field.type];\n const identifier = ts.factory.createIdentifier(field.name);\n const baseType = ts.factory.createTypeReferenceNode(field.type);\n const requiredType = ts.factory.createTypeReferenceNode(REQUIRED_TYPE, [\n baseType\n ]);\n let finalType = field.isRequired ? requiredType : baseType;\n if (field.choices) {\n finalType = createUnionTypeFromArray(field.choices);\n }\n if (field.isRequired) {\n imports.push(REQUIRED_TYPE);\n }\n if (additionalNode) {\n const typeLiteral = ts.isTypeLiteralNode(additionalNode) ? additionalNode : ts.factory.createTypeLiteralNode([additionalNode]);\n const genericType = field.isRepeater ? REPEATER_GROUP_TYPE : FIELD_GROUP_TYPE;\n imports.push(genericType);\n finalType = ts.factory.createTypeReferenceNode(genericType, [typeLiteral]);\n }\n return {\n type: createPropertySignature(\n identifier,\n finalType,\n !field.isRequired && !additionalNode\n ),\n imports\n };\n};\nconst filterUnusedImports = (imports, type) => {\n const usedImports = /* @__PURE__ */ new Set();\n const visit = (node) => {\n if (ts.isTypeReferenceNode(node)) {\n const typeName = node.typeName;\n if (\"escapedText\" in typeName) {\n usedImports.add(typeName.escapedText.toString());\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(type);\n return imports.filter((name) => usedImports.has(name));\n};\nfunction getImportDeclaration(imports, moduleSpecifier) {\n const importSpecifiers = Array.from(imports).map(\n (importName) => ts.factory.createImportSpecifier(\n true,\n void 0,\n ts.factory.createIdentifier(importName)\n )\n );\n const namedImports = ts.factory.createNamedImports(importSpecifiers);\n return ts.factory.createImportDeclaration(\n [],\n [],\n ts.factory.createImportClause(false, void 0, namedImports),\n ts.factory.createStringLiteral(moduleSpecifier)\n );\n}\nfunction getFieldTypes(fields) {\n const imports = [];\n const types = fields.map((field) => {\n if (field.children) {\n const childrenResult = getFieldTypes(field.children);\n imports.push(...childrenResult.imports);\n if (childrenResult.types.length) {\n const subType = ts.factory.createTypeLiteralNode(childrenResult.types);\n const { type: type2, imports: newImports2 } = buildTypeFromField(\n field,\n subType\n );\n imports.push(...newImports2);\n return type2;\n }\n }\n const { type, imports: newImports } = buildTypeFromField(field);\n imports.push(...newImports);\n return type;\n });\n const validImports = Array.from(\n new Set(imports.filter((name) => !INVALID_IMPORTS.includes(name)))\n );\n return { types, imports: validImports };\n}\nfunction constructFinalType(fields, typeName) {\n const { types, imports } = getFieldTypes(fields);\n const baseType = ts.factory.createTypeAliasDeclaration(\n [],\n [],\n \"\",\n void 0,\n ts.factory.createTypeLiteralNode(types)\n );\n const wrappedType = ts.factory.createTypeReferenceNode(DEFAULT_VALUES_TYPE, [\n baseType.type\n ]);\n const finalType = ts.factory.createTypeAliasDeclaration(\n [],\n [],\n typeName,\n void 0,\n wrappedType\n );\n const filteredImports = filterUnusedImports(imports, finalType);\n const importDeclaration = getImportDeclaration(\n [...filteredImports, DEFAULT_VALUES_TYPE],\n CMS_COMPONENTS_FIELD_TYPES\n );\n const defaultExport = ts.factory.createExportDefault(\n ts.factory.createIdentifier(typeName)\n );\n return [importDeclaration, finalType, defaultExport];\n}\nfunction writeFieldsType(fields, fileName, typeName) {\n const entries = getFieldEntries(fields);\n if (!entries) {\n return false;\n }\n try {\n const file = ts.createSourceFile(\n fileName,\n \"\",\n ts.ScriptTarget.ESNext,\n false,\n ts.ScriptKind.TS\n );\n const printer = ts.createPrinter();\n const nodes = constructFinalType(entries, typeName);\n const comments = [\n AUTO_GEN_COMMENT,\n \"Removing the above comment will disable type generation for this module\",\n \"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\"\n ].map((comment) => `// ${comment}`);\n const typeResult = nodes.map(\n (node) => printer.printNode(ts.EmitHint.Unspecified, node, file)\n );\n const result = [...comments, ...typeResult].join(\"\\n\");\n writeFileSync(fileName, result);\n return true;\n } catch (e) {\n console.error(e);\n return false;\n }\n}\nexport {\n AUTO_GEN_COMMENT,\n buildTypeFromField,\n constructFinalType,\n getFieldTypes,\n writeFieldsType\n};\n", "import { Field } from '@hubspot/cms-components/fields';\nimport { findAllModulesInRoot } from '@hubspot/cms-js-internal';\nimport {\n AUTO_GEN_COMMENT,\n writeFieldsType,\n} from '@hubspot/cms-js-internal/buildFieldsTypes';\nimport fs from 'fs';\nimport path from 'path';\nimport { ReactElement } from 'react';\nimport readline from 'readline';\nimport { ViteDevServer } from 'vite';\nimport { wrapMessageInColor } from './logColors.js';\nimport packagePath from './packagePath.js';\n\nconst lastSerializedFieldsCache: Record<string, string> = {};\n\nexport const formatAsTypeName = (str: string): string => {\n // Replace invalid chars w/ numbers, and prefix with underscore if invalid start\n const typeName = `${str.replace(/[^a-zA-Z0-9_$]/g, '_')}FieldsType`;\n const validFirstChar = /^[A-Za-z_$]/.test(str.charAt(0));\n\n return validFirstChar ? typeName : `_${typeName}`;\n};\n\nconst isInModulesFolder = (filePath: string, projectRoot: string) => {\n const getEntryPathFromId = (id: string) => {\n return id.startsWith(projectRoot) ? id.replace(`${projectRoot}/`, '') : '';\n };\n const currentModuleId = path.normalize(filePath);\n const moduleEntryPath = getEntryPathFromId(currentModuleId);\n\n const subFolderTokens = moduleEntryPath.split(path.sep);\n return {\n inModuleFolder:\n subFolderTokens[0] === 'components' && subFolderTokens[1] === 'modules',\n isRootModuleFile: subFolderTokens.length === 3,\n };\n};\n\nconst fileContainsAutoGenComment = async (filePath: string) => {\n // Always auto gen if file DNE\n if (!fs.existsSync(filePath)) return true;\n\n const stream = fs.createReadStream(filePath);\n const reader = readline.createInterface({ input: stream });\n const firstLine: string = await new Promise((resolve) =>\n reader.once('line', (line) => resolve(line.trim()))\n );\n reader.close();\n stream.close();\n\n return firstLine && firstLine === `// ${AUTO_GEN_COMMENT}`;\n};\n\n/**\n * If the filePath file is in the modules folder, find and return the closest index file.\n * If the filePath that was updated in modules root, return that path instead.\n */\nexport const getIndexFile = (filePath: string, projectRoot: string) => {\n const { inModuleFolder, isRootModuleFile } = isInModulesFolder(\n filePath,\n projectRoot\n );\n if (!inModuleFolder) return undefined;\n\n if (isRootModuleFile) return { indexFilePath: filePath, isRootModuleFile };\n\n // Get the index file in the root of the directory since not a root module file\n const dir = path.dirname(filePath);\n const files = fs.readdirSync(dir);\n const indexFileName = files.find((file) => file.startsWith('index.'));\n return indexFileName\n ? { indexFilePath: path.join(dir, indexFileName), isRootModuleFile }\n : undefined;\n};\n\n/*\n * Get the exported fields object from the indexFilePath and render out to JSON\n */\nexport const getIndexFileFields = async (\n indexFilePath: string,\n indexFileName: string,\n viteServer: ViteDevServer\n) => {\n let indexFile: Record<string, any>;\n let renderFieldsToJson: (\n fields: ReactElement | Field[] | any,\n moduleName: string\n ) => Field[];\n\n try {\n indexFile = await viteServer.ssrLoadModule(indexFilePath);\n const internalSsrPath = packagePath(import.meta.url, 'internalSsr');\n ({ renderFieldsToJson } = await viteServer.ssrLoadModule(internalSsrPath));\n } catch (e) {\n return undefined;\n }\n if (!indexFile.fields) return undefined;\n\n const fields = indexFile.fields;\n const renderedFieldsJson = renderFieldsToJson(fields, indexFileName);\n const isValidFields = Array.isArray(renderedFieldsJson);\n\n return isValidFields ? renderedFieldsJson : undefined;\n};\n\n/**\n * When a file inside of a module folder is updated, find the exported fields object\n * and try to generate a type file for it. If a types file exists, checks for the auto-gen\n * comment at the top before overwriting.\n */\nexport const maybeUpdateFields = async (\n filePath: string,\n viteServer: ViteDevServer,\n projectRoot: string\n) => {\n const indexInfo = getIndexFile(filePath, projectRoot);\n if (!indexInfo) return;\n\n const { indexFilePath, isRootModuleFile } = indexInfo;\n const indexFileName = path.parse(indexFilePath).name;\n\n // Do not regen if the only a types file was changed. Can infinite loop\n const isTypeFile = filePath.endsWith('.types.ts');\n if (isTypeFile) return;\n\n const fields = await getIndexFileFields(\n indexFilePath,\n indexFileName,\n viteServer\n );\n if (fields) {\n const typeFileName = isRootModuleFile\n ? `${indexFileName}.fields.types.ts`\n : 'fields.type.ts';\n const typeFilePath = path.join(path.dirname(filePath), typeFileName);\n\n // cache the field files based on path name & serialized file\n const lastSerializedFields = lastSerializedFieldsCache[typeFilePath];\n const serializedFields = JSON.stringify(fields);\n if (lastSerializedFields === serializedFields) return;\n\n const hasAutoGenComment = await fileContainsAutoGenComment(typeFilePath);\n if (!hasAutoGenComment) return;\n\n const moduleFolderName = path.basename(path.dirname(filePath));\n const outputTypeName = formatAsTypeName(moduleFolderName);\n const didSucceed = writeFieldsType(fields, typeFilePath, outputTypeName);\n\n if (didSucceed) {\n lastSerializedFieldsCache[typeFilePath] = serializedFields;\n }\n\n const pathToLog = isRootModuleFile\n ? `${moduleFolderName}/${indexFileName}`\n : moduleFolderName;\n const successMsg = `Successfully generated types for ${pathToLog}`;\n const errorMsg = `Failed to generate types for ${pathToLog}`;\n const message = didSucceed ? successMsg : errorMsg;\n console.log(wrapMessageInColor(didSucceed ? 'green' : 'red', message));\n }\n};\n\n/**\n * Generate field types for all modules once and start module file watcher to generate on add/change\n */\nexport const startFieldsTypeGenWatcher = (\n viteServer: ViteDevServer,\n projectRoot: string\n) => {\n // On server start, run auto-gen for all module folders\n const { moduleSubpaths } = findAllModulesInRoot(projectRoot);\n moduleSubpaths.forEach((modulePath) => {\n const resolvedPath = path.resolve(projectRoot, modulePath);\n maybeUpdateFields(resolvedPath, viteServer, projectRoot);\n });\n\n const watchCallback = (filePath: string) =>\n maybeUpdateFields(filePath, viteServer, projectRoot);\n viteServer.watcher.on('add', watchCallback).on('change', watchCallback);\n};\n", "import { CMSAssetConfig, ThemeConfig } from '@hubspot/cms-js-internal';\n\nexport function getSecretNamesFromConfig(\n config: CMSAssetConfig | ThemeConfig\n): string[] {\n if ('secretNames' in config && config.secretNames?.length > 0) {\n return config.secretNames;\n }\n if ('secret_names' in config && config.secret_names?.length > 0) {\n return config.secret_names;\n }\n return [];\n}\n", "#!/usr/bin/env node\n\nimport {\n getDevServerCommandLineOptions,\n buildThemePreviewOptions,\n} from './lib/cli.js';\nimport createDevServer from './createDevServer.js';\nimport { ThemePreviewOptions } from './lib/previewUtils.js';\n\nconst {\n webRoot,\n hubspotCliConfigPathOption,\n hubspotCliAccountNameOption,\n sslEnabledOption,\n storybook,\n fieldGenEnabledOption,\n resetSession,\n showUI,\n} = getDevServerCommandLineOptions(process.argv);\n\nif (!webRoot) {\n throw new Error(`No web root path argument specified`);\n}\n\nlet themePreviewOptions: ThemePreviewOptions;\n\nconst builtThemePreviewOptions = await buildThemePreviewOptions(webRoot);\n\nif (builtThemePreviewOptions) {\n themePreviewOptions = {\n ...builtThemePreviewOptions,\n resetSession,\n };\n}\n\ncreateDevServer(\n webRoot,\n storybook,\n hubspotCliConfigPathOption,\n hubspotCliAccountNameOption,\n sslEnabledOption,\n fieldGenEnabledOption,\n themePreviewOptions,\n showUI\n);\n"],
5
- "mappings": ";AAAA,OAAS,WAAAA,GAAS,QAAAC,OAAY,OAC9B,OAAS,cAAAC,OAAkB,KCD3B,IAAMC,GAAoB,OACpBC,GAAiB,MAMVC,GAAkC,CAC7C,MAAO,GACP,IAAK,GACL,MAAO,GACP,OAAQ,GACR,KAAM,GACN,QAAS,GACT,KAAM,GACN,MAAO,EACT,EAEO,SAASC,EAAmBC,EAAeC,EAAiB,CACjE,MAAO,GAAGL,MAAqBE,GAAsBE,CAAK,KAAKC,IAAUL,KAAoBC,IAC/F,CDjBA,OAAOK,OAAiB,eACxB,OAAS,4BAAAC,OAAgC,yCEJzC,OAAOC,OAAQ,KACf,OAAOC,MAAU,OACjB,OAAS,QAAAC,OAAY,4BACrB,OAAS,sBAAAC,OAA0B,qCACnC,OAAS,sBAAAC,OAA0B,8BACnC,OAAS,wBAAAC,OAA4B,4CACrC,OAAS,gBAAAC,OAAoB,sCAC7B,OAAOC,OAAc,WACrB,OAAS,oBAAAC,OAAwB,oCACjC,OAAOC,OAAY,cACnB,OAAiB,uBAAAC,OAA2B,8BAC5C,OAAS,UAAAC,MAAc,gCACvB,OACE,sBAAAC,GACA,iBAAAC,GACA,qBAAAC,GACA,qBAAAC,GACA,uBAAAC,GACA,oBAAAC,OACK,sCACP,OAAS,oBAAAC,OAAwB,gCACjC,OAAS,gCAAA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GroudANSIColorMap", "wrapMessageInColor", "color", "message", "cliProgress", "FILE_UPLOAD_RESULT_TYPES", "fs", "path", "walk", "createIgnoreFilter", "isAllowedExtension", "isConvertableFieldJs", "escapeRegExp", "inquirer", "getThemeJSONPath", "findup", "getAbsoluteFilePath", "logger", "isHubSpotHttpError", "isSystemError", "isFileSystemError", "isValidationError", "isMissingScopeError", "isSpecifiedError", "getAccountConfig", "HUBSPOT_ACCOUNT_TYPE_STRINGS", "util", "isAxiosError", "chalk", "process", "os", "tty", "COMPONENT_TYPES", "CONFIG_FILES", "PLATFORM_VERSION_ERROR_TYPES", "previewProjectPrompt", "themeComponents", "promptUser", "getProjectConfig", "_dir", "isUsingLocalWorkspace", "configPath", "__dir", "config", "projectConfig", "loadConfigFile", "source", "e", "getTypeFromConfigFile", "configFile", "key", "findProjectComponents", "projectSourceDir", "components", "projectFiles", "projectFile", "base", "dir", "parsedAppConfig", "isLegacy", "getIsLegacyApp", "isHublTheme", "getAppCardConfigs", "appConfig", "appPath", "cardConfigs", "cards", "file", "cardConfigPath", "cardConfig", "hasAnyReactExtensions", "determineSrcAndDest", "webRoot", "absoluteSrc", "dest", "projectDir", "themeJsonPath", "c", "themeDir", "themeName", "getUploadableFileList", "src", "convertFields", "filePaths", "allowedFiles", "uploadableFiles", "skipFiles", "filePath", "fileName", "choice", "updatedSkipFiles", "fieldsJsPrompt", "promptConfig", "FIELDS_FILES", "dirName", "fileChoices", "projectDirRegex", "fileDir", "selection", "fileChoice", "notPicked", "item", "logError", "error", "context", "debugError", "shouldSuppressError", "message", "msg", "ApiErrorContext", "props", "createPlatformVersionError", "err", "subCategory", "translationKey", "platformVersion", "errorContext", "uiLine", "values", "uiLink", "uiAccountDescription", "uiCommandReference", "accountId", "bold", "account", "env", "translateLevel", "level", "_supportsColor", "haveStream", "streamIsTTY", "min", "hasFlag", "osRelease", "sign", "version", "createSupportsColor", "stream", "options", "supportsColor", "UI_COLORS", "getTerminalUISupport", "supportsHyperlink", "linkText", "url", "terminalUISupport", "encodedUrl", "result", "command", "commandReference", "parseVersion", "versionString", "m", "versions", "n", "flag", "argv", "prefix", "position", "terminatorPosition", "printHelpMessage", "wrapMessageInColor", "getDevServerCommandLineOptions", "argv", "args", "webRoot", "hubspotCliConfigPathOption", "hubspotCliAccountNameOption", "configOptionIndex", "arg", "resolve", "accountOptionIndex", "sslEnabledOption", "storybook", "fieldGenEnabledOption", "resetSession", "showUI", "buildThemePreviewOptions", "isUsingLocalWorkspace", "themeJsonPath", "join", "existsSync", "filePaths", "getUploadableFileList", "dest", "determineSrcAndDest", "numFiles", "initialUploadProgressBar", "cliProgress", "uploadsHaveStarted", "results", "result", "FILE_UPLOAD_RESULT_TYPES", "logError", "ApiErrorContext", "path", "url", "express", "http", "bodyParser", "spawn", "normalizePath", "Transform", "Router", "urlencoded", "createProxyMiddleware", "path", "normalizePath", "fullOriginalUrlFromRequest", "request", "joinPosix", "renderToStaticMarkup", "path", "url", "normalizePath", "packagePath", "metaUrl", "projectPath", "path", "createHash", "fs", "readFileSync", "existsSync", "readdirSync", "lstatSync", "join", "COMPONENT_EXTENSIONS", "ENTRY_POINTS_PATH", "MODULE_FOLDER_PATH", "badInlineJsChars", "inlineJsEscapeChars", "escapeChar", "unsafeChar", "escapeForInlineJS", "input", "jsonStringifyAndEscapeForInlineJS", "baseIndent", "jsonIndent", "prettyPrint", "indentString", "viteRoot", "viteCommand", "resolveIslandPlugin", "islandsSet", "config", "id", "idWithNoParam", "islandModuleImportPath", "componentExtension", "path", "componentFilenameWithNoExtension", "modulePath", "moduleId", "clientRenderIsland", "virtualClientRenderIslandModuleId", "clientIslandEntryPlugin", "id", "idWithNoParam", "scriptTagToLogServerMessages", "messagesForBrowser", "groupLabel", "nonceAttribute", "consoleLines", "message", "funcString", "argString", "arg", "groupStart", "groupEnd", "getComponentExtension", "componentPath", "filteredExtensions", "COMPONENT_EXTENSIONS", "ext", "hasComponentExtension", "isStorybookStory", "path", "removeComponentExtension", "getEntryPointHash", "entryPoint", "createHash", "getEntryPointHashWithIndexSuffix", "index", "renderIndexSuffix", "getCMSAssetConfig", "webRoot", "cmsAssetsPath", "path", "cmsThemePath", "configPathToUse", "fs", "ENABLED_FEATURES_GATE_MAP", "isUngatedFor", "gates", "gate", "findAllComponentsIn", "webRoot", "componentsFolder", "fullComponentsFolderPath", "join", "componentsByName", "existsSync", "readdirSync", "fileOrFolderName", "fullPath", "subdirPath", "isDirectory", "lstatSync", "hasComponentExtension", "isStorybookStory", "subdirPathNoExtension", "removeComponentExtension", "potentialExtension", "COMPONENT_EXTENSIONS", "potentialIndexModule", "fullPotentialPath", "moduleIndexPathNoExtension", "findAllModulesInRoot", "allModuleComponents", "moduleNames", "moduleSubpath", "moduleSubpaths", "moduleExtensions", "path2", "moduleNamesWithExtension", "file", "findAllPartialsInRoot", "allPartialComponents", "partialNames", "partialSubpath", "partialSubpaths", "namespaceModulePropsShape", "props", "dataQueryResult", "hublParameters", "passedFieldValues", "hublData", "experimentalHublData", "moduleName", "supplementalFieldValues", "oldPropsShape", "fieldValues", "setIn", "object", "nestedKeysArray", "value", "curr", "finalKey", "index", "currentKey", "nextKey", "dotProp", "parser", "_traverse", "t", "jsx", "stream", "renderToPipeableStream", "renderToStaticMarkup", "cmsComponents", "ServerRenderContext", "setProperty", "getProperty", "hasProperty", "dotProp", "serializeIslandDataForInlineScript", "tweakedIslandsArray", "perServerRequestData", "baseIndent", "prettyPrint", "isUngatedForClientOnlySupplementalFieldSerialization", "islandsArrayToSerialize", "id", "moduleName", "moduleId", "props", "hydrateOn", "clientOnly", "priority", "url", "sharedStateID", "supplementalFieldValues", "wrapperModuleId", "wrapperUrl", "output", "filteredSupplementalFieldValues", "filterOutUnreadSupplementalFieldValues", "acc", "key", "jsonStringifyAndEscapeForInlineJS", "supplementalFieldValuesRead", "result", "fieldPath", "writeSharedStateToJsGlobal", "islands", "indent", "sharedStateIDs", "island", "x2", "indentString", "stateByID", "getIslandUrls", "roots", "viteDevServer", "islandModule", "wrapperModule", "getPerServerRequestUrls", "perServerRequestDataWithUrls", "reducer", "reducerWithUrl", "createIslandsGlobalJsForClientInDev", "noncePlaceholderPlugin", "HS_DEPLOYED", "html", "regex", "replacer", "_", "p1", "p2", "traverse", "_traverse", "CMS_MODULE_COMPONENT_NAME", "DND_AREA_COMPONENT_NAME", "PLUGIN_NAME", "findCmsModules", "buildContentDescriptors", "config", "resolvedConfig", "code", "moduleInfo", "shouldAnalyzeModule", "contentDescriptors", "analyzeSourceCodeUsages", "error", "entryPoints", "getEntryPoints", "entryPointCmsModuleMap", "buildEntryPointsCmsModuleMap", "relativeEntryPointCmsModuleMap", "convertEntryPointPathsToRelative", "entryPointIslandCmsModuleMap", "buildEntryPointIslandsCmsModuleMap", "relativeEntryPointIslandCmsModuleMap", "convertEntryPointIslandPathsToRelative", "modulesWithinModules", "filterEntryPointsToModules", "entryPointsCmsModuleMap", "relativeEntries", "entryPointPath", "cmsModules", "toRelativePath", "islandContentDescriptors", "islandCmsModuleUsage", "islandPath", "path", "fileId", "__", "ctx", "entryPointCmsModuleUsage", "entryPoint", "findCmsModuleUsages", "entryPointIslandsCmsModuleMap", "findIslandCmsModuleUsage", "sourceAst", "moduleComponentLocalImportName", "dndAreaComponentLocalImportName", "specifier", "cmsModuleName", "cmsModulePath", "cmsModuleLabel", "prop", "cmsModuleProps", "dndAreaName", "dndArea", "processed", "entryPointContentDescriptors", "importedId", "importedResult", "processedIslands", "islandModuleResults", "results", "resultForModuleId", "mergedDataDependencies", "importerCmsModuleUsageResult", "promiseForNewWritableStream", "chunks", "writableStream", "stream", "chunk", "encoding", "done", "resolve", "reject", "renderStreamToPromise", "reactElements", "options", "streamDonePromise", "pipe", "renderToPipeableStream", "createServerRenderContextV2", "createServerRenderContext", "renderServerSidePropsWithAsyncLocalStoreContext", "cmsComponents", "bootStrapRenderContext", "renderOnServer", "elements", "renderContext", "bootStrapRenderContext", "debugName", "renderOptions", "html", "renderStreamToPromise", "jsx", "ServerRenderContext", "scriptTagToLogServerMessages", "getServerGlobalsToInject", "environmentConfig", "hsServerPageUrl", "hsBasePath", "prettyPrint", "criticalDevErrors", "includeNonces", "globals", "jsonStringifyAndEscapeForInlineJS", "firstCriticalDevError", "findFullPathInModuleGraph", "modulePathNoExtension", "moduleGraph", "extension", "COMPONENT_EXTENSIONS", "pathToTry", "getComponentPaths", "viteServer", "componentPath", "componentPathWithExtension", "componentPathNoExtension", "hasComponentExtension", "removeComponentExtension", "findFullPathInModuleGraph", "getEntryPointBasePath", "ENTRY_POINTS_PATH", "MODULE_FOLDER_PATH", "renderComponentWithCSS", "viteServer", "componentPath", "Component", "propsAndExtraDeps", "pageUrl", "entryPointBasePath", "contextOptions", "environmentConfig", "renderOptions", "getServerSideProps", "modifyHtmlCallback", "internalSsrPath", "packagePath", "renderComponentOnServer", "collectCssInDev", "componentPathWithExtension", "getComponentPaths", "renderResult", "html", "renderContext", "cssNeeded", "inlineAssets", "staticAssetRenderFunc", "staticAsset", "renderToStaticMarkup", "renderComponentWithCSS_default", "getByteSizeOf", "props", "formatBytesToString", "bytes", "getPropsInfo", "reportOptions", "recursionDepth", "propsSizeInBytes", "result", "key", "value", "size", "logPartialInfo", "partialPath", "lookForModuleInFolder", "modulePath", "viteServer", "componentModule", "insideFolderPath", "joinPosix", "e", "renderPartial", "partialPath", "props", "pageUrl", "basePath", "environmentConfig", "renderOptions", "logPartialInfo", "resolvedPath", "hasComponentExtension", "Component", "renderComponentWithCSS_default", "renderPartial_default", "fsPromises", "isDebugUrlString", "criticalDevErrorsToServerMessages", "criticalDevErrors", "criticalDevError", "criticalDevErrorsToServerMessages_default", "readFile", "fsPromises", "getIsUngatedForClientOnlySupplementalFieldSerialization", "gates", "generateIslandSetupScriptBlock", "packagePath", "createdPlainHtmlTemplate", "baseTemplatePath", "title", "globalScriptBlock", "createIslandHtmlTemplate", "htmlTemplate", "createHtmlShellDependingOnRenderContext", "url", "renderContext", "viteServer", "jsRenderingGates", "prettyPrint", "isDebugUrlString", "serverMessages", "criticalDevErrorsToServerMessages_default", "serverLogScript", "scriptTagToLogServerMessages", "getServerGlobalsToInject", "isUngatedForClientOnlySupplementalFieldSerialization", "createIslandsGlobalJsForClientInDev", "getIslandRuntimeAndGlobalToInject", "sortedIslandRoots", "perServerRequestData", "internalSsrPath", "islandRuntimeScript", "buildStaticEnvConfig", "hsCliHttp", "getAccountConfig", "axios", "getAxiosConfig", "debugFactory", "debug", "DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED", "DEV_SERVER_USAGE_ENDPOINT", "EVENT_NAME", "trackingAccountId", "trackingEnv", "getPlatform", "getNodeVersionData", "trackUsage", "action", "accountConfig", "trackingAccountId", "getAccountConfig", "isAuthedWithPersonalAccessKey", "usageEvent", "EVENT_NAME", "baseRequestOptions", "DEV_SERVER_USAGE_ENDPOINT_AUTHENTICATED", "DEV_SERVER_USAGE_ENDPOINT", "hsCliHttp", "config", "getAxiosConfig", "trackingEnv", "axios", "setTrackingInfo", "accountId", "env", "sendTrackingRequest", "debug", "wrapMessageInColor", "e", "buildStaticEnvConfig", "path", "normalizePath", "fs", "resolve", "unescape", "localJsRenderStartString", "localJsRenderEndString", "isRecord", "value", "findLocalRenderPlaceholders", "body", "offsetSoFar", "result", "startOffset", "nextNewlineOffset", "pathEndOffset", "path", "nextCommentEndOffset", "endOffset", "jsonString", "json", "getHSProjectConfig", "hsProjectConfigPath", "e", "getProjectNameFromHSConfig", "hsProjectConfig", "path", "normalizePath", "getAccountId", "getEnv", "hsCliHttp", "joinPosix", "cmsComponents", "hsCliHttp", "hsCliHttp", "graphQLCache", "fetchModuleGraphQLData", "accountId", "query", "requestedModulePath", "pageUrl", "searchParams", "compositeQueryKey", "dataQueryResult", "graphQLCache", "hsCliHttp", "e", "traverseFieldsJSON", "getFieldValuesForModule", "fieldsJSON", "fieldOverrides", "props", "traverseFieldsJSON", "fieldPathArray", "value", "setIn", "VALIDATE_FIELDS_ENDPOINT", "VALIDATE_META_ENDPOINT", "filterToModuleDataDepsIncludedIn", "getModuleDataDependecyTypeFrom", "cmsComponents", "handleValidationApiError", "result", "type", "renderContext", "requestedModulePath", "errorMessage", "handleModuleValidationErrors", "validationErrors", "validationSeverityToLogLevel", "validationError", "getApplyValidationToRenderContext", "portalId", "fieldsJSON", "metaJSON", "renderResult", "fieldsValidationResponse", "metaValidationResponse", "fieldsResult", "metaResult", "hsCliHttp", "index", "response", "lookForModuleInFolder", "modulePath", "viteServer", "componentModule", "insideFolderPath", "joinPosix", "e", "renderModule", "moduleProps", "pageUrl", "basePath", "environmentConfig", "renderOptions", "fieldOverrides", "hublParameters", "supplementalFieldValues", "experimentalHublData", "hublData", "moduleName", "ungatedForServerSideProps", "isUngatedFor", "messagesForBrowser", "dataQueryResult", "foundPath", "getServerSideProps", "extraDeps", "hasComponentExtension", "Component", "fields", "meta", "internalSsrPath", "packagePath", "renderFieldsToJson", "fieldValues", "getFieldValuesForModule", "applyFieldsValidationToRenderContext", "fetchModuleGraphQLData", "errorString", "graphQLError", "error", "namespacedModuleProps", "namespaceModulePropsShape", "depType", "renderComponentWithCSS_default", "renderModule_default", "createEmptyServerRenderContext", "VALID_PROXY_DOMAIN_SUFFIXES", "getSubDomainFromValidLocalDomain", "hostname", "validProxyDomainSuffix", "VALID_PROXY_DOMAIN_SUFFIXES", "randomStringWithLotsOf", "char", "maxLength", "fakeRenderJsComponent", "indexForThisRender", "resolve", "reject", "randomTimeout", "fakeJsRenderedOutput", "createEmptyServerRenderContext", "e", "consoleWarn", "message", "AnsiToHtmlConverter", "customColors", "Converter", "darkErrorStyles", "renderLocalError_default", "path", "error", "stackWithColorClasses", "hsCliHttp", "fetchPreviewInfo_default", "accountId", "portalId", "contentId", "content", "error", "errorMessagePrefix", "buildStaticEnvConfig", "isDebugUrlString", "mergeServerRequestData_internal", "stringify", "readFileSync", "crypto", "relative", "join", "hsCliHttp", "PREVIEW_API_PATH", "initiateSession", "accountId", "resetSession", "diffDeveloperFileHashes", "token", "fileHashes", "uploadFolder", "chokidar", "path", "shouldIgnoreFile", "convertToUnixPath", "isAllowedExtension", "getExt", "splitLocalPath", "upload", "deleteFile", "MODULE_EXTENSION", "escapeRegExp", "REMOTE_FS_IS_DIRTY", "remoteFsDirtyHandler", "req", "res", "markRemoteFsDirty", "initialPreviewBufferUpload", "accountId", "src", "dest", "filePaths", "uploadOptions", "onFinishCallback", "rest", "results", "uploadFolder", "filePath", "path", "startPreviewWatcher", "watcherIsReady", "watcher", "chokidar", "file", "shouldIgnoreFile", "addFileCallback", "buildUploadFileToPreviewBufferCallback", "changeFileCallback", "deleteFileCallback", "buildDeleteFileFromPreviewBufferCallback", "deleteFolderCallback", "error", "sleep", "ms", "resolve", "isAllowedExtension", "destPath", "getDesignManagerPath", "uploadFile", "type", "moduleChild", "isModuleFolderChild", "filename", "remotePath", "deleteRemoteFile", "regex", "escapeRegExp", "relativePath", "convertToUnixPath", "upload", "markRemoteFsDirty", "uploadFailureMessage", "remoteFilePath", "deleteFile", "pathParts", "splitLocalPath", "part", "getExt", "MODULE_EXTENSION", "path", "removePreviewPrefix", "t", "getPreviewUrl", "request", "queryParams", "authedPortalId", "authedEnv", "authedHublet", "stringify", "buildHTMLResponse", "content", "insertAtEndOfBody", "html", "script", "insertAt", "baseStr", "index", "insertStr", "endOfBodyIndex", "addRefreshScript", "buildDevFileHashTable", "src", "dest", "filePaths", "acc", "filePath", "relativePath", "relative", "destPath", "join", "getMd5Hash", "fileContent", "readFileSync", "hash", "crypto", "initiatePreviewSession", "absoluteWebRoot", "themePreviewOptions", "res", "initiateSession", "err", "token", "tokenStatus", "startProgressBar", "absoluteDest", "nonJSRFilePaths", "uploadOptions", "initialPreviewBufferUpload", "hashes", "diffRes", "diffDeveloperFileHashes", "changedFiles", "addedFiles", "filesToUpload", "relPath", "startPreviewWatcher", "getEntryPointBasePathFromProxyRequest", "request", "requestPath", "pathParamDict", "resolvePlaceholderPath", "placeholderPath", "projectName", "projectComponent", "mappedPlaceholderPath", "makeProxyPreviewRequest", "accountId", "urlToProxy", "previewKey", "contentId", "environmentConfig", "__jsRenderingGates", "cookieHeader", "localPreviewToken", "url", "renderPreviewLocally", "proxiedQueryParams", "baseURL", "pathname", "PARAMS_TO_IGNORE", "queryKeys", "queryKey", "values", "localProxyProject", "hsCliHttp", "error", "isRecord", "value", "isModulePlaceholder", "renderComponentForPlaceholder", "indexForThisRender", "localRenderPlaceholder", "webRoot", "viteServer", "pageUrl", "basePath", "hsProjectJsonProjectName", "webRootProjectComponent", "localRenderPlaceholderProps", "__projectIdentifier", "projectFolder", "projectComponentFolder", "componentFolder", "componentTypeFolder", "componentFileName", "partialPath", "resolvedPath", "normalizePath", "path", "entryPointPath", "fakeRenderJsComponent", "ENTRY_POINTS_PATH", "renderComponentForPlaceholderPartial", "MODULE_FOLDER_PATH", "localModuleRenderPlaceholder", "renderComponentForPlaceholderModule", "renderPartial_default", "getEntryPointHashWithIndexSuffix", "renderModule_default", "proxySpecificPage", "response", "portalId", "hublet", "projectComponentPath", "jsRenderingGates", "fullOriginalUrl", "proxyEnv", "prettyPrint", "isDebugUrlString", "getAccountId", "getEnv", "previewInfo", "fetchPreviewInfo_default", "buildStaticEnvConfig", "pageHtml", "addRefreshScript", "infillReactModulesAndWriteResponse", "sortIslandRootsByPriority", "localRenderPlaceholders", "findLocalRenderPlaceholders", "numPlaceholders", "numJsRenderFailures", "islands", "mergedPerRequestState", "criticalDevErrors", "renderPromisesByChunkIndex", "offsetSoFar", "pageChunks", "renderPromise", "promiseResult", "_a", "html", "cssNeeded", "inlineAssets", "renderContext", "mergeServerRequestData_internal", "result", "inlineAsset", "e", "renderLocalError_default", "i", "chunk", "foobar", "getServerGlobalsToInject", "scriptTagToLogServerMessages", "criticalDevErrorsToServerMessages_default", "sortedIslandRoots", "islandRuntimeAndGlobalScriptHtml", "getIslandRuntimeAndGlobalToInject", "hsCliHttp", "jsdom", "JSDOM", "jsdom", "renderRemoteModulePreview", "modulePath", "authedPortalId", "authedEnv", "cookieValue", "moduleInfoQueryParams", "moduleInfo", "hsCliHttp", "currentHubApiDomainOverride", "queryParams", "modulePreviewHtml", "dom", "modulePreviewContent", "cssNeeded", "element", "renderLocalProjectModulePreview", "moduleName", "authedHublet", "webRoot", "viteServer", "jsRenderingGates", "projectName", "projectComponentPath", "fullOriginalUrl", "fieldOverrides", "normalizePath", "path", "basePath", "getEntryPointBasePath", "environmentConfig", "buildStaticEnvConfig", "componentModule", "foundPath", "hasComponentExtension", "lookForModuleInFolder", "Component", "fields", "meta", "hublDataTemplate", "internalSsrPath", "packagePath", "renderFieldsToJson", "localFieldsJson", "localFieldValues", "getFieldValuesForModule", "localModule", "templatePreview", "localRenderPlaceholders", "findLocalRenderPlaceholders", "renderComponentForPlaceholder", "joinPosix", "partialRouteHandler", "request", "response", "sendTrackingRequest", "authedPortalId", "authedEnv", "authedHublet", "webRoot", "viteServer", "jsRenderingGates", "projectName", "projectComponentPath", "partialName", "baseTemplatePath", "packagePath", "partialPath", "normalizePath", "path", "entrypointPath", "basePath", "getEntryPointBasePath", "environmentConfig", "buildStaticEnvConfig", "renderedHtml", "cssNeeded", "renderContext", "inlineAssets", "renderPartial_default", "fullOriginalUrlFromRequest", "getEntryPointHash", "resolvedCss", "resolvedInlineAssets", "partialHtml", "moduleNode", "hasComponentExtension", "cmsModules", "localProjectModules", "moduleDescriptor", "remoteModules", "remoteModulePreviewPromises", "localProjectModulePreviewPromises", "remoteModule", "modulePlaceholder", "createModulePlaceholder", "renderRemoteModulePreview", "result", "localProjectModule", "renderLocalProjectModulePreview", "remoteModuleResults", "localProjectModuleResults", "html", "createHtmlShellDependingOnRenderContext", "inlineAsset", "e", "moduleName", "partial_default", "jsx", "jsxs", "EmptyPartialsList", "webRoot", "PartialLinkInLI", "partialName", "PartialsList", "partialNames", "jsx", "linksToAllPartialRouteHandler", "request", "response", "webRoot", "partialNames", "findAllPartialsInRoot", "responseHtml", "renderOnServer", "PartialsList", "linksToAllPartialsRouteHandler_default", "jsx", "jsxs", "EmptyModulesList", "webRoot", "ModuleLinkInLI", "moduleName", "ModulesList", "moduleNames", "ModulesList_default", "jsx", "linksToAllModuleRouteHandler", "request", "response", "webRoot", "moduleNames", "findAllModulesInRoot", "responseHtml", "renderOnServer", "ModulesList_default", "linksToAllModulesRouteHandler_default", "buildStaticEnvConfig", "path", "normalizePath", "moduleRouteHandler", "request", "response", "sendTrackingRequest", "authedPortalId", "authedEnv", "authedHublet", "webRoot", "viteServer", "jsRenderingGates", "projectName", "projectComponentPath", "moduleName", "baseTemplatePath", "packagePath", "modulePath", "normalizePath", "path", "entrypointPath", "fieldOverrides", "basePath", "getEntryPointBasePath", "environmentConfig", "buildStaticEnvConfig", "renderedHtml", "cssNeeded", "renderContext", "inlineAssets", "renderModule_default", "fullOriginalUrlFromRequest", "getEntryPointHash", "html", "createHtmlShellDependingOnRenderContext", "inlineAsset", "e", "module_default", "path", "normalizePath", "joinPosix", "lookForModuleInFolder", "modulePath", "viteServer", "componentModule", "insideFolderPath", "joinPosix", "e", "renderModuleFieldsJson", "requestedModulePath", "hasComponentExtension", "error", "internalSsrPath", "packagePath", "renderFieldsToJson", "renderModuleFieldsJson_default", "moduleFieldsJsonRouteHandler", "request", "response", "sendTrackingRequest", "webRoot", "viteServer", "moduleName", "modulePath", "normalizePath", "path", "fieldsJson", "renderModuleFieldsJson_default", "error", "moduleFieldsJson_default", "http", "https", "getAccountId", "requestPage", "url", "redirects", "originalUrl", "resolve", "reject", "https", "http", "res", "portalIdHeader", "contentId", "debug", "err", "fetchContentMetadata", "portalId", "portalIdFromResponse", "pageAccount", "getAccountId", "proxyPageRouteHandler", "request", "response", "next", "sendTrackingRequest", "viteServer", "webRoot", "projectName", "projectComponentPath", "jsRenderingGates", "fullOriginalUrl", "fullOriginalUrlFromRequest", "domainToProxy", "getSubDomainFromValidLocalDomain", "urlToProxy", "VALID_PROXY_DOMAIN_SUFFIXES", "message", "consoleWarn", "portalId", "contentId", "hublet", "fetchContentMetadata", "proxySpecificPage", "e", "request", "HCMS_PATH", "HS_FS_PATH", "HUB_FS_PATH", "isInternalCMSRoute", "req", "proxyPageResourceRedirect", "res", "next", "VALID_PROXY_DOMAIN_SUFFIXES", "domainToProxy", "getSubDomainFromValidLocalDomain", "pathToProxy", "urlToProxy", "request", "isSendingJSON", "headerEntries", "header", "body", "jsx", "HubLModulesList", "modules", "module", "removePreviewPrefix", "hsCliHttp", "DESIGN_MANAGER_API_PATH", "fetchHubLModules", "accountId", "previewToken", "fetchPreviewTemplates", "fetchModuleByPath", "path", "fetchTemplateByPath", "fetchModulePageDependencies", "url", "jsx", "jsxs", "HubLTemplatesList", "templates", "isCodedFile", "template", "removePreviewPrefix", "TEMPLATE_EXTENSION_REGEX", "filePath", "Fragment", "jsx", "jsxs", "homeRouteHandler", "request", "response", "next", "getSubDomainFromValidLocalDomain", "sendTrackingRequest", "authedPortalId", "webRoot", "storybookEnabled", "devServerPort", "localPreviewToken", "jsRenderingGates", "isUngatedForUnifiedThemePreview", "partialNames", "findAllPartialsInRoot", "moduleNames", "findAllModulesInRoot", "hublModuleData", "fetchHubLModules", "hublTemplateData", "fetchPreviewTemplates", "responseHtml", "renderOnServer", "PartialsList", "ModulesList_default", "HubLModulesList", "HubLTemplatesList", "homeRouteHandler_default", "jsx", "jsxs", "proxyPathPageRouteHandler", "request", "response", "next", "sendTrackingRequest", "viteServer", "webRoot", "projectName", "projectComponentPath", "jsRenderingGates", "responseHtml", "renderOnServer", "proxyPageUrl", "message", "consoleWarn", "portalId", "contentId", "hublet", "fetchContentMetadata", "proxySpecificPage", "e", "fetch", "HCMS_PATH", "HS_FS_PATH", "HUB_FS_PATH", "isInternalCMSRoute", "req", "proxyPathPageResourceRedirect", "res", "next", "isAHtmlRequest", "proxyPageUrl", "refererUrl", "encodedPageUrl", "urlToProxy", "response", "err", "fetch", "localDomains", "proxyServerlessRequest", "req", "res", "next", "method", "headers", "refererUrl", "domainToProxy", "body", "referrerDomain", "e", "urlToProxy", "contentType", "cookie", "headersToPass", "proxyLogArgs", "response", "err", "path", "normalizePath", "modulePreviewRouteHandler", "request", "response", "sendTrackingRequest", "authedPortalId", "authedEnv", "authedHublet", "webRoot", "viteServer", "jsRenderingGates", "projectName", "projectComponentPath", "moduleName", "modulePath", "normalizePath", "path", "PREVIEWER_APP_PARAM", "fieldOverrides", "parsedFieldOverrides", "e", "renderedHtml", "cssNeeded", "renderContext", "inlineAssets", "renderLocalProjectModulePreview", "fullOriginalUrlFromRequest", "baseTemplatePath", "packagePath", "html", "createHtmlShellDependingOnRenderContext", "inlineAsset", "modulePreviewRouteHandler_default", "hsCliHttp", "hublModuleRouteHandler", "request", "response", "sendTrackingRequest", "authedPortalId", "localPreviewToken", "modulePath", "buildModuleIndex", "calculatedPath", "customWidgetInfo", "fetchModuleByPath", "params", "previewUrl", "getPreviewUrl", "result", "hsCliHttp", "html", "addRefreshScript", "err", "buildErrorIndex", "buildHTMLResponse", "hsCliHttp", "buildStaticEnvConfig", "getEnv", "templateRouteHandler", "request", "response", "sendTrackingRequest", "authedPortalId", "localPreviewToken", "projectName", "viteServer", "webRoot", "projectComponentPath", "jsRenderingGates", "environmentConfig", "templatePath", "buildTemplateIndex", "calculatedPath", "templateInfo", "fetchTemplateByPath", "err", "buildErrorIndex", "localProxyProject", "params", "previewUrl", "getPreviewUrl", "result", "hsCliHttp", "pageHtml", "addRefreshScript", "infillReactModulesAndWriteResponse", "buildHTMLResponse", "fs", "path", "normalizePath", "mapReactModules", "modules", "themeWebRoot", "viteServer", "name", "index", "modulePath", "normalizePath", "path", "fieldsJson", "renderModuleFieldsJson_default", "normalizeHubLModules", "module", "normalizePartialsData", "partialData", "normalizeTemplatesData", "templates", "template", "getDevServerUIData", "reqLocals", "authedEnv", "authedPortalId", "projectName", "localPreviewToken", "webRootProjectComponentFolder", "modulesData", "findAllModulesInRoot", "partialsData", "findAllPartialsInRoot", "reactModules", "hubLModuleData", "hubLTemplateData", "fetchHubLModules", "fetchPreviewTemplates", "hubLTemplates", "isCodedFile", "mappedHubLModules", "getDevServerUIData_default", "Router", "spawn", "getOpenCommand", "handleGetModulePages", "req", "res", "next", "path", "portalId", "data", "fetchModulePageDependencies", "err", "handleOpenFile", "command", "spawn", "createAppServerRoutes", "router", "Router", "createAppServerRoutes_default", "STORYBOOK_DOMAINS", "VALID_PROXY_DOMAIN_SUFFIXES", "domain", "createDevServerRoutes", "viteServer", "storybookPort", "appServer", "reqLocals", "appWebRoot", "devServerApp", "Router", "request", "response", "next", "method", "url", "hostname", "debug", "createProxyMiddleware", "__pathname", "req", "urlencoded", "createAppServerRoutes_default", "res", "initialProps", "getDevServerUIData_default", "template", "fs", "render", "rendered", "html", "e", "proxyPathPageRouteHandler", "linksToAllPartialsRouteHandler_default", "partial_default", "remoteFsDirtyHandler", "modulePreviewRouteHandler_default", "linksToAllModulesRouteHandler_default", "module_default", "moduleFieldsJson_default", "hublModuleRouteHandler", "templateRouteHandler", "proxyServerlessRequest", "homeRouteHandler_default", "proxyPathPageResourceRedirect", "proxyPageResourceRedirect", "proxyPageRouteHandler", "createDevServerRoutes_default", "net", "express", "Router", "getAccountId", "cors", "getShadowDevServerCheckHandler", "devServerPort", "themePath", "request", "response", "query", "hostName", "pathName", "contentId", "portalIdString", "portalId", "accountId", "isTemplateFromDevTheme", "localProxyUrl", "getAccountId", "templatePath", "fetchPreviewInfo_default", "error", "createShadowDevServerRoutes", "shadowDevServerRoutes", "Router", "cors", "testNetServer", "net", "startShadowDevServer", "devServerPort", "shadowPort", "themePath", "res", "rej", "err", "shadowDevServer", "express", "createShadowDevServerRoutes", "createViteServer", "react", "mkcert", "viteCommonjs", "devSecretsPlugin", "secretNames", "readFileSync", "join", "getPackageJson", "packagePath", "getDepsForPackage", "packageJson", "getDepsForPackageIfExists", "createViteDevServer", "webRoot", "port", "sslEnabled", "domainsToProxy", "jsRenderingGates", "secretNames", "additionalMkcertHosts", "proxyDomain", "origin", "isProjectWithReact", "ssrAndOptimizeDep", "reactAndIslandsPlugins", "react", "clientIslandEntryPlugin", "resolveIslandPlugin", "viteCommonjs", "devSecretsPlugin", "noncePlaceholderPlugin", "viteConfig", "findCmsModules", "mkcert", "createViteServer", "createViteDevServer_default", "createViteServer", "react", "createAppServer", "webRoot", "port", "sslEnabled", "viteConfig", "react", "clientIslandEntryPlugin", "resolveIslandPlugin", "createViteServer", "createAppServer_default", "net", "http", "https", "requireHTTPS", "message", "response", "newLocation", "createHttpsRedirectingServer", "opts", "handler", "innerHTTPServer", "innerHTTPSServer", "socket", "buffer", "byte", "protocol", "proxy", "fetchAccessToken", "getGatesFromEnv", "mapEnabledFeaturesToGates", "enabledFeatures", "gates", "enabledFeature", "ENABLED_FEATURES_GATE_MAP", "getJsRenderingGates", "portalId", "env", "personalAccessKey", "fetchAccessToken", "envGates", "getGatesFromEnv", "mergedGates", "getEnv", "getAccountId", "getAccountConfig", "loadConfig", "validateConfig", "fetchSecrets", "hsCliHttp", "MISSING_SCOPE_ERROR_PREFIX", "OAUTH_ERROR_REGEX", "NOT_PUBLIC_USE_ERROR", "MissingScopeError", "error", "messageEnd", "logMissingScopeWarning", "isMissingScopeError", "handleSecretsError", "statusCode", "errorDetails", "fetchDomains", "portalId", "hsCliHttp", "error", "isMissingScopeError", "MissingScopeError", "fetchWebsiteDomainNames", "domain", "r", "path", "fs", "select", "hsCliHttp", "HSPROJECT_JSON", "checkFileExists", "filePath", "findHSProjectJson", "startPath", "currentDir", "dirLevel", "maxDirLevel", "validateHSPlatform", "projectConfigPath", "portalId", "hsProjectJSONContents", "hsProjectJSONData", "platformVersion", "platformVersionResult", "e", "answer", "versionNumber", "hsCliHttp", "writeFileSync", "ts", "fieldTypeNameByType", "getFieldEntries", "fields", "field", "name", "type", "fieldType", "entry", "value", "label", "children", "INVALID_IMPORTS", "FIELD_GROUP_TYPE", "REPEATER_GROUP_TYPE", "REQUIRED_TYPE", "DEFAULT_VALUES_TYPE", "CMS_COMPONENTS", "CMS_COMPONENTS_FIELD_TYPES", "AUTO_GEN_COMMENT", "createPropertySignature", "identifier", "hasQuestionToken", "createUnionTypeFromArray", "values", "buildTypeFromField", "additionalNode", "imports", "baseType", "requiredType", "finalType", "typeLiteral", "genericType", "filterUnusedImports", "usedImports", "visit", "node", "typeName", "getImportDeclaration", "moduleSpecifier", "importSpecifiers", "importName", "namedImports", "getFieldTypes", "types", "childrenResult", "subType", "type2", "newImports2", "newImports", "validImports", "constructFinalType", "wrappedType", "filteredImports", "importDeclaration", "defaultExport", "writeFieldsType", "fileName", "entries", "file", "printer", "nodes", "comments", "comment", "typeResult", "result", "e", "fs", "path", "readline", "lastSerializedFieldsCache", "formatAsTypeName", "str", "typeName", "isInModulesFolder", "filePath", "projectRoot", "getEntryPathFromId", "id", "currentModuleId", "path", "subFolderTokens", "fileContainsAutoGenComment", "fs", "stream", "reader", "readline", "firstLine", "resolve", "line", "AUTO_GEN_COMMENT", "getIndexFile", "inModuleFolder", "isRootModuleFile", "dir", "indexFileName", "file", "getIndexFileFields", "indexFilePath", "viteServer", "indexFile", "renderFieldsToJson", "internalSsrPath", "packagePath", "fields", "renderedFieldsJson", "maybeUpdateFields", "indexInfo", "typeFileName", "typeFilePath", "lastSerializedFields", "serializedFields", "moduleFolderName", "outputTypeName", "didSucceed", "writeFieldsType", "pathToLog", "successMsg", "errorMsg", "wrapMessageInColor", "startFieldsTypeGenWatcher", "moduleSubpaths", "findAllModulesInRoot", "modulePath", "resolvedPath", "watchCallback", "getSecretNamesFromConfig", "config", "_a", "_b", "BASE_PATH", "PORT", "SHADOW_PORT", "STORYBOOK_PORT", "createDevServer", "webRoot", "storybook", "hubspotCliConfigPathOption", "hubspotCliAccountNameOption", "sslEnabledOption", "fieldGenEnabledOption", "themePreviewOptions", "showUI", "authedPortalId", "authedEnv", "jsRenderingGates", "personalAccessKey", "secretNames", "secretNamesFromConfig", "loadConfig", "cmsAssetConfig", "getCMSAssetConfig", "getSecretNamesFromConfig", "validateConfig", "getAccountId", "env", "getEnv", "getAccountConfig", "getJsRenderingGates", "secretsResponse", "fetchSecrets", "secretName", "missingSecrets", "e", "handleSecretsError", "setTrackingInfo", "sendTrackingRequest", "domainsToProxy", "portalDomains", "fetchWebsiteDomainNames", "d", "MissingScopeError", "logMissingScopeWarning", "failedDomainFetchMessages", "msg", "wrapMessageInColor", "authedHublet", "hsCliHttp", "absoluteWebRoot", "normalizePath", "path", "__webRootProjectFolder", "webRootProjectComponentFolder", "projectConfigPath", "findHSProjectJson", "validateHSPlatform", "isUngatedForUnifiedThemePreview", "_localPreviewToken", "_tokenStatus", "localPreviewToken", "tokenStatus", "initiatePreviewSession", "viteServer", "createViteDevServer_default", "startFieldsTypeGenWatcher", "viteHTTPSConfig", "httpsKey", "httpsCert", "projectName", "getProjectNameFromHSConfig", "httpServers", "expressServer", "express", "bodyParser", "appWebRoot", "url", "reqLocals", "appServer", "createAppServer_default", "createDevServerRoutes_default", "server", "innerHTTPServer", "innerHTTPSServer", "createHttpsRedirectingServer", "httpServer", "http", "startShadowDevServer", "extraServerInfo", "protocol", "packageRoot", "configPath", "storybookProcess", "spawn", "Transform", "chunk", "_encoding", "callback", "serverClosePromises", "resolve", "createDevServer_default", "webRoot", "hubspotCliConfigPathOption", "hubspotCliAccountNameOption", "sslEnabledOption", "storybook", "fieldGenEnabledOption", "resetSession", "showUI", "getDevServerCommandLineOptions", "themePreviewOptions", "builtThemePreviewOptions", "buildThemePreviewOptions", "createDevServer_default"]
7
- }