@teambit/preview 0.0.853 → 0.0.855

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.
@@ -503,9 +503,9 @@ class PreviewMain {
503
503
  async isScaling(component) {
504
504
  var _component$state$aspe, _previewData$isScalin;
505
505
 
506
- const previewData = (_component$state$aspe = component.state.aspects.get(_preview().PreviewAspect.id)) === null || _component$state$aspe === void 0 ? void 0 : _component$state$aspe.data; // Core envs are always scaling (their template bundle containing the scaling logic)
506
+ const previewData = (_component$state$aspe = component.state.aspects.get(_preview().PreviewAspect.id)) === null || _component$state$aspe === void 0 ? void 0 : _component$state$aspe.data; // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality
507
507
 
508
- return (_previewData$isScalin = previewData === null || previewData === void 0 ? void 0 : previewData.isScaling) !== null && _previewData$isScalin !== void 0 ? _previewData$isScalin : this.envs.isUsingCoreEnv(component);
508
+ return (_previewData$isScalin = previewData === null || previewData === void 0 ? void 0 : previewData.isScaling) !== null && _previewData$isScalin !== void 0 ? _previewData$isScalin : this.envs.isUsingCoreEnv(component) && (await this.isBundledWithEnv(component)) === false;
509
509
  }
510
510
  /**
511
511
  * This function is calculate the isScaling flag for the component preview.
@@ -1 +1 @@
1
- {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","isScaling","previewData","state","aspects","isUsingCoreEnv","calculateIsScaling","getOrCalculateEnv","previewConfig","getPreviewConfig","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","allComponentContextAspects","reduce","acc","curr","concat","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","onComponentLoad","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain, UIRoot } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n */\n async isScaling(component: Component): Promise<boolean> {\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n // Core envs are always scaling (their template bundle containing the scaling logic)\n return previewData?.isScaling ?? this.envs.isUsingCoreEnv(component);\n }\n\n /**\n * This function is calculate the isScaling flag for the component preview.\n * It should be only used during the component on load.\n * Once the component load, you should only use the `isScaling` to fetch it from the calculated data.\n * @param component\n * @returns\n */\n private async calculateIsScaling(component: Component): Promise<boolean> {\n // It's important to use getOrCalculateEnv here and not just getEnv as it's running during on load\n // so the envs data is not on the component aspects yet.\n const env = this.envs.getOrCalculateEnv(component);\n const previewConfig = env?.env?.getPreviewConfig();\n // default to true if the env doesn't have a preview config\n return previewConfig?.isScaling ?? true;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.onComponentLoad(async (component) => {\n const isScaling = await preview.calculateIsScaling(component);\n return {\n isScaling\n };\n });\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAA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AC/BqM,OAAO,CAAClL,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAAC2M,GAAlB,CAAsBrN,CAAtB,CAAxD,CADF;MAGAN,SAAS,CAAC4N,eAAV,CAA0B,MAAOzM,SAAP,IAAqB;QAC7C,MAAM2B,SAAS,GAAG,MAAO6J,OAAO,CAACxJ,kBAAR,CAA2BhC,SAA3B,CAAzB;QACA,OAAO;UACL2B;QADK,CAAP;MAGD,CALD;MAMA9C,SAAS,CAAC6N,yBAAV,CAAqCvN,CAAD,IAClCqM,OAAO,CAAClL,qBAAR,CAA8BnB,CAA9B,EAAkCU,iBAAD,IAAuBA,iBAAiB,CAAC8M,MAAlB,CAAyBxN,CAAzB,CAAxD,CADF;MAGAN,SAAS,CAAC+N,yBAAV,CAAqC7M,GAAD,IAASyL,OAAO,CAACqB,sBAAR,CAA+B9M,GAA/B,CAA7C;IACD;;IAEDuL,OAAO,CAACR,QAAR,CAAiB,IAAAgC,yBAAA,EAActB,OAAd,CAAjB;IAEA,OAAOA,OAAP;EACD;;AAriBsB;;;gCAAZvN,W,WAmbI,CAAC8O,eAAA,CAAKC,QAAL,EAAD,EAAqCD,eAAA,CAAKC,QAAL,EAArC,C;gCAnbJ/O,W,aAqbM2K,kB;gCArbN3K,W,kBAsbW,CACpBgP,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAtbX3P,W,mBAqcY;EACrBkO,QAAQ,EAAE;AADW,C;;AAmGzBpO,wBAAA,CAAc8P,UAAd,CAAyB5P,WAAzB"}
1
+ {"version":3,"names":["noopResult","results","toString","DEFAULT_TEMP_DIR","join","CACHE_ROOT","PreviewAspect","id","PreviewMain","constructor","harmony","previewSlot","ui","envs","componentAspect","pkg","aspectLoader","config","bundlingStrategySlot","builder","workspace","logger","dependencyResolver","Map","Date","now","c","updater","env","getEnv","envId","executionRef","executionRefs","get","warn","updateLinkFiles","currentComponents","executionCtx","cId","component","forEach","components","found","Promise","resolve","handleComponentChange","remove","tempFolder","getTempDir","getComponentBundleSize","data","getDataByAspect","undefined","COMPONENT_STRATEGY_SIZE_KEY_NAME","getPreview","artifacts","getArtifactsVinylByAspectAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByAspectAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","isScaling","previewData","state","aspects","isUsingCoreEnv","calculateIsScaling","getOrCalculateEnv","previewConfig","getPreviewConfig","isLegacyHeader","ENV_WITH_LEGACY_DOCS","ENV_STRATEGY_ARTIFACT_NAME","envType","getEnvData","type","includes","getEnvTemplate","GENERATE_ENV_TEMPLATE_TASK_NAME","getCoreEnvTemplate","coreEnvDir","getAspectDir","artifactDef","getEnvTemplateArtifactDef","artifactFactory","ArtifactFactory","rootDir","getRootDir","existsSync","coreEnvDirFromBvm","getAspectDirFromBvm","paths","resolvePaths","artifactFiles","ArtifactFiles","populateVinylsFromPaths","vinyls","getEnvTemplateFromComponentEnv","getEnvId","getEnvTemplateByEnvId","isCoreEnv","host","getHost","resolvedEnvId","resolveComponentId","envComponent","BitError","getDefs","values","writeLink","prefix","moduleMap","defaultModule","dirName","isSplitComponentBundle","contents","generateLink","writeLinkContents","targetDir","hash","objectHash","targetPath","timestamp","writeHash","writeFileSync","set","getPreviewTarget","context","relatedContexts","ctxId","ExecutionRef","previewRuntime","writePreviewRuntime","linkFiles","previews","map","previewDef","templatePath","renderTemplatePath","getModuleMap","getEnvPreviewConfig","splitComponentBundle","withPaths","environment","compilerInstance","getCompiler","modulePath","getPreviewComponentRootPath","getRuntimeModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","name","uiRoot","getUi","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","runtimeName","componentIds","opts","root","MainRuntime","Error","allComponentContextAspects","reduce","acc","curr","concat","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getBundlingStrategy","defaultStrategies","envPreviewConfig","strategyFromEnv","strategyName","bundlingStrategy","strategies","selected","find","strategy","BundlingStrategyNotFound","registerBundlingStrategy","register","registerDefinition","provider","bundler","componentExtension","uiMain","pubsub","loggerMain","graphql","createLogger","preview","registerStartPlugin","PreviewStartPlugin","registerRoute","PreviewRoute","ComponentPreviewRoute","EnvTemplateRoute","PreviewAssetsRoute","registerTarget","entry","bind","disabled","registerBuildTasks","EnvPreviewTemplateTask","PreviewTask","registerOnComponentAdd","add","onComponentLoad","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","BundlerAspect","BuilderAspect","ComponentAspect","UIAspect","EnvsAspect","WorkspaceAspect","PkgAspect","PubsubAspect","AspectLoaderAspect","LoggerAspect","DependencyResolverAspect","GraphqlAspect","addRuntime"],"sources":["preview.main.runtime.tsx"],"sourcesContent":["import { ArtifactFactory, BuilderAspect } from '@teambit/builder';\nimport type { BuilderMain } from '@teambit/builder';\nimport { Asset, BundlerAspect, BundlerMain } from '@teambit/bundler';\nimport { PubsubAspect, PubsubMain } from '@teambit/pubsub';\nimport { MainRuntime } from '@teambit/cli';\nimport {\n Component,\n ComponentAspect,\n ComponentMain,\n ComponentMap,\n ComponentID,\n ResolveAspectsOptions,\n} from '@teambit/component';\nimport { EnvsAspect } from '@teambit/envs';\nimport type { EnvsMain, ExecutionContext, PreviewEnv } from '@teambit/envs';\nimport { Slot, SlotRegistry, Harmony } from '@teambit/harmony';\nimport { UIAspect, UiMain, UIRoot } from '@teambit/ui';\nimport { CACHE_ROOT } from '@teambit/legacy/dist/constants';\nimport { BitError } from '@teambit/bit-error';\nimport objectHash from 'object-hash';\nimport { uniq } from 'lodash';\nimport { writeFileSync, existsSync, mkdirSync } from 'fs-extra';\nimport { join } from 'path';\nimport { PkgAspect, PkgMain } from '@teambit/pkg';\nimport { AspectLoaderAspect, getAspectDir, getAspectDirFromBvm } from '@teambit/aspect-loader';\nimport type { AspectDefinition, AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceAspect, { Workspace } from '@teambit/workspace';\nimport { LoggerAspect, LoggerMain, Logger } from '@teambit/logger';\nimport { DependencyResolverAspect } from '@teambit/dependency-resolver';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { ArtifactFiles } from '@teambit/legacy/dist/consumer/component/sources/artifact-files';\nimport GraphqlAspect, { GraphqlMain } from '@teambit/graphql';\nimport { BundlingStrategyNotFound } from './exceptions';\nimport { generateLink } from './generate-link';\nimport { PreviewArtifact } from './preview-artifact';\nimport { PreviewDefinition } from './preview-definition';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { PreviewRoute } from './preview.route';\nimport { PreviewTask, PREVIEW_TASK_NAME } from './preview.task';\nimport { BundlingStrategy } from './bundling-strategy';\nimport { EnvBundlingStrategy, ComponentBundlingStrategy } from './strategies';\nimport { ExecutionRef } from './execution-ref';\nimport { PreviewStartPlugin } from './preview.start-plugin';\nimport {\n EnvPreviewTemplateTask,\n GENERATE_ENV_TEMPLATE_TASK_NAME,\n getArtifactDef as getEnvTemplateArtifactDef,\n} from './env-preview-template.task';\nimport { EnvTemplateRoute } from './env-template.route';\nimport { ComponentPreviewRoute } from './component-preview.route';\nimport { COMPONENT_STRATEGY_ARTIFACT_NAME, COMPONENT_STRATEGY_SIZE_KEY_NAME } from './strategies/component-strategy';\nimport { ENV_STRATEGY_ARTIFACT_NAME } from './strategies/env-strategy';\nimport { previewSchema } from './preview.graphql';\nimport { PreviewAssetsRoute } from './preview-assets.route';\n\nconst noopResult = {\n results: [],\n toString: () => `updating link file`,\n};\n\nconst DEFAULT_TEMP_DIR = join(CACHE_ROOT, PreviewAspect.id);\n\nexport type PreviewDefinitionRegistry = SlotRegistry<PreviewDefinition>;\n\ntype PreviewFiles = {\n files: string[];\n isBundledWithEnv: boolean;\n};\n\nexport type ComponentPreviewSizedFile = Asset;\n\nexport type ComponentPreviewSize = {\n files: ComponentPreviewSizedFile[];\n assets: ComponentPreviewSizedFile[];\n totalFiles: number;\n compressedTotalFiles?: number;\n totalAssets: number;\n compressedTotalAssets?: number;\n total: number;\n compressedTotal?: number;\n};\n\nexport type ComponentPreviewMetaData = {\n size?: ComponentPreviewSize;\n};\n\nexport type PreviewConfig = {\n bundlingStrategy?: string;\n disabled: boolean;\n /**\n * limit concurrent components when running the bundling step for your bundler during generate components preview task.\n * this helps mitigate large memory consumption for the build pipeline. This may increase the overall time for the generate-preview task, but reduce memory footprint.\n * default - no limit.\n */\n maxChunkSize?: number;\n};\n\nexport type EnvPreviewConfig = {\n strategyName?: string;\n splitComponentBundle?: boolean;\n};\n\nexport type BundlingStrategySlot = SlotRegistry<BundlingStrategy>;\n\nexport type GenerateLinkFn = (prefix: string, componentMap: ComponentMap<string[]>, defaultModule?: string) => string;\n\nexport class PreviewMain {\n constructor(\n /**\n * harmony context.\n */\n private harmony: Harmony,\n\n /**\n * slot for preview definitions.\n */\n private previewSlot: PreviewDefinitionRegistry,\n\n private ui: UiMain,\n\n private envs: EnvsMain,\n\n private componentAspect: ComponentMain,\n\n private pkg: PkgMain,\n\n private aspectLoader: AspectLoaderMain,\n\n readonly config: PreviewConfig,\n\n private bundlingStrategySlot: BundlingStrategySlot,\n\n private builder: BuilderMain,\n\n private workspace: Workspace | undefined,\n\n private logger: Logger,\n\n private dependencyResolver: DependencyResolverMain\n ) {}\n\n get tempFolder(): string {\n return this.workspace?.getTempDir(PreviewAspect.id) || DEFAULT_TEMP_DIR;\n }\n\n getComponentBundleSize(component: Component): ComponentPreviewSize | undefined {\n const data = this.builder.getDataByAspect(component, PreviewAspect.id);\n\n if (!data) return undefined;\n return data[COMPONENT_STRATEGY_SIZE_KEY_NAME];\n }\n\n async getPreview(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n PREVIEW_TASK_NAME\n );\n if (!artifacts) return undefined;\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * Get a list of all the artifact files generated during the GeneratePreview task\n * @param component\n * @returns\n */\n async getPreviewFiles(component: Component): Promise<PreviewFiles | undefined> {\n const artifacts = await this.getPreview(component);\n const isBundledWithEnv = await this.isBundledWithEnv(component);\n if (!artifacts) return undefined;\n return {\n files: artifacts.getPaths(),\n isBundledWithEnv,\n };\n }\n\n /**\n * Check if the component preview bundle contain the env as part of the bundle or only the component code\n * (we used in the past to bundle them together, there might also be specific envs which still uses the env strategy)\n * @param component\n * @returns\n */\n async isBundledWithEnv(component: Component): Promise<boolean> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n COMPONENT_STRATEGY_ARTIFACT_NAME\n );\n if (!artifacts || !artifacts.length) return true;\n\n return false;\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n */\n async isScaling(component: Component): Promise<boolean> {\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality\n return (\n previewData?.isScaling ??\n (this.envs.isUsingCoreEnv(component) && (await this.isBundledWithEnv(component)) === false)\n );\n }\n\n /**\n * This function is calculate the isScaling flag for the component preview.\n * It should be only used during the component on load.\n * Once the component load, you should only use the `isScaling` to fetch it from the calculated data.\n * @param component\n * @returns\n */\n private async calculateIsScaling(component: Component): Promise<boolean> {\n // It's important to use getOrCalculateEnv here and not just getEnv as it's running during on load\n // so the envs data is not on the component aspects yet.\n const env = this.envs.getOrCalculateEnv(component);\n const previewConfig = env?.env?.getPreviewConfig();\n // default to true if the env doesn't have a preview config\n return previewConfig?.isScaling ?? true;\n }\n\n /**\n * Check if the component preview bundle contain the header inside of it (legacy)\n * today we are not including the header inside anymore\n * @param component\n * @returns\n */\n async isLegacyHeader(component: Component): Promise<boolean> {\n // these envs had header in their docs\n const ENV_WITH_LEGACY_DOCS = ['react', 'env', 'aspect', 'lit', 'html', 'node', 'mdx', 'react-native', 'readme'];\n\n const artifacts = await this.builder.getArtifactsVinylByAspectAndName(\n component,\n PreviewAspect.id,\n ENV_STRATEGY_ARTIFACT_NAME\n );\n const envType = this.envs.getEnvData(component).type;\n return !!artifacts && !!artifacts.length && ENV_WITH_LEGACY_DOCS.includes(envType);\n }\n\n /**\n * Getting the env template artifact\n * This should be called with the env itself or it will return undefined\n * If you want to get the env template from the env of the component,\n * use: getEnvTemplateFromComponentEnv below\n *\n * @param component\n * @returns\n */\n async getEnvTemplate(component: Component): Promise<PreviewArtifact | undefined> {\n const artifacts = await this.builder.getArtifactsVinylByAspectAndTaskName(\n component,\n PreviewAspect.id,\n GENERATE_ENV_TEMPLATE_TASK_NAME\n );\n if (!artifacts || !artifacts.length) return undefined;\n\n return new PreviewArtifact(artifacts);\n }\n\n /**\n * This is a special method to get a core env template\n * As the core envs doesn't exist in the scope we need to bring it from other place\n * We will bring it from the core env package files\n */\n private async getCoreEnvTemplate(envId: string): Promise<PreviewArtifact | undefined> {\n const coreEnvDir = getAspectDir(envId);\n // const finalDir = join(coreEnvDir, getEnvTemplateArtifactDirectory());\n const artifactDef = getEnvTemplateArtifactDef()[0];\n const artifactFactory = new ArtifactFactory();\n\n let rootDir = artifactFactory.getRootDir(coreEnvDir, artifactDef);\n if (!existsSync(rootDir)) {\n // fallback to the bvm folder\n const coreEnvDirFromBvm = getAspectDirFromBvm(envId);\n rootDir = artifactFactory.getRootDir(coreEnvDirFromBvm, artifactDef);\n }\n if (!existsSync(rootDir)) {\n return undefined;\n }\n const paths = artifactFactory.resolvePaths(rootDir, artifactDef);\n if (!paths || !paths.length) {\n return undefined;\n }\n const artifactFiles = new ArtifactFiles(paths);\n\n artifactFiles.populateVinylsFromPaths(rootDir);\n return new PreviewArtifact(artifactFiles.vinyls);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateFromComponentEnv(component: Component): Promise<PreviewArtifact | undefined> {\n const envId = this.envs.getEnvId(component);\n return this.getEnvTemplateByEnvId(envId);\n }\n\n /**\n * This will fetch the component env, then will take the env template from the component env\n * @param component\n */\n async getEnvTemplateByEnvId(envId: string): Promise<PreviewArtifact | undefined> {\n // Special treatment for core envs\n if (this.aspectLoader.isCoreEnv(envId)) {\n return this.getCoreEnvTemplate(envId);\n }\n const host = this.componentAspect.getHost();\n const resolvedEnvId = await host.resolveComponentId(envId);\n const envComponent = await host.get(resolvedEnvId);\n if (!envComponent) {\n throw new BitError(`can't load env. env id is ${envId}`);\n }\n return this.getEnvTemplate(envComponent);\n }\n\n getDefs(): PreviewDefinition[] {\n return this.previewSlot.values();\n }\n\n private writeHash = new Map<string, string>();\n private timestamp = Date.now();\n\n /**\n * write a link to load custom modules dynamically.\n * @param prefix write\n * @param moduleMap map of components to module paths to require.\n * @param defaultModule\n * @param dirName\n */\n writeLink(\n prefix: string,\n moduleMap: ComponentMap<string[]>,\n defaultModule: string | undefined,\n dirName: string,\n isSplitComponentBundle: boolean\n ) {\n const contents = generateLink(prefix, moduleMap, defaultModule, isSplitComponentBundle);\n return this.writeLinkContents(contents, dirName, prefix);\n }\n\n writeLinkContents(contents: string, targetDir: string, prefix: string) {\n const hash = objectHash(contents);\n const targetPath = join(targetDir, `${prefix}-${this.timestamp}.js`);\n\n // write only if link has changed (prevents triggering fs watches)\n if (this.writeHash.get(targetPath) !== hash) {\n writeFileSync(targetPath, contents);\n this.writeHash.set(targetPath, hash);\n }\n\n return targetPath;\n }\n\n private executionRefs = new Map<string, ExecutionRef>();\n\n private async getPreviewTarget(\n /** execution context (of the specific env) */\n context: ExecutionContext\n ): Promise<string[]> {\n // store context for later link-file updates\n // also register related envs that this context is acting on their behalf\n [context.id, ...context.relatedContexts].forEach((ctxId) => {\n this.executionRefs.set(ctxId, new ExecutionRef(context));\n });\n\n const previewRuntime = await this.writePreviewRuntime(context);\n const linkFiles = await this.updateLinkFiles(context.components, context);\n\n return [...linkFiles, previewRuntime];\n }\n\n private updateLinkFiles(components: Component[] = [], context: ExecutionContext) {\n const previews = this.previewSlot.values();\n const paths = previews.map(async (previewDef) => {\n const templatePath = await previewDef.renderTemplatePath?.(context);\n\n const map = await previewDef.getModuleMap(components);\n const isSplitComponentBundle = this.getEnvPreviewConfig().splitComponentBundle ?? false;\n const withPaths = map.map<string[]>((files, component) => {\n const environment = this.envs.getEnv(component).env;\n const compilerInstance = environment.getCompiler?.();\n const modulePath =\n compilerInstance?.getPreviewComponentRootPath?.(component) || this.pkg.getRuntimeModulePath(component);\n return files.map((file) => {\n if (!this.workspace || !compilerInstance) {\n return file.path;\n }\n const distRelativePath = compilerInstance.getDistPathBySrcPath(file.relative);\n return join(this.workspace.path, modulePath, distRelativePath);\n });\n // return files.map((file) => file.path);\n });\n\n const dirPath = join(this.tempFolder, context.id);\n if (!existsSync(dirPath)) mkdirSync(dirPath, { recursive: true });\n\n const link = this.writeLink(previewDef.prefix, withPaths, templatePath, dirPath, isSplitComponentBundle);\n return link;\n });\n\n return Promise.all(paths);\n }\n\n async writePreviewRuntime(context: { components: Component[] }, aspectsIdsToNotFilterOut: string[] = []) {\n const [name, uiRoot] = this.getUi();\n const resolvedAspects = await this.resolveAspects(PreviewRuntime.name, undefined, uiRoot);\n const filteredAspects = this.filterAspectsByExecutionContext(resolvedAspects, context, aspectsIdsToNotFilterOut);\n const filePath = await this.ui.generateRoot(filteredAspects, name, 'preview', PreviewAspect.id);\n return filePath;\n }\n\n async resolveAspects(\n runtimeName?: string,\n componentIds?: ComponentID[],\n uiRoot?: UIRoot,\n opts?: ResolveAspectsOptions\n ): Promise<AspectDefinition[]> {\n const root = uiRoot || this.getUi()[1];\n runtimeName = runtimeName || MainRuntime.name;\n const resolvedAspects = await root.resolveAspects(runtimeName, componentIds, opts);\n return resolvedAspects;\n }\n\n private getUi() {\n const ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n return ui;\n }\n\n /**\n * Filter the aspects to have only aspects that are:\n * 1. core aspects\n * 2. configured on the host (workspace/scope)\n * 3. used by at least one component from the context\n * @param aspects\n * @param context\n */\n private filterAspectsByExecutionContext(\n aspects: AspectDefinition[],\n context: { components: Component[] },\n aspectsIdsToNotFilterOut: string[] = []\n ) {\n let allComponentContextAspects: string[] = [];\n allComponentContextAspects = context.components.reduce((acc, curr) => {\n return acc.concat(curr.state.aspects.ids);\n }, allComponentContextAspects);\n const hostAspects = Object.keys(this.harmony.config.toObject());\n const allAspectsToInclude = uniq(hostAspects.concat(allComponentContextAspects));\n const filtered = aspects.filter((aspect) => {\n if (!aspect.getId) {\n return false;\n }\n return (\n this.aspectLoader.isCoreAspect(aspect.getId) ||\n allAspectsToInclude.includes(aspect.getId) ||\n aspectsIdsToNotFilterOut.includes(aspect.getId)\n );\n });\n\n return filtered;\n }\n\n private getDefaultStrategies() {\n return [\n new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),\n new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),\n ];\n }\n\n // TODO - executionContext should be responsible for updating components list, and emit 'update' events\n // instead we keep track of changes\n private handleComponentChange = async (c: Component, updater: (currentComponents: ExecutionRef) => void) => {\n const env = this.envs.getEnv(c);\n const envId = env.id.toString();\n\n const executionRef = this.executionRefs.get(envId);\n if (!executionRef) {\n this.logger.warn(\n `failed to update link file for component \"${c.id.toString()}\" - could not find execution context for ${envId}`\n );\n return noopResult;\n }\n\n // add / remove / etc\n updater(executionRef);\n\n await this.updateLinkFiles(executionRef.currentComponents, executionRef.executionCtx);\n\n return noopResult;\n };\n\n private handleComponentRemoval = (cId: ComponentID) => {\n let component: Component | undefined;\n this.executionRefs.forEach((components) => {\n const found = components.get(cId);\n if (found) component = found;\n });\n if (!component) return Promise.resolve(noopResult);\n\n return this.handleComponentChange(component, (currentComponents) => currentComponents.remove(cId));\n };\n\n getEnvPreviewConfig(env?: PreviewEnv): EnvPreviewConfig {\n const config = env?.getPreviewConfig && typeof env?.getPreviewConfig === 'function' ? env?.getPreviewConfig() : {};\n\n return config;\n }\n\n /**\n * return the configured bundling strategy.\n */\n getBundlingStrategy(env?: PreviewEnv): BundlingStrategy {\n const defaultStrategies = this.getDefaultStrategies();\n const envPreviewConfig = this.getEnvPreviewConfig(env);\n const strategyFromEnv = envPreviewConfig?.strategyName;\n const strategyName = strategyFromEnv || this.config.bundlingStrategy || 'env';\n const strategies = this.bundlingStrategySlot.values().concat(defaultStrategies);\n const selected = strategies.find((strategy) => {\n return strategy.name === strategyName;\n });\n\n if (!selected) throw new BundlingStrategyNotFound(strategyName);\n\n return selected;\n }\n\n /**\n * register a new bundling strategy. default available strategies are `env` and ``\n */\n registerBundlingStrategy(bundlingStrategy: BundlingStrategy) {\n this.bundlingStrategySlot.register(bundlingStrategy);\n return this;\n }\n\n /**\n * register a new preview definition.\n */\n registerDefinition(previewDef: PreviewDefinition) {\n this.previewSlot.register(previewDef);\n }\n\n static slots = [Slot.withType<PreviewDefinition>(), Slot.withType<BundlingStrategy>()];\n\n static runtime = MainRuntime;\n static dependencies = [\n BundlerAspect,\n BuilderAspect,\n ComponentAspect,\n UIAspect,\n EnvsAspect,\n WorkspaceAspect,\n PkgAspect,\n PubsubAspect,\n AspectLoaderAspect,\n LoggerAspect,\n DependencyResolverAspect,\n GraphqlAspect,\n ];\n\n static defaultConfig = {\n disabled: false,\n };\n\n static async provider(\n // eslint-disable-next-line max-len\n [\n bundler,\n builder,\n componentExtension,\n uiMain,\n envs,\n workspace,\n pkg,\n pubsub,\n aspectLoader,\n loggerMain,\n dependencyResolver,\n graphql,\n ]: [\n BundlerMain,\n BuilderMain,\n ComponentMain,\n UiMain,\n EnvsMain,\n Workspace | undefined,\n PkgMain,\n PubsubMain,\n AspectLoaderMain,\n LoggerMain,\n DependencyResolverMain,\n GraphqlMain\n ],\n config: PreviewConfig,\n [previewSlot, bundlingStrategySlot]: [PreviewDefinitionRegistry, BundlingStrategySlot],\n harmony: Harmony\n ) {\n const logger = loggerMain.createLogger(PreviewAspect.id);\n // app.registerApp(new PreviewApp());\n const preview = new PreviewMain(\n harmony,\n previewSlot,\n uiMain,\n envs,\n componentExtension,\n pkg,\n aspectLoader,\n config,\n bundlingStrategySlot,\n builder,\n workspace,\n logger,\n dependencyResolver\n );\n\n if (workspace) uiMain.registerStartPlugin(new PreviewStartPlugin(workspace, bundler, uiMain, pubsub, logger));\n\n componentExtension.registerRoute([\n new PreviewRoute(preview, logger),\n new ComponentPreviewRoute(preview, logger),\n // @ts-ignore\n new EnvTemplateRoute(preview, logger),\n new PreviewAssetsRoute(preview, logger),\n ]);\n\n bundler.registerTarget([\n {\n entry: preview.getPreviewTarget.bind(preview),\n },\n ]);\n\n if (!config.disabled)\n builder.registerBuildTasks([\n new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),\n new PreviewTask(bundler, preview, dependencyResolver, logger),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\n );\n workspace.onComponentLoad(async (component) => {\n const isScaling = await preview.calculateIsScaling(component);\n return {\n isScaling,\n };\n });\n workspace.registerOnComponentChange((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))\n );\n workspace.registerOnComponentRemove((cId) => preview.handleComponentRemoval(cId));\n }\n\n graphql.register(previewSchema(preview));\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EA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gCAxbN3K,W,kBAybW,CACpBgP,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAzbX3P,W,mBAwcY;EACrBkO,QAAQ,EAAE;AADW,C;;AAmGzBpO,wBAAA,CAAc8P,UAAd,CAAyB5P,WAAzB"}
@@ -284,7 +284,7 @@ class PreviewPreview {
284
284
  }));
285
285
  };
