@teambit/preview 0.0.857 → 0.0.859

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.
@@ -22,6 +22,9 @@ function previewSchema(previewExtension) {
22
22
  typeDefs: (0, _graphqlTag().default)`
23
23
  type Preview {
24
24
  # url: String!
25
+ """
26
+ Check if the component supports scaling
27
+ """
25
28
  isScaling: Boolean
26
29
  includesEnvTemplate: Boolean
27
30
  legacyHeader: Boolean
@@ -49,7 +52,7 @@ function previewSchema(previewExtension) {
49
52
  isScaling: ({
50
53
  component
51
54
  }) => {
52
- return previewExtension.isScaling(component);
55
+ return previewExtension.doesScaling(component);
53
56
  },
54
57
  legacyHeader: ({
55
58
  component
@@ -1 +1 @@
1
- {"version":3,"names":["previewSchema","previewExtension","typeDefs","gql","resolvers","Component","preview","component","Preview","includesEnvTemplate","isBundledWithEnv","isScaling","legacyHeader","isLegacyHeader"],"sources":["preview.graphql.ts"],"sourcesContent":["import { Component } from '@teambit/component';\nimport gql from 'graphql-tag';\n\nimport { PreviewMain } from './preview.main.runtime';\n\nexport function previewSchema(previewExtension: PreviewMain) {\n return {\n typeDefs: gql`\n type Preview {\n # url: String!\n isScaling: Boolean\n includesEnvTemplate: Boolean\n legacyHeader: Boolean\n }\n\n extend type Component {\n preview: Preview\n }\n `,\n resolvers: {\n Component: {\n preview: (component: Component) => {\n // return previewExtension.getPreview(component);\n return { component };\n },\n },\n Preview: {\n includesEnvTemplate: ({ component }) => {\n return previewExtension.isBundledWithEnv(component);\n },\n isScaling: ({ component }) => {\n return previewExtension.isScaling(component);\n },\n legacyHeader: ({ component }) => {\n return previewExtension.isLegacyHeader(component);\n },\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIO,SAASA,aAAT,CAAuBC,gBAAvB,EAAsD;EAC3D,OAAO;IACLC,QAAQ,EAAE,IAAAC,qBAAA,CAAI;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAZS;IAaLC,SAAS,EAAE;MACTC,SAAS,EAAE;QACTC,OAAO,EAAGC,SAAD,IAA0B;UACjC;UACA,OAAO;YAAEA;UAAF,CAAP;QACD;MAJQ,CADF;MAOTC,OAAO,EAAE;QACPC,mBAAmB,EAAE,CAAC;UAAEF;QAAF,CAAD,KAAmB;UACtC,OAAON,gBAAgB,CAACS,gBAAjB,CAAkCH,SAAlC,CAAP;QACD,CAHM;QAIPI,SAAS,EAAE,CAAC;UAAEJ;QAAF,CAAD,KAAmB;UAC5B,OAAON,gBAAgB,CAACU,SAAjB,CAA2BJ,SAA3B,CAAP;QACD,CANM;QAOPK,YAAY,EAAE,CAAC;UAAEL;QAAF,CAAD,KAAmB;UAC/B,OAAON,gBAAgB,CAACY,cAAjB,CAAgCN,SAAhC,CAAP;QACD;MATM;IAPA;EAbN,CAAP;AAiCD"}
1
+ {"version":3,"names":["previewSchema","previewExtension","typeDefs","gql","resolvers","Component","preview","component","Preview","includesEnvTemplate","isBundledWithEnv","isScaling","doesScaling","legacyHeader","isLegacyHeader"],"sources":["preview.graphql.ts"],"sourcesContent":["import { Component } from '@teambit/component';\nimport gql from 'graphql-tag';\n\nimport { PreviewMain } from './preview.main.runtime';\n\nexport function previewSchema(previewExtension: PreviewMain) {\n return {\n typeDefs: gql`\n type Preview {\n # url: String!\n \"\"\"\n Check if the component supports scaling\n \"\"\"\n isScaling: Boolean\n includesEnvTemplate: Boolean\n legacyHeader: Boolean\n }\n\n extend type Component {\n preview: Preview\n }\n `,\n resolvers: {\n Component: {\n preview: (component: Component) => {\n // return previewExtension.getPreview(component);\n return { component };\n },\n },\n Preview: {\n includesEnvTemplate: ({ component }) => {\n return previewExtension.isBundledWithEnv(component);\n },\n isScaling: ({ component }) => {\n return previewExtension.doesScaling(component);\n },\n legacyHeader: ({ component }) => {\n return previewExtension.isLegacyHeader(component);\n },\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIO,SAASA,aAAT,CAAuBC,gBAAvB,EAAsD;EAC3D,OAAO;IACLC,QAAQ,EAAE,IAAAC,qBAAA,CAAI;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAfS;IAgBLC,SAAS,EAAE;MACTC,SAAS,EAAE;QACTC,OAAO,EAAGC,SAAD,IAA0B;UACjC;UACA,OAAO;YAAEA;UAAF,CAAP;QACD;MAJQ,CADF;MAOTC,OAAO,EAAE;QACPC,mBAAmB,EAAE,CAAC;UAAEF;QAAF,CAAD,KAAmB;UACtC,OAAON,gBAAgB,CAACS,gBAAjB,CAAkCH,SAAlC,CAAP;QACD,CAHM;QAIPI,SAAS,EAAE,CAAC;UAAEJ;QAAF,CAAD,KAAmB;UAC5B,OAAON,gBAAgB,CAACW,WAAjB,CAA6BL,SAA7B,CAAP;QACD,CANM;QAOPM,YAAY,EAAE,CAAC;UAAEN;QAAF,CAAD,KAAmB;UAC/B,OAAON,gBAAgB,CAACa,cAAjB,CAAgCP,SAAhC,CAAP;QACD;MATM;IAPA;EAhBN,CAAP;AAoCD"}
@@ -33,6 +33,16 @@ export declare type ComponentPreviewSize = {
33
33
  export declare type ComponentPreviewMetaData = {
34
34
  size?: ComponentPreviewSize;
35
35
  };
36
+ export declare type PreviewVariantConfig = {
37
+ isScaling?: boolean;
38
+ };
39
+ /**
40
+ * Preview data that stored on the component on load
41
+ */
42
+ export declare type PreviewComponentData = {
43
+ doesScaling?: boolean;
44
+ isScaling?: boolean;
45
+ };
36
46
  export declare type PreviewConfig = {
37
47
  bundlingStrategy?: string;
38
48
  disabled: boolean;
@@ -94,18 +104,35 @@ export declare class PreviewMain {
94
104
  * @returns
95
105
  */
96
106
  isBundledWithEnv(component: Component): Promise<boolean>;
107
+ private calcDoesScalingForComponent;
97
108
  /**
98
109
  * can the current component preview scale in size for different preview sizes.
110
+ * this calculation is based on the env of the component and if the env of the component support it.
111
+ */
112
+ doesScaling(component: Component): Promise<boolean>;
113
+ /**
114
+ * Check if the current version of the env support scaling
115
+ * @param envComponent
116
+ * @returns
117
+ */
118
+ isEnvSupportScaling(envComponent: Component): boolean;
119
+ /**
120
+ * This function is calculate the isScaling support flag for the component preview.
121
+ * This is calculated only for the env component and not for the component itself.
122
+ * It should be only used during the (env) component on load.
123
+ * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.
124
+ * If you want to check if an env for a given component support scaling, use the `isScaling` function.
125
+ * @param component
126
+ * @returns
99
127
  */
100
- isScaling(component: Component): Promise<boolean>;
128
+ private calculateIsEnvSupportScaling;
101
129
  /**
102
- * This function is calculate the isScaling flag for the component preview.
103
- * It should be only used during the component on load.
104
- * Once the component load, you should only use the `isScaling` to fetch it from the calculated data.
130
+ * Get the preview config of the component.
131
+ * (config that was set by variants or on bitmap)
105
132
  * @param component
106
133
  * @returns
107
134
  */
108
- private calculateIsScaling;
135
+ getPreviewConfig(component: Component): PreviewVariantConfig | undefined;
109
136
  /**
110
137
  * Check if the component preview bundle contain the header inside of it (legacy)
111
138
  * today we are not including the header inside anymore
@@ -494,37 +494,114 @@ class PreviewMain {
494
494
  const artifacts = await this.builder.getArtifactsVinylByAspectAndName(component, _preview().PreviewAspect.id, _componentStrategy().COMPONENT_STRATEGY_ARTIFACT_NAME);
495
495
  if (!artifacts || !artifacts.length) return true;
496
496
  return false;
497
+ } // This used on component load to calc the final result of support is scaling for a given component
498
+ // This calc based on the env, env data, env preview config and more
499
+ // if you want to get the final result use the `doesScaling` method below
500
+ // This should be used only for component load
501
+
502
+
503
+ async calcDoesScalingForComponent(component) {
504
+ const isBundledWithEnv = await this.isBundledWithEnv(component); // 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
505
+
506
+ if (this.envs.isUsingCoreEnv(component)) {
507
+ // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)
508
+ // If it's new, and we are here, it means that we already use a version of the env that support scaling
509
+ const isNew = await component.isNew();
510
+
511
+ if (isNew) {
512
+ return true;
513
+ }
514
+
515
+ return isBundledWithEnv === false;
516
+ } // For envs that bundled with the env return true always
517
+
518
+
519
+ if (isBundledWithEnv) {
520
+ return true;
521
+ }
522
+
523
+ const envComponent = await this.envs.getEnvComponent(component);
524
+ return this.isEnvSupportScaling(envComponent);
497
525
  }
498
526
  /**
499
527
  * can the current component preview scale in size for different preview sizes.
528
+ * this calculation is based on the env of the component and if the env of the component support it.
500
529
  */
501
530
 
502
531
 
503
- async isScaling(component) {
504
- var _component$state$aspe, _previewData$isScalin;
532
+ async doesScaling(component) {
533
+ var _this$workspace2, _component$state$aspe;
534
+
535
+ const inWorkspace = await ((_this$workspace2 = this.workspace) === null || _this$workspace2 === void 0 ? void 0 : _this$workspace2.hasId(component.id)); // Support case when we have the dev server for the env, in that case we calc the data of the env as we can't rely on the env data from the scope
536
+ // since we bundle it for the dev server again
537
+
538
+ if (inWorkspace) {
539
+ const envComponent = await this.envs.getEnvComponent(component);
540
+ const envSupportScaling = await this.calculateIsEnvSupportScaling(envComponent);
541
+ return envSupportScaling !== null && envSupportScaling !== void 0 ? envSupportScaling : true;
542
+ }
543
+
544
+ const previewData = (_component$state$aspe = component.state.aspects.get(_preview().PreviewAspect.id)) === null || _component$state$aspe === void 0 ? void 0 : _component$state$aspe.data;
545
+ if (!previewData) return false; // Get the does scaling (the new calculation) or the old calc used in isScaling (between versions (about) 848 and 860)
505
546
 
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
547
+ if (previewData.doesScaling !== undefined) return previewData.doesScaling; // in case this component were tagged with versions between 848 and 860 we need to use the old calculation
548
+ // together with the env calculation
549
+ // In that case it means the component already tagged, so we take the env calc from the env data and not re-calc it
507
550
 
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;
551
+ if (previewData.isScaling) {
552
+ const envComponent = await this.envs.getEnvComponent(component);
553
+ const envSupportScaling = this.isEnvSupportScaling(envComponent);
554
+ return !!envSupportScaling;
555
+ }
556
+
557
+ return false;
509
558
  }
510
559
  /**
511
- * This function is calculate the isScaling flag for the component preview.
512
- * It should be only used during the component on load.
513
- * Once the component load, you should only use the `isScaling` to fetch it from the calculated data.
560
+ * Check if the current version of the env support scaling
561
+ * @param envComponent
562
+ * @returns
563
+ */
564
+
565
+
566
+ isEnvSupportScaling(envComponent) {
567
+ var _envComponent$state$a;
568
+
569
+ const previewData = (_envComponent$state$a = envComponent.state.aspects.get(_preview().PreviewAspect.id)) === null || _envComponent$state$a === void 0 ? void 0 : _envComponent$state$a.data;
570
+ return !!(previewData !== null && previewData !== void 0 && previewData.isScaling);
571
+ }
572
+ /**
573
+ * This function is calculate the isScaling support flag for the component preview.
574
+ * This is calculated only for the env component and not for the component itself.
575
+ * It should be only used during the (env) component on load.
576
+ * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.
577
+ * If you want to check if an env for a given component support scaling, use the `isScaling` function.
514
578
  * @param component
515
579
  * @returns
516
580
  */
517
581
 
518
582
 
519
- async calculateIsScaling(component) {
520
- var _env$env, _previewConfig$isScal;
583
+ async calculateIsEnvSupportScaling(envComponent) {
584
+ var _previewAspectConfig$;
585
+
586
+ const isEnv = this.envs.isEnv(envComponent); // If the component is not an env, we don't want to store anything in the data
521
587
 
522
- // It's important to use getOrCalculateEnv here and not just getEnv as it's running during on load
523
- // so the envs data is not on the component aspects yet.
524
- const env = this.envs.getOrCalculateEnv(component);
525
- const previewConfig = env === null || env === void 0 ? void 0 : (_env$env = env.env) === null || _env$env === void 0 ? void 0 : _env$env.getPreviewConfig(); // default to true if the env doesn't have a preview config
588
+ if (!isEnv) return undefined;
589
+ const previewAspectConfig = this.getPreviewConfig(envComponent); // default to true if the env doesn't have a preview config
526
590
 
527
- return (_previewConfig$isScal = previewConfig === null || previewConfig === void 0 ? void 0 : previewConfig.isScaling) !== null && _previewConfig$isScal !== void 0 ? _previewConfig$isScal : true;
591
+ return (_previewAspectConfig$ = previewAspectConfig === null || previewAspectConfig === void 0 ? void 0 : previewAspectConfig.isScaling) !== null && _previewAspectConfig$ !== void 0 ? _previewAspectConfig$ : true;
592
+ }
593
+ /**
594
+ * Get the preview config of the component.
595
+ * (config that was set by variants or on bitmap)
596
+ * @param component
597
+ * @returns
598
+ */
599
+
600
+
601
+ getPreviewConfig(component) {
602
+ var _component$state$aspe2;
603
+
604
+ return (_component$state$aspe2 = component.state.aspects.get(_preview().PreviewAspect.id)) === null || _component$state$aspe2 === void 0 ? void 0 : _component$state$aspe2.config;
528
605
  }
529
606
  /**
530
607
  * Check if the component preview bundle contain the header inside of it (legacy)
@@ -806,10 +883,17 @@ class PreviewMain {
806
883
  if (workspace) {
807
884
  workspace.registerOnComponentAdd(c => preview.handleComponentChange(c, currentComponents => currentComponents.add(c)));
808
885
  workspace.onComponentLoad(async component => {
809
- const isScaling = await preview.calculateIsScaling(component);
810
- return {
811
- isScaling
812
- };
886
+ const doesScaling = await preview.calcDoesScalingForComponent(component);
887
+ const isScaling = await preview.calculateIsEnvSupportScaling(component);
888
+ const data = {
889
+ doesScaling
890
+ }; // If there is no isScaling result at all, it's probably not an env. don't store any data.
891
+
892
+ if (isScaling !== undefined) {
893
+ data.isScaling = isScaling;
894
+ }
895
+
896
+ return data;
813
897
  });
814
898
  workspace.registerOnComponentChange(c => preview.handleComponentChange(c, currentComponents => currentComponents.update(c)));
815
899
  workspace.registerOnComponentRemove(cId => preview.handleComponentRemoval(cId));
@@ -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 // 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;EAAA;;EAAA;I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,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"}
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","calcDoesScalingForComponent","isUsingCoreEnv","isNew","envComponent","getEnvComponent","isEnvSupportScaling","doesScaling","inWorkspace","hasId","envSupportScaling","calculateIsEnvSupportScaling","previewData","state","aspects","isScaling","isEnv","previewAspectConfig","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","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 PreviewVariantConfig = {\n isScaling?: boolean;\n}\n\n/**\n * Preview data that stored on the component on load\n */\nexport type PreviewComponentData = {\n doesScaling?: boolean;\n isScaling?: boolean;\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\n // This used on component load to calc the final result of support is scaling for a given component\n // This calc based on the env, env data, env preview config and more\n // if you want to get the final result use the `doesScaling` method below\n // This should be used only for component load\n private async calcDoesScalingForComponent(component: Component): Promise<boolean> {\n const isBundledWithEnv = await this.isBundledWithEnv(component);\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 if (this.envs.isUsingCoreEnv(component)){\n // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)\n // If it's new, and we are here, it means that we already use a version of the env that support scaling\n const isNew = await component.isNew();\n if (isNew){\n return true;\n }\n return isBundledWithEnv === false\n }\n // For envs that bundled with the env return true always\n if (isBundledWithEnv){\n return true;\n }\n const envComponent = await this.envs.getEnvComponent(component);\n return this.isEnvSupportScaling(envComponent)\n }\n\n /**\n * can the current component preview scale in size for different preview sizes.\n * this calculation is based on the env of the component and if the env of the component support it.\n */\n async doesScaling(component: Component): Promise<boolean> {\n const inWorkspace = await this.workspace?.hasId(component.id);\n // Support case when we have the dev server for the env, in that case we calc the data of the env as we can't rely on the env data from the scope\n // since we bundle it for the dev server again\n if (inWorkspace) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = await this.calculateIsEnvSupportScaling(envComponent);\n return envSupportScaling ?? true;\n }\n const previewData = component.state.aspects.get(PreviewAspect.id)?.data;\n if (!previewData) return false;\n // Get the does scaling (the new calculation) or the old calc used in isScaling (between versions (about) 848 and 860)\n if (previewData.doesScaling !== undefined) return previewData.doesScaling;\n // in case this component were tagged with versions between 848 and 860 we need to use the old calculation\n // together with the env calculation\n // In that case it means the component already tagged, so we take the env calc from the env data and not re-calc it\n if (previewData.isScaling) {\n const envComponent = await this.envs.getEnvComponent(component);\n const envSupportScaling = this.isEnvSupportScaling(envComponent);\n return !!envSupportScaling;\n }\n return false;\n }\n\n /**\n * Check if the current version of the env support scaling\n * @param envComponent\n * @returns\n */\n isEnvSupportScaling(envComponent: Component): boolean {\n const previewData = envComponent.state.aspects.get(PreviewAspect.id)?.data;\n return (!!previewData?.isScaling);\n }\n\n /**\n * This function is calculate the isScaling support flag for the component preview.\n * This is calculated only for the env component and not for the component itself.\n * It should be only used during the (env) component on load.\n * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.\n * If you want to check if an env for a given component support scaling, use the `isScaling` function.\n * @param component\n * @returns\n */\n private async calculateIsEnvSupportScaling(envComponent: Component): Promise<boolean | undefined> {\n const isEnv = this.envs.isEnv(envComponent);\n // If the component is not an env, we don't want to store anything in the data\n if (!isEnv) return undefined;\n const previewAspectConfig = this.getPreviewConfig(envComponent);\n // default to true if the env doesn't have a preview config\n return previewAspectConfig?.isScaling ?? true;\n }\n\n /**\n * Get the preview config of the component.\n * (config that was set by variants or on bitmap)\n * @param component\n * @returns\n */\n getPreviewConfig(component: Component): PreviewVariantConfig | undefined {\n return component.state.aspects.get(PreviewAspect.id)?.config;\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 doesScaling = await preview.calcDoesScalingForComponent(component);\n const isScaling = await preview.calculateIsEnvSupportScaling(component);\n const data: PreviewComponentData = {\n doesScaling,\n }\n // If there is no isScaling result at all, it's probably not an env. don't store any data.\n if (isScaling !== undefined){\n data.isScaling = isScaling\n }\n return data;\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;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;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N,GAA/B,CAA7C;IACD;;IAED+L,OAAO,CAACR,QAAR,CAAiB,IAAAgC,yBAAA,EAActB,OAAd,CAAjB;IAEA,OAAOA,OAAP;EACD;;AA9mBsB;;;gCAAZ/N,W,WAsfI,CAACsP,eAAA,CAAKC,QAAL,EAAD,EAAqCD,eAAA,CAAKC,QAAL,EAArC,C;gCAtfJvP,W,aAwfMmL,kB;gCAxfNnL,W,kBAyfW,CACpBwP,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAzfXnQ,W,mBAwgBY;EACrB0O,QAAQ,EAAE;AADW,C;;AAyGzB5O,wBAAA,CAAcsQ,UAAd,CAAyBpQ,WAAzB"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "0.0.857",
3
+ "version": "0.0.859",
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.857"
9
+ "version": "0.0.859"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -23,29 +23,29 @@
23
23
  "@babel/runtime": "7.12.18",
24
24
  "core-js": "^3.0.0",
25
25
  "@teambit/harmony": "0.3.3",
26
- "@teambit/express": "0.0.667",
27
- "@teambit/logger": "0.0.662",
26
+ "@teambit/express": "0.0.669",
27
+ "@teambit/logger": "0.0.664",
28
28
  "@teambit/ui-foundation.ui.pages.static-error": "0.0.82",
29
- "@teambit/builder": "0.0.857",
30
- "@teambit/bundler": "0.0.857",
31
- "@teambit/component": "0.0.857",
29
+ "@teambit/builder": "0.0.859",
30
+ "@teambit/bundler": "0.0.859",
31
+ "@teambit/component": "0.0.859",
32
32
  "@teambit/preview.ui.component-preview": "0.0.503",
33
- "@teambit/aspect-loader": "0.0.857",
34
- "@teambit/cli": "0.0.569",
35
- "@teambit/dependency-resolver": "0.0.857",
36
- "@teambit/envs": "0.0.857",
33
+ "@teambit/aspect-loader": "0.0.859",
34
+ "@teambit/cli": "0.0.571",
35
+ "@teambit/dependency-resolver": "0.0.859",
36
+ "@teambit/envs": "0.0.859",
37
37
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.489",
38
38
  "@teambit/component-id": "0.0.417",
39
39
  "@teambit/bit-error": "0.0.400",
40
- "@teambit/graphql": "0.0.857",
41
- "@teambit/pkg": "0.0.857",
42
- "@teambit/pubsub": "0.0.857",
43
- "@teambit/ui": "0.0.857",
44
- "@teambit/workspace": "0.0.857",
45
- "@teambit/compiler": "0.0.857",
40
+ "@teambit/graphql": "0.0.859",
41
+ "@teambit/pkg": "0.0.859",
42
+ "@teambit/pubsub": "0.0.859",
43
+ "@teambit/ui": "0.0.859",
44
+ "@teambit/workspace": "0.0.859",
45
+ "@teambit/compiler": "0.0.859",
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.857"
48
+ "@teambit/isolator": "0.0.859"
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.350",
66
+ "@teambit/legacy": "1.0.351",
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.857/dist/preview.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.857/dist/preview.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.859/dist/preview.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.859/dist/preview.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -84,6 +84,18 @@ export type ComponentPreviewMetaData = {
84
84
  size?: ComponentPreviewSize;
85
85
  };
86
86
 
87
+ export type PreviewVariantConfig = {
88
+ isScaling?: boolean;
89
+ }
90
+
91
+ /**
92
+ * Preview data that stored on the component on load
93
+ */
94
+ export type PreviewComponentData = {
95
+ doesScaling?: boolean;
96
+ isScaling?: boolean;
97
+ }
98
+
87
99
  export type PreviewConfig = {
88
100
  bundlingStrategy?: string;
89
101
  disabled: boolean;
@@ -192,32 +204,96 @@ export class PreviewMain {
192
204
  return false;
193
205
  }
194
206
 
207
+
208
+
209
+ // This used on component load to calc the final result of support is scaling for a given component
210
+ // This calc based on the env, env data, env preview config and more
211
+ // if you want to get the final result use the `doesScaling` method below
212
+ // This should be used only for component load
213
+ private async calcDoesScalingForComponent(component: Component): Promise<boolean> {
214
+ const isBundledWithEnv = await this.isBundledWithEnv(component);
215
+ // 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
216
+ if (this.envs.isUsingCoreEnv(component)){
217
+ // If the component is new, no point to check the is bundle with env (there is no artifacts so it will for sure return false)
218
+ // If it's new, and we are here, it means that we already use a version of the env that support scaling
219
+ const isNew = await component.isNew();
220
+ if (isNew){
221
+ return true;
222
+ }
223
+ return isBundledWithEnv === false
224
+ }
225
+ // For envs that bundled with the env return true always
226
+ if (isBundledWithEnv){
227
+ return true;
228
+ }
229
+ const envComponent = await this.envs.getEnvComponent(component);
230
+ return this.isEnvSupportScaling(envComponent)
231
+ }
232
+
195
233
  /**
196
234
  * can the current component preview scale in size for different preview sizes.
235
+ * this calculation is based on the env of the component and if the env of the component support it.
197
236
  */
198
- async isScaling(component: Component): Promise<boolean> {
237
+ async doesScaling(component: Component): Promise<boolean> {
238
+ const inWorkspace = await this.workspace?.hasId(component.id);
239
+ // Support case when we have the dev server for the env, in that case we calc the data of the env as we can't rely on the env data from the scope
240
+ // since we bundle it for the dev server again
241
+ if (inWorkspace) {
242
+ const envComponent = await this.envs.getEnvComponent(component);
243
+ const envSupportScaling = await this.calculateIsEnvSupportScaling(envComponent);
244
+ return envSupportScaling ?? true;
245
+ }
199
246
  const previewData = component.state.aspects.get(PreviewAspect.id)?.data;
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
- );
247
+ if (!previewData) return false;
248
+ // Get the does scaling (the new calculation) or the old calc used in isScaling (between versions (about) 848 and 860)
249
+ if (previewData.doesScaling !== undefined) return previewData.doesScaling;
250
+ // in case this component were tagged with versions between 848 and 860 we need to use the old calculation
251
+ // together with the env calculation
252
+ // In that case it means the component already tagged, so we take the env calc from the env data and not re-calc it
253
+ if (previewData.isScaling) {
254
+ const envComponent = await this.envs.getEnvComponent(component);
255
+ const envSupportScaling = this.isEnvSupportScaling(envComponent);
256
+ return !!envSupportScaling;
257
+ }
258
+ return false;
259
+ }
260
+
261
+ /**
262
+ * Check if the current version of the env support scaling
263
+ * @param envComponent
264
+ * @returns
265
+ */
266
+ isEnvSupportScaling(envComponent: Component): boolean {
267
+ const previewData = envComponent.state.aspects.get(PreviewAspect.id)?.data;
268
+ return (!!previewData?.isScaling);
205
269
  }
206
270
 
207
271
  /**
208
- * This function is calculate the isScaling flag for the component preview.
209
- * It should be only used during the component on load.
210
- * Once the component load, you should only use the `isScaling` to fetch it from the calculated data.
272
+ * This function is calculate the isScaling support flag for the component preview.
273
+ * This is calculated only for the env component and not for the component itself.
274
+ * It should be only used during the (env) component on load.
275
+ * Once the component load, you should only use the `isEnvSupportScaling` to fetch it from the calculated data.
276
+ * If you want to check if an env for a given component support scaling, use the `isScaling` function.
211
277
  * @param component
212
278
  * @returns
213
279
  */
214
- private async calculateIsScaling(component: Component): Promise<boolean> {
215
- // It's important to use getOrCalculateEnv here and not just getEnv as it's running during on load
216
- // so the envs data is not on the component aspects yet.
217
- const env = this.envs.getOrCalculateEnv(component);
218
- const previewConfig = env?.env?.getPreviewConfig();
280
+ private async calculateIsEnvSupportScaling(envComponent: Component): Promise<boolean | undefined> {
281
+ const isEnv = this.envs.isEnv(envComponent);
282
+ // If the component is not an env, we don't want to store anything in the data
283
+ if (!isEnv) return undefined;
284
+ const previewAspectConfig = this.getPreviewConfig(envComponent);
219
285
  // default to true if the env doesn't have a preview config
220
- return previewConfig?.isScaling ?? true;
286
+ return previewAspectConfig?.isScaling ?? true;
287
+ }
288
+
289
+ /**
290
+ * Get the preview config of the component.
291
+ * (config that was set by variants or on bitmap)
292
+ * @param component
293
+ * @returns
294
+ */
295
+ getPreviewConfig(component: Component): PreviewVariantConfig | undefined {
296
+ return component.state.aspects.get(PreviewAspect.id)?.config;
221
297
  }
222
298
 
223
299
  /**
@@ -642,10 +718,16 @@ export class PreviewMain {
642
718
  preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))
643
719
  );
644
720
  workspace.onComponentLoad(async (component) => {
645
- const isScaling = await preview.calculateIsScaling(component);
646
- return {
647
- isScaling,
648
- };
721
+ const doesScaling = await preview.calcDoesScalingForComponent(component);
722
+ const isScaling = await preview.calculateIsEnvSupportScaling(component);
723
+ const data: PreviewComponentData = {
724
+ doesScaling,
725
+ }
726
+ // If there is no isScaling result at all, it's probably not an env. don't store any data.
727
+ if (isScaling !== undefined){
728
+ data.isScaling = isScaling
729
+ }
730
+ return data;
649
731
  });
650
732
  workspace.registerOnComponentChange((c) =>
651
733
  preview.handleComponentChange(c, (currentComponents) => currentComponents.update(c))