286
286
 
287
- window.addEventListener('resize', (0, _lodash().debounce)(sendPubsubEvent, 300));
287
+ window.document.body.addEventListener('resize', (0, _lodash().debounce)(sendPubsubEvent, 300));
288
288
  let counter = 0;
289
289
  const interval = setInterval(() => {
290
290
  // TODO: think
@@ -1 +1 @@
1
- {"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\nimport { debounce } from 'lodash';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n // fit content always.\n window.document.body.style.width = 'fit-content';\n\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(\n componentId,\n previewModule,\n includes,\n this.getRenderingContext(componentAspects)\n );\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }\n\n window.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }, 200);\n }\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;E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ve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","window","document","body","style","width","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","previewModule","render","getRenderingContext","reportSize","setViewport","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","query","getQuery","viewPort","getParam","maxWidth","parent","sendPubsubEvent","SizeEvent","offsetWidth","height","offsetHeight","debounce","counter","interval","setInterval","clearInterval","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","metadata","mainModule","componentMapMetadata","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","catch","err","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","param","params","URLSearchParams","withoutHash","location","hash","substring","after","split","before","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\nimport { debounce } from 'lodash';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\nimport { SizeEvent } from './size-event';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n // fit content always.\n window.document.body.style.width = 'fit-content';\n\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n const previewModule = await this.getPreviewModule(name, componentId);\n const render = preview.render(\n componentId,\n previewModule,\n includes,\n this.getRenderingContext(componentAspects)\n );\n\n this.reportSize();\n this.setViewport();\n return render;\n };\n\n setViewport() {\n const query = this.getQuery();\n const viewPort = this.getParam(query, 'viewport');\n if (!viewPort) {\n window.document.body.style.width = '100%';\n return;\n }\n\n window.document.body.style.maxWidth = `${viewPort}px`;\n }\n\n reportSize() {\n if (!window?.parent || !window?.document) return;\n // TODO: discuss with gilad for a better way to resolve page loaded here.\n\n const sendPubsubEvent = () => {\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }\n\n window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));\n\n let counter = 0;\n const interval = setInterval(() => {\n // TODO: think\n counter += 1;\n if (counter > 10) {\n clearInterval(interval);\n return;\n }\n this.pubsub.pub(PreviewAspect.id, new SizeEvent({\n width: window.document.body.offsetWidth,\n height: window.document.body.offsetHeight\n }));\n }, 200);\n }\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n const metadata = componentPreviews[`${previewName}_metadata`];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n componentMapMetadata: {\n [id.fullName]: metadata,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n\n // TODO - should we load assets other than .css / .js?\n // if (previewBundleFileName.endsWith('.css')) {\n this.addComponentFileLinkElement(id, previewBundleFileName).catch((err) => {\n throw new Error(\n `[preview.preview] failed loading asset \"${previewBundleFileName}\". Error - \"${err?.toString()}\"`\n );\n });\n\n // do NOT await non js assets, as they might never load (like images), and not critical for rendering.\n return undefined;\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n getQuery() {\n const withoutHash = window.location.hash.substring(1);\n const [, after] = withoutHash.split('?');\n return after;\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAMA,cAAN,CAAqB;EAC1BC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,WATC,EAWDC,oBAXC,EAYT;IAAA,KARQF,MAQR,GARQA,MAQR;IAAA,KAHQC,WAGR,GAHQA,WAGR;I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0BF,MAA1B;IAFR,CAAP;EAID;;EAQoB,aAARG,QAAQ,CACnB,CAACvJ,MAAD,CADmB,EAEnBwJ,MAFmB,EAGnB,CAACvJ,WAAD,EAAcC,oBAAd,CAHmB,EAInB;IACA,MAAMoB,OAAO,GAAG,IAAIxB,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEAS,MAAM,CAACyC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA9B,OAAO,CAACqB,MAAR;IACD,CAHD;IAKA,OAAOrB,OAAP;EACD;;AAvUyB;;;gCAAfxB,c,aAoTM2J,yB;gCApTN3J,c,kBAsTW,CAAC4J,iBAAD,C;gCAtTX5J,c,WAwTI,CAAC6J,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB/F,wBAAA,CAAcgG,UAAd,CAAyB/J,cAAzB"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.853",
3
+ "version": "0.0.855",
4
4
  "homepage": "https://bit.dev/teambit/preview/preview",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.preview",
8
8
  "name": "preview",
9
- "version": "0.0.853"
9
+ "version": "0.0.855"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -22,30 +22,30 @@
22
22
  "graphql-request": "3.4.0",
23
23
  "@babel/runtime": "7.12.18",
24
24
  "core-js": "^3.0.0",
25
- "@teambit/express": "0.0.664",
26
- "@teambit/logger": "0.0.659",
25
+ "@teambit/express": "0.0.666",
26
+ "@teambit/logger": "0.0.661",
27
27
  "@teambit/ui-foundation.ui.pages.static-error": "0.0.82",
28
- "@teambit/builder": "0.0.853",
29
- "@teambit/bundler": "0.0.853",
30
- "@teambit/component": "0.0.853",
31
- "@teambit/preview.ui.component-preview": "0.0.502",
32
- "@teambit/aspect-loader": "0.0.853",
33
- "@teambit/cli": "0.0.566",
34
- "@teambit/dependency-resolver": "0.0.853",
35
- "@teambit/envs": "0.0.853",
28
+ "@teambit/builder": "0.0.855",
29
+ "@teambit/bundler": "0.0.855",
30
+ "@teambit/component": "0.0.855",
31
+ "@teambit/preview.ui.component-preview": "0.0.503",
32
+ "@teambit/aspect-loader": "0.0.855",
33
+ "@teambit/cli": "0.0.568",
34
+ "@teambit/dependency-resolver": "0.0.855",
35
+ "@teambit/envs": "0.0.855",
36
36
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.489",
37
37
  "@teambit/component-id": "0.0.417",
38
38
  "@teambit/harmony": "0.3.3",
39
39
  "@teambit/bit-error": "0.0.400",
40
- "@teambit/graphql": "0.0.853",
41
- "@teambit/pkg": "0.0.853",
42
- "@teambit/pubsub": "0.0.853",
43
- "@teambit/ui": "0.0.853",
44
- "@teambit/workspace": "0.0.853",
45
- "@teambit/compiler": "0.0.853",
40
+ "@teambit/graphql": "0.0.855",
41
+ "@teambit/pkg": "0.0.855",
42
+ "@teambit/pubsub": "0.0.855",
43
+ "@teambit/ui": "0.0.855",
44
+ "@teambit/workspace": "0.0.855",
45
+ "@teambit/compiler": "0.0.855",
46
46
  "@teambit/preview.cli.preview-server-status": "0.0.498",
47
47
  "@teambit/preview.cli.webpack-events-listener": "0.0.167",
48
- "@teambit/isolator": "0.0.853"
48
+ "@teambit/isolator": "0.0.855"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@types/mime": "2.0.3",
@@ -63,7 +63,7 @@
63
63
  "@teambit/preview.aspect-docs.preview": "0.0.145"
64
64
  },
65
65
  "peerDependencies": {
66
- "@teambit/legacy": "1.0.347",
66
+ "@teambit/legacy": "1.0.349",
67
67
  "react-dom": "^16.8.0 || ^17.0.0",
68
68
  "react": "^16.8.0 || ^17.0.0"
69
69
  },
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.853/dist/preview.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.853/dist/preview.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.855/dist/preview.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.855/dist/preview.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -197,8 +197,11 @@ export class PreviewMain {
197
197
  */
198
198
  async isScaling(component: Component): Promise<boolean> {
199
199
  const previewData = component.state.aspects.get(PreviewAspect.id)?.data;
200
- // Core envs are always scaling (their template bundle containing the scaling logic)
201
- return previewData?.isScaling ?? this.envs.isUsingCoreEnv(component);
200
+ // if it's a core env and the env template is apart from the component it means the template bundle already contain the scaling functionality
201
+ return (
202
+ previewData?.isScaling ??
203
+ (this.envs.isUsingCoreEnv(component) && (await this.isBundledWithEnv(component)) === false)
204
+ );
202
205
  }
203
206
 
204
207
  /**
@@ -639,9 +642,9 @@ export class PreviewMain {
639
642
  preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))
640
643
  );
641
644
  workspace.onComponentLoad(async (component) => {
642
- const isScaling = await preview.calculateIsScaling(component);
645
+ const isScaling = await preview.calculateIsScaling(component);
643
646
  return {
644
- isScaling
647
+ isScaling,
645
648
  };
646
649
  });
647
650
  workspace.registerOnComponentChange((c) =>
@@ -142,7 +142,7 @@ export class PreviewPreview {
142
142
  }));
143
143
  }
144
144
 
145
- window.addEventListener('resize', debounce(sendPubsubEvent, 300));
145
+ window.document.body.addEventListener('resize', debounce(sendPubsubEvent, 300));
146
146
 
147
147
  let counter = 0;
148
148
  const interval = setInterval(() => {