@teambit/preview 0.0.738 → 0.0.739
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.
- package/dist/env-preview-template.task.d.ts +5 -1
- package/dist/env-preview-template.task.js +16 -21
- package/dist/env-preview-template.task.js.map +1 -1
- package/dist/preview.main.runtime.js +2 -2
- package/dist/preview.main.runtime.js.map +1 -1
- package/dist/preview.task.d.ts +5 -1
- package/dist/preview.task.js +4 -3
- package/dist/preview.task.js.map +1 -1
- package/dist/strategies/component-strategy.d.ts +2 -6
- package/dist/strategies/component-strategy.js +8 -1
- package/dist/strategies/component-strategy.js.map +1 -1
- package/dist/strategies/env-strategy.d.ts +7 -1
- package/dist/strategies/env-strategy.js +10 -2
- package/dist/strategies/env-strategy.js.map +1 -1
- package/package-tar/teambit-preview-0.0.739.tgz +0 -0
- package/package.json +16 -16
- package/{preview-1653227849497.js → preview-1653362849981.js} +2 -2
- package/preview.main.runtime.tsx +6 -3
- package/strategies/component-strategy.ts +9 -2
- package/strategies/env-strategy.ts +8 -1
- package/package-tar/teambit-preview-0.0.738.tgz +0 -0
|
@@ -3,6 +3,8 @@ import { AspectLoaderMain } from '@teambit/aspect-loader';
|
|
|
3
3
|
import { Capsule } from '@teambit/isolator';
|
|
4
4
|
import { BundlerContext, BundlerEntryMap, BundlerResult } from '@teambit/bundler';
|
|
5
5
|
import type { EnvDefinition, EnvsMain } from '@teambit/envs';
|
|
6
|
+
import { Logger } from '@teambit/logger';
|
|
7
|
+
import { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
6
8
|
import type { PreviewMain } from './preview.main.runtime';
|
|
7
9
|
export declare type ModuleExpose = {
|
|
8
10
|
name: string;
|
|
@@ -16,10 +18,12 @@ export declare class EnvPreviewTemplateTask implements BuildTask {
|
|
|
16
18
|
private preview;
|
|
17
19
|
private envs;
|
|
18
20
|
private aspectLoader;
|
|
21
|
+
private dependencyResolver;
|
|
22
|
+
private logger;
|
|
19
23
|
aspectId: string;
|
|
20
24
|
name: string;
|
|
21
25
|
location: TaskLocation;
|
|
22
|
-
constructor(preview: PreviewMain, envs: EnvsMain, aspectLoader: AspectLoaderMain);
|
|
26
|
+
constructor(preview: PreviewMain, envs: EnvsMain, aspectLoader: AspectLoaderMain, dependencyResolver: DependencyResolverMain, logger: Logger);
|
|
23
27
|
execute(context: BuildContext): Promise<BuiltTaskResult>;
|
|
24
28
|
private runBundlerForGroups;
|
|
25
29
|
private shouldUseDefaultBundler;
|
|
@@ -102,10 +102,12 @@ exports.PEERS_CHUNK_NAME = PEERS_CHUNK_NAME;
|
|
|
102
102
|
|
|
103
103
|
class EnvPreviewTemplateTask {
|
|
104
104
|
// readonly dependencies = [CompilerAspect.id];
|
|
105
|
-
constructor(preview, envs, aspectLoader) {
|
|
105
|
+
constructor(preview, envs, aspectLoader, dependencyResolver, logger) {
|
|
106
106
|
this.preview = preview;
|
|
107
107
|
this.envs = envs;
|
|
108
108
|
this.aspectLoader = aspectLoader;
|
|
109
|
+
this.dependencyResolver = dependencyResolver;
|
|
110
|
+
this.logger = logger;
|
|
109
111
|
(0, _defineProperty2().default)(this, "aspectId", 'teambit.preview/preview');
|
|
110
112
|
(0, _defineProperty2().default)(this, "name", GENERATE_ENV_TEMPLATE_TASK_NAME);
|
|
111
113
|
(0, _defineProperty2().default)(this, "location", 'end');
|
|
@@ -146,7 +148,8 @@ class EnvPreviewTemplateTask {
|
|
|
146
148
|
|
|
147
149
|
if (!grouped[groupEnvId]) {
|
|
148
150
|
grouped[groupEnvId] = {
|
|
149
|
-
env
|
|
151
|
+
env,
|
|
152
|
+
envToGetBundler,
|
|
150
153
|
targets: [target]
|
|
151
154
|
};
|
|
152
155
|
} else {
|
|
@@ -169,7 +172,6 @@ class EnvPreviewTemplateTask {
|
|
|
169
172
|
const bundlerContext = Object.assign(context, {
|
|
170
173
|
targets: [],
|
|
171
174
|
entry: [],
|
|
172
|
-
externalizePeer: false,
|
|
173
175
|
development: context.dev,
|
|
174
176
|
metaData: {
|
|
175
177
|
initiator: `${GENERATE_ENV_TEMPLATE_TASK_NAME} task`,
|
|
@@ -178,7 +180,7 @@ class EnvPreviewTemplateTask {
|
|
|
178
180
|
});
|
|
179
181
|
const bundlerResults = await (0, _pMapSeries().default)(Object.entries(groups), async ([, targetsGroup]) => {
|
|
180
182
|
bundlerContext.targets = targetsGroup.targets;
|
|
181
|
-
const bundler = await targetsGroup.
|
|
183
|
+
const bundler = await targetsGroup.envToGetBundler.getTemplateBundler(bundlerContext);
|
|
182
184
|
const bundlerResult = await bundler.run();
|
|
183
185
|
return bundlerResult;
|
|
184
186
|
});
|
|
@@ -187,7 +189,7 @@ class EnvPreviewTemplateTask {
|
|
|
187
189
|
}
|
|
188
190
|
|
|
189
191
|
shouldUseDefaultBundler(envDef) {
|
|
190
|
-
if (this.aspectLoader.isCoreEnv(envDef.id)) return true;
|
|
192
|
+
if (this.aspectLoader.isCoreEnv(envDef.id) && envDef.id !== 'teambit.react/react-native') return true;
|
|
191
193
|
const env = envDef.env;
|
|
192
194
|
if (env.getTemplateBundler && typeof env.getTemplateBundler === 'function') return false;
|
|
193
195
|
return true;
|
|
@@ -199,23 +201,10 @@ class EnvPreviewTemplateTask {
|
|
|
199
201
|
const env = envDef.env;
|
|
200
202
|
const envPreviewConfig = this.preview.getEnvPreviewConfig(envDef.env);
|
|
201
203
|
const isSplitComponentBundle = (_envPreviewConfig$spl = envPreviewConfig.splitComponentBundle) !== null && _envPreviewConfig$spl !== void 0 ? _envPreviewConfig$spl : false;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (env.getHostDependencies && typeof env.getHostDependencies === 'function') {
|
|
205
|
-
peers = (await env.getHostDependencies()) || [];
|
|
206
|
-
} else {
|
|
207
|
-
const envComponentPeers = Object.keys((await env.getDependencies()).peerDependencies || {}) || [];
|
|
208
|
-
let additionalHostDeps = [];
|
|
209
|
-
|
|
210
|
-
if (env.getAdditionalHostDependencies && typeof env.getAdditionalHostDependencies === 'function') {
|
|
211
|
-
additionalHostDeps = await env.getAdditionalHostDependencies();
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
peers = envComponentPeers.concat(additionalHostDeps);
|
|
215
|
-
} // const module = await this.getPreviewModule(envComponent);
|
|
204
|
+
const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(env); // console.log('envid22', env.__getDescriptor(), 'peers', peers)
|
|
205
|
+
// const module = await this.getPreviewModule(envComponent);
|
|
216
206
|
// const entries = Object.keys(module).map((key) => module.exposes[key]);
|
|
217
207
|
|
|
218
|
-
|
|
219
208
|
const capsule = context.capsuleNetwork.graphCapsules.getCapsule(envComponent.id);
|
|
220
209
|
if (!capsule) throw new Error('no capsule found'); // Passing here the env itself to make sure it's preview runtime will be part of the preview root file
|
|
221
210
|
// that's needed to make sure the providers register there are running correctly
|
|
@@ -237,7 +226,13 @@ class EnvPreviewTemplateTask {
|
|
|
237
226
|
splitChunks: true
|
|
238
227
|
},
|
|
239
228
|
components: [envComponent],
|
|
240
|
-
outputPath
|
|
229
|
+
outputPath,
|
|
230
|
+
|
|
231
|
+
/* It's a path to the root of the host component. */
|
|
232
|
+
// hostRootDir, handle this
|
|
233
|
+
hostDependencies: peers,
|
|
234
|
+
aliasHostDependencies: true,
|
|
235
|
+
exposeHostDependencies: true
|
|
241
236
|
};
|
|
242
237
|
}
|
|
243
238
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["GENERATE_ENV_TEMPLATE_TASK_NAME","PREVIEW_ROOT_CHUNK_NAME","PEERS_CHUNK_NAME","EnvPreviewTemplateTask","constructor","preview","envs","aspectLoader","execute","context","previewDefs","getDefs","htmlConfig","generateHtmlConfig","dev","originalSeedersIds","capsuleNetwork","originalSeedersCapsules","map","c","component","id","toString","grouped","Promise","all","components","length","includes","undefined","envDef","getEnvFromComponent","env","bundlingStrategy","getBundlingStrategy","name","target","getEnvTargetFromComponent","shouldUseDefaultBundler","envToGetBundler","getEnvsEnvDefinition","groupEnvId","targets","push","isEmpty","componentsResults","runBundlerForGroups","groups","bundlerContext","Object","assign","entry","externalizePeer","development","metaData","initiator","envId","bundlerResults","mapSeries","entries","targetsGroup","bundler","getTemplateBundler","bundlerResult","run","results","computeResults","flatten","isCoreEnv","envComponent","envPreviewConfig","getEnvPreviewConfig","isSplitComponentBundle","splitComponentBundle","peers","getHostDependencies","envComponentPeers","keys","getDependencies","peerDependencies","additionalHostDeps","getAdditionalHostDependencies","concat","capsule","graphCapsules","getCapsule","Error","previewRoot","writePreviewRuntime","previewModules","getPreviewModules","outputPath","computeOutputPath","existsSync","mkdirpSync","getEntries","runtimeChunkName","html","chunking","splitChunks","previewRootChunkName","peersChunkName","options","htmlConfigs","previewModule","generateHtmlConfigForPreviewDef","previewDef","previewDeps","include","chunks","prefix","includePeers","unshift","config","title","templateContent","minify","filename","previewRootEntry","import","peersRootEntry","reduce","acc","module","linkFile","writeLink","ComponentMap","create","path","dependOn","allResults","result","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","modules","compact","def","renderTemplatePathByEnv","join","getArtifactDirectory","CAPSULE_ARTIFACTS_DIR","globPatterns","rootDir"],"sources":["env-preview-template.task.ts"],"sourcesContent":["import {\n BuildContext,\n BuiltTaskResult,\n BuildTask,\n TaskLocation,\n ComponentResult,\n CAPSULE_ARTIFACTS_DIR,\n} from '@teambit/builder';\nimport mapSeries from 'p-map-series';\nimport { Component, ComponentMap } from '@teambit/component';\nimport { AspectLoaderMain } from '@teambit/aspect-loader';\nimport { Capsule } from '@teambit/isolator';\nimport { Bundler, BundlerContext, BundlerEntryMap, BundlerHtmlConfig, BundlerResult, Target } from '@teambit/bundler';\nimport type { EnvDefinition, Environment, EnvsMain } from '@teambit/envs';\nimport { join } from 'path';\nimport { compact, flatten, isEmpty } from 'lodash';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport type { PreviewMain } from './preview.main.runtime';\nimport { PreviewDefinition } from '.';\nimport { html } from './webpack';\n\nexport type ModuleExpose = {\n name: string;\n path: string;\n include?: string[];\n};\n\ntype TargetsGroup = {\n env: Environment;\n targets: Target[];\n};\ntype TargetsGroupMap = {\n [envId: string]: TargetsGroup;\n};\n\nexport const GENERATE_ENV_TEMPLATE_TASK_NAME = 'GenerateEnvTemplate';\nexport const PREVIEW_ROOT_CHUNK_NAME = 'previewRoot';\nexport const PEERS_CHUNK_NAME = 'peers';\n\nexport class EnvPreviewTemplateTask implements BuildTask {\n aspectId = 'teambit.preview/preview';\n name = GENERATE_ENV_TEMPLATE_TASK_NAME;\n location: TaskLocation = 'end';\n // readonly dependencies = [CompilerAspect.id];\n\n constructor(private preview: PreviewMain, private envs: EnvsMain, private aspectLoader: AspectLoaderMain) {}\n\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n const previewDefs = this.preview.getDefs();\n const htmlConfig = this.generateHtmlConfig(previewDefs, PREVIEW_ROOT_CHUNK_NAME, PEERS_CHUNK_NAME, {\n dev: context.dev,\n });\n const originalSeedersIds = context.capsuleNetwork.originalSeedersCapsules.map((c) => c.component.id.toString());\n const grouped: TargetsGroupMap = {};\n await Promise.all(\n context.components.map(async (component) => {\n // Do not run over other components in the graph. it make the process much longer with no need\n if (originalSeedersIds && originalSeedersIds.length && !originalSeedersIds.includes(component.id.toString())) {\n return undefined;\n }\n const envDef = this.envs.getEnvFromComponent(component);\n if (!envDef) return undefined;\n const env = envDef.env;\n const bundlingStrategy = this.preview.getBundlingStrategy(envDef.env);\n if (bundlingStrategy.name === 'env') {\n return undefined;\n }\n const target = await this.getEnvTargetFromComponent(context, component, envDef, htmlConfig);\n if (!target) return undefined;\n const shouldUseDefaultBundler = this.shouldUseDefaultBundler(envDef);\n let envToGetBundler = this.envs.getEnvsEnvDefinition().env;\n let groupEnvId = 'default';\n if (!shouldUseDefaultBundler) {\n envToGetBundler = env;\n groupEnvId = envDef.id;\n }\n if (!grouped[groupEnvId]) {\n grouped[groupEnvId] = {\n env: envToGetBundler,\n targets: [target],\n };\n } else {\n grouped[groupEnvId].targets.push(target);\n }\n return undefined;\n })\n );\n if (isEmpty(grouped)) {\n return { componentsResults: [] };\n }\n\n return this.runBundlerForGroups(context, grouped);\n }\n\n private async runBundlerForGroups(context: BuildContext, groups: TargetsGroupMap): Promise<BuiltTaskResult> {\n const bundlerContext: BundlerContext = Object.assign(context, {\n targets: [],\n entry: [],\n externalizePeer: false,\n development: context.dev,\n metaData: {\n initiator: `${GENERATE_ENV_TEMPLATE_TASK_NAME} task`,\n envId: context.id,\n },\n });\n const bundlerResults = await mapSeries(Object.entries(groups), async ([, targetsGroup]) => {\n bundlerContext.targets = targetsGroup.targets;\n const bundler: Bundler = await targetsGroup.env.getTemplateBundler(bundlerContext);\n const bundlerResult = await bundler.run();\n return bundlerResult;\n });\n\n const results = await this.computeResults(bundlerContext, flatten(bundlerResults));\n return results;\n }\n\n private shouldUseDefaultBundler(envDef: EnvDefinition): boolean {\n if (this.aspectLoader.isCoreEnv(envDef.id)) return true;\n const env = envDef.env;\n if (env.getTemplateBundler && typeof env.getTemplateBundler === 'function') return false;\n return true;\n }\n\n private async getEnvTargetFromComponent(\n context: BuildContext,\n envComponent: Component,\n envDef: EnvDefinition,\n htmlConfig: BundlerHtmlConfig[]\n ): Promise<Target | undefined> {\n const env = envDef.env;\n const envPreviewConfig = this.preview.getEnvPreviewConfig(envDef.env);\n const isSplitComponentBundle = envPreviewConfig.splitComponentBundle ?? false;\n let peers;\n if (env.getHostDependencies && typeof env.getHostDependencies === 'function') {\n peers = (await env.getHostDependencies()) || [];\n } else {\n const envComponentPeers = Object.keys((await env.getDependencies()).peerDependencies || {}) || [];\n let additionalHostDeps = [];\n if (env.getAdditionalHostDependencies && typeof env.getAdditionalHostDependencies === 'function') {\n additionalHostDeps = await env.getAdditionalHostDependencies();\n }\n peers = envComponentPeers.concat(additionalHostDeps);\n }\n\n // const module = await this.getPreviewModule(envComponent);\n // const entries = Object.keys(module).map((key) => module.exposes[key]);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(envComponent.id);\n if (!capsule) throw new Error('no capsule found');\n // Passing here the env itself to make sure it's preview runtime will be part of the preview root file\n // that's needed to make sure the providers register there are running correctly\n const previewRoot = await this.preview.writePreviewRuntime(context, [envComponent.id.toString()]);\n const previewModules = await this.getPreviewModules(envDef);\n // const templatesFile = previewModules.map((template) => {\n // return this.preview.writeLink(template.name, ComponentMap.create([]), template.path, capsule.path);\n // });\n const outputPath = this.computeOutputPath(context, envComponent);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const entries = this.getEntries(previewModules, capsule, previewRoot, isSplitComponentBundle, peers);\n\n return {\n peers,\n runtimeChunkName: 'runtime',\n html: htmlConfig,\n entries,\n chunking: {\n splitChunks: true,\n },\n components: [envComponent],\n outputPath,\n };\n }\n\n private generateHtmlConfig(\n previewDefs: PreviewDefinition[],\n previewRootChunkName: string,\n peersChunkName: string,\n options: { dev?: boolean }\n ): BundlerHtmlConfig[] {\n const htmlConfigs = previewDefs.map((previewModule) =>\n this.generateHtmlConfigForPreviewDef(previewModule, previewRootChunkName, peersChunkName, options)\n );\n return htmlConfigs;\n }\n\n private generateHtmlConfigForPreviewDef(\n previewDef: PreviewDefinition,\n previewRootChunkName: string,\n peersChunkName: string,\n options: { dev?: boolean }\n ): BundlerHtmlConfig {\n const previewDeps = previewDef.include || [];\n const chunks = [...previewDeps, previewDef.prefix, previewRootChunkName];\n if (previewDef.includePeers) {\n chunks.unshift(peersChunkName);\n }\n\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n minify: options?.dev ?? true,\n chunks,\n filename: `${previewDef.prefix}.html`,\n };\n return config;\n }\n\n getEntries(\n previewModules: ModuleExpose[],\n capsule: Capsule,\n previewRoot: string,\n isSplitComponentBundle = false,\n peers: string[] = []\n ): BundlerEntryMap {\n const previewRootEntry = {\n filename: 'preview-root.[chunkhash].js',\n import: previewRoot,\n };\n\n const peersRootEntry = {\n filename: 'peers.[chunkhash].js',\n import: peers,\n };\n\n const entries = previewModules.reduce(\n (acc, module) => {\n const linkFile = this.preview.writeLink(\n module.name,\n ComponentMap.create([]),\n module.path,\n capsule.path,\n isSplitComponentBundle\n );\n acc[module.name] = {\n // filename: `${module.name}.[contenthash].js`,\n filename: `${module.name}.[chunkhash].js`,\n // filename: `${module.name}.js`,\n import: linkFile,\n // library: {\n // name: module.name,\n // type: 'umd',\n // },\n };\n if (module.include) {\n acc[module.name].dependOn = module.include;\n }\n return acc;\n },\n { [PREVIEW_ROOT_CHUNK_NAME]: previewRootEntry, [PEERS_CHUNK_NAME]: peersRootEntry }\n );\n\n return entries;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const allResults = results.map((result) => {\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n return componentsResults;\n });\n\n const componentsResults = flatten(allResults);\n\n const artifacts = getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async getPreviewModules(envDef: EnvDefinition): Promise<ModuleExpose[]> {\n const previewDefs = this.preview.getDefs();\n\n const modules = compact(\n await Promise.all(\n previewDefs.map(async (def) => {\n if (!def.renderTemplatePathByEnv) return undefined;\n return {\n name: def.prefix,\n path: await def.renderTemplatePathByEnv(envDef.env),\n include: def.include,\n };\n })\n )\n );\n\n return modules;\n }\n\n private computeOutputPath(context: BuildContext, component: Component) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) throw new Error('no capsule found');\n return join(capsule.path, getArtifactDirectory());\n }\n}\n\nexport function getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'env-template');\n}\n\nexport function getArtifactDef() {\n return [\n {\n name: 'env-template',\n globPatterns: ['**'],\n rootDir: getArtifactDirectory(),\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAQA;EAAA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AACA,GAAG,CAACC,uBAAT,EAAkC,OAAOnH,SAAP;MAClC,OAAO;QACLM,IAAI,EAAE4G,GAAG,CAACjC,MADL;QAELkB,IAAI,EAAE,MAAMe,GAAG,CAACC,uBAAJ,CAA4BlH,MAAM,CAACE,GAAnC,CAFP;QAGL4E,OAAO,EAAEmC,GAAG,CAACnC;MAHR,CAAP;IAKD,CAPD,CADI,CADQ,CAAhB;IAaA,OAAOiC,OAAP;EACD;;EAEOjD,iBAAiB,CAACnF,OAAD,EAAwBW,SAAxB,EAA8C;IACrE,MAAM+D,OAAO,GAAG1E,OAAO,CAACO,cAAR,CAAuBoE,aAAvB,CAAqCC,UAArC,CAAgDjE,SAAS,CAACC,EAA1D,CAAhB;IACA,IAAI,CAAC8D,OAAL,EAAc,MAAM,IAAIG,KAAJ,CAAU,kBAAV,CAAN;IACd,OAAO,IAAA2D,YAAA,EAAK9D,OAAO,CAAC6C,IAAb,EAAmBkB,oBAAoB,EAAvC,CAAP;EACD;;AArQsD;;;;AAwQlD,SAASA,oBAAT,GAAgC;EACrC,OAAO,IAAAD,YAAA,EAAKE,gCAAL,EAA4B,cAA5B,CAAP;AACD;;AAEM,SAASP,cAAT,GAA0B;EAC/B,OAAO,CACL;IACEzG,IAAI,EAAE,cADR;IAEEiH,YAAY,EAAE,CAAC,IAAD,CAFhB;IAGEC,OAAO,EAAEH,oBAAoB;EAH/B,CADK,CAAP;AAOD"}
|
|
1
|
+
{"version":3,"names":["GENERATE_ENV_TEMPLATE_TASK_NAME","PREVIEW_ROOT_CHUNK_NAME","PEERS_CHUNK_NAME","EnvPreviewTemplateTask","constructor","preview","envs","aspectLoader","dependencyResolver","logger","execute","context","previewDefs","getDefs","htmlConfig","generateHtmlConfig","dev","originalSeedersIds","capsuleNetwork","originalSeedersCapsules","map","c","component","id","toString","grouped","Promise","all","components","length","includes","undefined","envDef","getEnvFromComponent","env","bundlingStrategy","getBundlingStrategy","name","target","getEnvTargetFromComponent","shouldUseDefaultBundler","envToGetBundler","getEnvsEnvDefinition","groupEnvId","targets","push","isEmpty","componentsResults","runBundlerForGroups","groups","bundlerContext","Object","assign","entry","development","metaData","initiator","envId","bundlerResults","mapSeries","entries","targetsGroup","bundler","getTemplateBundler","bundlerResult","run","results","computeResults","flatten","isCoreEnv","envComponent","envPreviewConfig","getEnvPreviewConfig","isSplitComponentBundle","splitComponentBundle","peers","getPeerDependenciesListFromEnv","capsule","graphCapsules","getCapsule","Error","previewRoot","writePreviewRuntime","previewModules","getPreviewModules","outputPath","computeOutputPath","existsSync","mkdirpSync","getEntries","runtimeChunkName","html","chunking","splitChunks","hostDependencies","aliasHostDependencies","exposeHostDependencies","previewRootChunkName","peersChunkName","options","htmlConfigs","previewModule","generateHtmlConfigForPreviewDef","previewDef","previewDeps","include","chunks","prefix","includePeers","unshift","config","title","templateContent","minify","filename","previewRootEntry","import","peersRootEntry","reduce","acc","module","linkFile","writeLink","ComponentMap","create","path","dependOn","allResults","result","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","modules","compact","def","renderTemplatePathByEnv","join","getArtifactDirectory","CAPSULE_ARTIFACTS_DIR","globPatterns","rootDir"],"sources":["env-preview-template.task.ts"],"sourcesContent":["import {\n BuildContext,\n BuiltTaskResult,\n BuildTask,\n TaskLocation,\n ComponentResult,\n CAPSULE_ARTIFACTS_DIR,\n} from '@teambit/builder';\nimport mapSeries from 'p-map-series';\nimport { Component, ComponentMap } from '@teambit/component';\nimport { AspectLoaderMain } from '@teambit/aspect-loader';\nimport { Capsule } from '@teambit/isolator';\nimport { Bundler, BundlerContext, BundlerEntryMap, BundlerHtmlConfig, BundlerResult, Target } from '@teambit/bundler';\nimport type { EnvDefinition, Environment, EnvsMain } from '@teambit/envs';\nimport { join } from 'path';\nimport { compact, flatten, isEmpty } from 'lodash';\nimport { Logger } from '@teambit/logger';\nimport { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport type { PreviewMain } from './preview.main.runtime';\nimport { PreviewDefinition } from '.';\nimport { html } from './webpack';\n\nexport type ModuleExpose = {\n name: string;\n path: string;\n include?: string[];\n};\n\ntype TargetsGroup = {\n env: Environment;\n envToGetBundler: Environment;\n targets: Target[];\n};\ntype TargetsGroupMap = {\n [envId: string]: TargetsGroup;\n};\n\nexport const GENERATE_ENV_TEMPLATE_TASK_NAME = 'GenerateEnvTemplate';\nexport const PREVIEW_ROOT_CHUNK_NAME = 'previewRoot';\nexport const PEERS_CHUNK_NAME = 'peers';\n\nexport class EnvPreviewTemplateTask implements BuildTask {\n aspectId = 'teambit.preview/preview';\n name = GENERATE_ENV_TEMPLATE_TASK_NAME;\n location: TaskLocation = 'end';\n // readonly dependencies = [CompilerAspect.id];\n\n constructor(\n private preview: PreviewMain,\n private envs: EnvsMain,\n private aspectLoader: AspectLoaderMain,\n private dependencyResolver: DependencyResolverMain,\n private logger: Logger\n ) {}\n\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n const previewDefs = this.preview.getDefs();\n const htmlConfig = this.generateHtmlConfig(previewDefs, PREVIEW_ROOT_CHUNK_NAME, PEERS_CHUNK_NAME, {\n dev: context.dev,\n });\n const originalSeedersIds = context.capsuleNetwork.originalSeedersCapsules.map((c) => c.component.id.toString());\n const grouped: TargetsGroupMap = {};\n await Promise.all(\n context.components.map(async (component) => {\n // Do not run over other components in the graph. it make the process much longer with no need\n if (originalSeedersIds && originalSeedersIds.length && !originalSeedersIds.includes(component.id.toString())) {\n return undefined;\n }\n const envDef = this.envs.getEnvFromComponent(component);\n if (!envDef) return undefined;\n const env = envDef.env;\n const bundlingStrategy = this.preview.getBundlingStrategy(envDef.env);\n if (bundlingStrategy.name === 'env') {\n return undefined;\n }\n const target = await this.getEnvTargetFromComponent(context, component, envDef, htmlConfig);\n if (!target) return undefined;\n const shouldUseDefaultBundler = this.shouldUseDefaultBundler(envDef);\n let envToGetBundler = this.envs.getEnvsEnvDefinition().env;\n let groupEnvId = 'default';\n if (!shouldUseDefaultBundler) {\n envToGetBundler = env;\n groupEnvId = envDef.id;\n }\n if (!grouped[groupEnvId]) {\n grouped[groupEnvId] = {\n env,\n envToGetBundler,\n targets: [target],\n };\n } else {\n grouped[groupEnvId].targets.push(target);\n }\n return undefined;\n })\n );\n if (isEmpty(grouped)) {\n return { componentsResults: [] };\n }\n\n return this.runBundlerForGroups(context, grouped);\n }\n\n private async runBundlerForGroups(context: BuildContext, groups: TargetsGroupMap): Promise<BuiltTaskResult> {\n const bundlerContext: BundlerContext = Object.assign(context, {\n targets: [],\n entry: [],\n development: context.dev,\n metaData: {\n initiator: `${GENERATE_ENV_TEMPLATE_TASK_NAME} task`,\n envId: context.id,\n },\n });\n const bundlerResults = await mapSeries(Object.entries(groups), async ([, targetsGroup]) => {\n bundlerContext.targets = targetsGroup.targets;\n const bundler: Bundler = await targetsGroup.envToGetBundler.getTemplateBundler(bundlerContext);\n const bundlerResult = await bundler.run();\n return bundlerResult;\n });\n\n const results = await this.computeResults(bundlerContext, flatten(bundlerResults));\n return results;\n }\n\n private shouldUseDefaultBundler(envDef: EnvDefinition): boolean {\n if (this.aspectLoader.isCoreEnv(envDef.id) && envDef.id !== 'teambit.react/react-native') return true;\n const env = envDef.env;\n if (env.getTemplateBundler && typeof env.getTemplateBundler === 'function') return false;\n return true;\n }\n\n private async getEnvTargetFromComponent(\n context: BuildContext,\n envComponent: Component,\n envDef: EnvDefinition,\n htmlConfig: BundlerHtmlConfig[]\n ): Promise<Target | undefined> {\n const env = envDef.env;\n const envPreviewConfig = this.preview.getEnvPreviewConfig(envDef.env);\n const isSplitComponentBundle = envPreviewConfig.splitComponentBundle ?? false;\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(env);\n // console.log('envid22', env.__getDescriptor(), 'peers', peers)\n\n // const module = await this.getPreviewModule(envComponent);\n // const entries = Object.keys(module).map((key) => module.exposes[key]);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(envComponent.id);\n if (!capsule) throw new Error('no capsule found');\n // Passing here the env itself to make sure it's preview runtime will be part of the preview root file\n // that's needed to make sure the providers register there are running correctly\n const previewRoot = await this.preview.writePreviewRuntime(context, [envComponent.id.toString()]);\n const previewModules = await this.getPreviewModules(envDef);\n // const templatesFile = previewModules.map((template) => {\n // return this.preview.writeLink(template.name, ComponentMap.create([]), template.path, capsule.path);\n // });\n const outputPath = this.computeOutputPath(context, envComponent);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const entries = this.getEntries(previewModules, capsule, previewRoot, isSplitComponentBundle, peers);\n\n return {\n peers,\n runtimeChunkName: 'runtime',\n html: htmlConfig,\n entries,\n chunking: {\n splitChunks: true,\n },\n components: [envComponent],\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n exposeHostDependencies: true,\n };\n }\n\n private generateHtmlConfig(\n previewDefs: PreviewDefinition[],\n previewRootChunkName: string,\n peersChunkName: string,\n options: { dev?: boolean }\n ): BundlerHtmlConfig[] {\n const htmlConfigs = previewDefs.map((previewModule) =>\n this.generateHtmlConfigForPreviewDef(previewModule, previewRootChunkName, peersChunkName, options)\n );\n return htmlConfigs;\n }\n\n private generateHtmlConfigForPreviewDef(\n previewDef: PreviewDefinition,\n previewRootChunkName: string,\n peersChunkName: string,\n options: { dev?: boolean }\n ): BundlerHtmlConfig {\n const previewDeps = previewDef.include || [];\n const chunks = [...previewDeps, previewDef.prefix, previewRootChunkName];\n if (previewDef.includePeers) {\n chunks.unshift(peersChunkName);\n }\n\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n minify: options?.dev ?? true,\n chunks,\n filename: `${previewDef.prefix}.html`,\n };\n return config;\n }\n\n getEntries(\n previewModules: ModuleExpose[],\n capsule: Capsule,\n previewRoot: string,\n isSplitComponentBundle = false,\n peers: string[] = []\n ): BundlerEntryMap {\n const previewRootEntry = {\n filename: 'preview-root.[chunkhash].js',\n import: previewRoot,\n };\n\n const peersRootEntry = {\n filename: 'peers.[chunkhash].js',\n import: peers,\n };\n\n const entries = previewModules.reduce(\n (acc, module) => {\n const linkFile = this.preview.writeLink(\n module.name,\n ComponentMap.create([]),\n module.path,\n capsule.path,\n isSplitComponentBundle\n );\n acc[module.name] = {\n // filename: `${module.name}.[contenthash].js`,\n filename: `${module.name}.[chunkhash].js`,\n // filename: `${module.name}.js`,\n import: linkFile,\n // library: {\n // name: module.name,\n // type: 'umd',\n // },\n };\n if (module.include) {\n acc[module.name].dependOn = module.include;\n }\n return acc;\n },\n { [PREVIEW_ROOT_CHUNK_NAME]: previewRootEntry, [PEERS_CHUNK_NAME]: peersRootEntry }\n );\n\n return entries;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const allResults = results.map((result) => {\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n return componentsResults;\n });\n\n const componentsResults = flatten(allResults);\n\n const artifacts = getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async getPreviewModules(envDef: EnvDefinition): Promise<ModuleExpose[]> {\n const previewDefs = this.preview.getDefs();\n\n const modules = compact(\n await Promise.all(\n previewDefs.map(async (def) => {\n if (!def.renderTemplatePathByEnv) return undefined;\n return {\n name: def.prefix,\n path: await def.renderTemplatePathByEnv(envDef.env),\n include: def.include,\n };\n })\n )\n );\n\n return modules;\n }\n\n private computeOutputPath(context: BuildContext, component: Component) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) throw new Error('no capsule found');\n return join(capsule.path, getArtifactDirectory());\n }\n}\n\nexport function getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'env-template');\n}\n\nexport function getArtifactDef() {\n return [\n {\n name: 'env-template',\n globPatterns: ['**'],\n rootDir: getArtifactDirectory(),\n },\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA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D,EAAwBW,SAAxB,EAA8C;IACrE,MAAMuD,OAAO,GAAGlE,OAAO,CAACO,cAAR,CAAuB4D,aAAvB,CAAqCC,UAArC,CAAgDzD,SAAS,CAACC,EAA1D,CAAhB;IACA,IAAI,CAACsD,OAAL,EAAc,MAAM,IAAIG,KAAJ,CAAU,kBAAV,CAAN;IACd,OAAO,IAAA8D,YAAA,EAAKjE,OAAO,CAACgD,IAAb,EAAmBkB,oBAAoB,EAAvC,CAAP;EACD;;AAvQsD;;;;AA0QlD,SAASA,oBAAT,GAAgC;EACrC,OAAO,IAAAD,YAAA,EAAKE,gCAAL,EAA4B,cAA5B,CAAP;AACD;;AAEM,SAASP,cAAT,GAA0B;EAC/B,OAAO,CACL;IACEpG,IAAI,EAAE,cADR;IAEE4G,YAAY,EAAE,CAAC,IAAD,CAFhB;IAGEC,OAAO,EAAEH,oBAAoB;EAH/B,CADK,CAAP;AAOD"}
|
|
@@ -679,7 +679,7 @@ class PreviewMain {
|
|
|
679
679
|
}
|
|
680
680
|
|
|
681
681
|
getDefaultStrategies() {
|
|
682
|
-
return [new (_strategies().EnvBundlingStrategy)(this), new (_strategies().ComponentBundlingStrategy)(this, this.pkg, this.dependencyResolver)];
|
|
682
|
+
return [new (_strategies().EnvBundlingStrategy)(this, this.pkg, this.dependencyResolver), new (_strategies().ComponentBundlingStrategy)(this, this.pkg, this.dependencyResolver)];
|
|
683
683
|
} // TODO - executionContext should be responsible for updating components list, and emit 'update' events
|
|
684
684
|
// instead we keep track of changes
|
|
685
685
|
|
|
@@ -734,7 +734,7 @@ class PreviewMain {
|
|
|
734
734
|
bundler.registerTarget([{
|
|
735
735
|
entry: preview.getPreviewTarget.bind(preview)
|
|
736
736
|
}]);
|
|
737
|
-
if (!config.disabled) builder.registerBuildTasks([new (_envPreviewTemplate().EnvPreviewTemplateTask)(preview, envs, aspectLoader), new (_preview3().PreviewTask)(bundler, preview)]);
|
|
737
|
+
if (!config.disabled) builder.registerBuildTasks([new (_envPreviewTemplate().EnvPreviewTemplateTask)(preview, envs, aspectLoader, dependencyResolver, logger), new (_preview3().PreviewTask)(bundler, preview, dependencyResolver, logger)]);
|
|
738
738
|
|
|
739
739
|
if (workspace) {
|
|
740
740
|
workspace.registerOnComponentAdd(c => preview.handleComponentChange(c, currentComponents => currentComponents.add(c)));
|
|
@@ -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","getArtifactsVinylByExtensionAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByExtensionAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","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","getModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","getUi","Error","name","uiRoot","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","aspects","allComponentContextAspects","reduce","acc","curr","concat","state","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","includes","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","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","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","MainRuntime","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 { Component, ComponentAspect, ComponentMain, ComponentMap, ComponentID } 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 } 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 { 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.getArtifactsVinylByExtensionAndTaskName(\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.getArtifactsVinylByExtensionAndName(\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 * 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.getArtifactsVinylByExtensionAndTaskName(\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.getModulePath(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 ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n const [name, uiRoot] = ui;\n const resolvedAspects = await uiRoot.resolveAspects(PreviewRuntime.name);\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 /**\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 [new EnvBundlingStrategy(this), new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver)];\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),\n new PreviewTask(bundler, preview),\n ]);\n\n if (workspace) {\n workspace.registerOnComponentAdd((c) =>\n preview.handleComponentChange(c, (currentComponents) => currentComponents.add(c))\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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AC4L,MAAlB,CAAyBtM,CAAzB,CAAxD,CADF;MAGAN,SAAS,CAAC6M,yBAAV,CAAqC3L,GAAD,IAASwK,OAAO,CAACoB,sBAAR,CAA+B5L,GAA/B,CAA7C;IACD;;IAEDsK,OAAO,CAACR,QAAR,CAAiB,IAAA+B,yBAAA,EAAcrB,OAAd,CAAjB;IAEA,OAAOA,OAAP;EACD;;AAhesB;;;gCAAZtM,W,WAoXI,CAAC4N,eAAA,CAAKC,QAAL,EAAD,EAAqCD,eAAA,CAAKC,QAAL,EAArC,C;gCApXJ7N,W,aAsXM8N,kB;gCAtXN9N,W,kBAuXW,CACpB+N,wBADoB,EAEpBC,wBAFoB,EAGpBC,4BAHoB,EAIpBC,cAJoB,EAKpBC,kBALoB,EAMpBC,oBANoB,EAOpBC,gBAPoB,EAQpBC,sBARoB,EASpBC,kCAToB,EAUpBC,sBAVoB,EAWpBC,8CAXoB,EAYpBC,kBAZoB,C;gCAvXX1O,W,mBAsYY;EACrBiN,QAAQ,EAAE;AADW,C;;AA6FzBnN,wBAAA,CAAc6O,UAAd,CAAyB3O,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","getArtifactsVinylByExtensionAndTaskName","PREVIEW_TASK_NAME","PreviewArtifact","getPreviewFiles","isBundledWithEnv","files","getPaths","getArtifactsVinylByExtensionAndName","COMPONENT_STRATEGY_ARTIFACT_NAME","length","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","getModulePath","file","path","distRelativePath","getDistPathBySrcPath","relative","dirPath","mkdirSync","recursive","link","all","aspectsIdsToNotFilterOut","getUi","Error","name","uiRoot","resolvedAspects","resolveAspects","PreviewRuntime","filteredAspects","filterAspectsByExecutionContext","filePath","generateRoot","aspects","allComponentContextAspects","reduce","acc","curr","concat","state","ids","hostAspects","Object","keys","toObject","allAspectsToInclude","uniq","filtered","filter","aspect","getId","isCoreAspect","includes","getDefaultStrategies","EnvBundlingStrategy","ComponentBundlingStrategy","getPreviewConfig","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","registerOnComponentChange","update","registerOnComponentRemove","handleComponentRemoval","previewSchema","Slot","withType","MainRuntime","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 { Component, ComponentAspect, ComponentMain, ComponentMap, ComponentID } 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 } 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 { 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.getArtifactsVinylByExtensionAndTaskName(\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.getArtifactsVinylByExtensionAndName(\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 * 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.getArtifactsVinylByExtensionAndTaskName(\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.getModulePath(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 ui = this.ui.getUi();\n if (!ui) throw new Error('ui not found');\n const [name, uiRoot] = ui;\n const resolvedAspects = await uiRoot.resolveAspects(PreviewRuntime.name);\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 /**\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.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;;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;;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;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AA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YY;EACrBiN,QAAQ,EAAE;AADW,C;;AA6FzBnN,wBAAA,CAAc6O,UAAd,CAAyB3O,WAAzB"}
|
package/dist/preview.task.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ import { BundlerMain } from '@teambit/bundler';
|
|
|
4
4
|
import { ComponentMap } from '@teambit/component';
|
|
5
5
|
import { Capsule } from '@teambit/isolator';
|
|
6
6
|
import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
|
|
7
|
+
import { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
8
|
+
import { Logger } from '@teambit/logger';
|
|
7
9
|
import { PreviewMain } from './preview.main.runtime';
|
|
8
10
|
export declare const PREVIEW_TASK_NAME = "GeneratePreview";
|
|
9
11
|
export declare class PreviewTask implements BuildTask {
|
|
@@ -15,6 +17,8 @@ export declare class PreviewTask implements BuildTask {
|
|
|
15
17
|
* preview extension.
|
|
16
18
|
*/
|
|
17
19
|
private preview;
|
|
20
|
+
private dependencyResolver;
|
|
21
|
+
private logger;
|
|
18
22
|
constructor(
|
|
19
23
|
/**
|
|
20
24
|
* bundler extension.
|
|
@@ -23,7 +27,7 @@ export declare class PreviewTask implements BuildTask {
|
|
|
23
27
|
/**
|
|
24
28
|
* preview extension.
|
|
25
29
|
*/
|
|
26
|
-
preview: PreviewMain);
|
|
30
|
+
preview: PreviewMain, dependencyResolver: DependencyResolverMain, logger: Logger);
|
|
27
31
|
aspectId: string;
|
|
28
32
|
name: string;
|
|
29
33
|
location: TaskLocation;
|
package/dist/preview.task.js
CHANGED
|
@@ -51,9 +51,11 @@ class PreviewTask {
|
|
|
51
51
|
/**
|
|
52
52
|
* preview extension.
|
|
53
53
|
*/
|
|
54
|
-
preview) {
|
|
54
|
+
preview, dependencyResolver, logger) {
|
|
55
55
|
this.bundler = bundler;
|
|
56
56
|
this.preview = preview;
|
|
57
|
+
this.dependencyResolver = dependencyResolver;
|
|
58
|
+
this.logger = logger;
|
|
57
59
|
(0, _defineProperty2().default)(this, "aspectId", 'teambit.preview/preview');
|
|
58
60
|
(0, _defineProperty2().default)(this, "name", PREVIEW_TASK_NAME);
|
|
59
61
|
(0, _defineProperty2().default)(this, "location", 'end');
|
|
@@ -74,7 +76,6 @@ class PreviewTask {
|
|
|
74
76
|
const targets = await bundlingStrategy.computeTargets(computeTargetsContext, defs, this);
|
|
75
77
|
const bundlerContext = Object.assign(context, {
|
|
76
78
|
targets,
|
|
77
|
-
externalizePeer: bundlingStrategy.name !== 'env',
|
|
78
79
|
compress: bundlingStrategy.name !== 'env' && splitComponentBundle,
|
|
79
80
|
entry: [],
|
|
80
81
|
publicPath: this.getPreviewDirectory(context),
|
|
@@ -85,7 +86,7 @@ class PreviewTask {
|
|
|
85
86
|
envId: context.id
|
|
86
87
|
}
|
|
87
88
|
});
|
|
88
|
-
const bundler = await context.env.getBundler(bundlerContext
|
|
89
|
+
const bundler = await context.env.getBundler(bundlerContext);
|
|
89
90
|
const bundlerResults = await bundler.run();
|
|
90
91
|
const results = bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);
|
|
91
92
|
return results;
|
package/dist/preview.task.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["PREVIEW_TASK_NAME","PreviewTask","constructor","bundler","preview","execute","context","defs","getDefs","url","envRuntime","id","bundlingStrategy","getBundlingStrategy","env","envPreviewConfig","getEnvPreviewConfig","splitComponentBundle","computeTargetsContext","Object","assign","targets","computeTargets","bundlerContext","
|
|
1
|
+
{"version":3,"names":["PREVIEW_TASK_NAME","PreviewTask","constructor","bundler","preview","dependencyResolver","logger","execute","context","defs","getDefs","url","envRuntime","id","bundlingStrategy","getBundlingStrategy","env","envPreviewConfig","getEnvPreviewConfig","splitComponentBundle","computeTargetsContext","Object","assign","targets","computeTargets","bundlerContext","compress","name","entry","publicPath","getPreviewDirectory","rootPath","development","dev","metaData","initiator","envId","getBundler","bundlerResults","run","results","computeResults","getLinkFileDirectory","join","CAPSULE_ARTIFACTS_DIR","outputPath","resolve","getPathsFromMap","capsule","moduleMap","compiler","getCompiler","map","files","file","path","getDistPathBySrcPath","relative"],"sources":["preview.task.ts"],"sourcesContent":["import { resolve, join } from 'path';\nimport { ExecutionContext } from '@teambit/envs';\nimport { BuildContext, BuiltTaskResult, BuildTask, TaskLocation, CAPSULE_ARTIFACTS_DIR } from '@teambit/builder';\nimport { Bundler, BundlerContext, BundlerMain, Target } from '@teambit/bundler';\nimport { Compiler } from '@teambit/compiler';\nimport { ComponentMap } from '@teambit/component';\nimport { Capsule } from '@teambit/isolator';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { Logger } from '@teambit/logger';\nimport { PreviewMain } from './preview.main.runtime';\n\nexport const PREVIEW_TASK_NAME = 'GeneratePreview';\nexport class PreviewTask implements BuildTask {\n constructor(\n /**\n * bundler extension.\n */\n private bundler: BundlerMain,\n\n /**\n * preview extension.\n */\n private preview: PreviewMain,\n\n private dependencyResolver: DependencyResolverMain,\n private logger: Logger\n ) {}\n\n aspectId = 'teambit.preview/preview';\n name = PREVIEW_TASK_NAME;\n location: TaskLocation = 'end';\n // readonly dependencies = [CompilerAspect.id];\n\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n const defs = this.preview.getDefs();\n const url = `/preview/${context.envRuntime.id}`;\n const bundlingStrategy = this.preview.getBundlingStrategy(context.env);\n const envPreviewConfig = this.preview.getEnvPreviewConfig(context.env);\n const splitComponentBundle = envPreviewConfig.splitComponentBundle ?? false;\n const computeTargetsContext = Object.assign(context, { splitComponentBundle });\n\n const targets: Target[] = await bundlingStrategy.computeTargets(computeTargetsContext, defs, this);\n\n const bundlerContext: BundlerContext = Object.assign(context, {\n targets,\n compress: bundlingStrategy.name !== 'env' && splitComponentBundle,\n entry: [],\n publicPath: this.getPreviewDirectory(context),\n rootPath: url,\n development: context.dev,\n metaData: {\n initiator: `${PREVIEW_TASK_NAME} task`,\n envId: context.id,\n },\n });\n\n const bundler: Bundler = await context.env.getBundler(bundlerContext);\n const bundlerResults = await bundler.run();\n\n const results = bundlingStrategy.computeResults(bundlerContext, bundlerResults, this);\n return results;\n }\n\n getLinkFileDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview-links');\n }\n\n getPreviewDirectory(context: ExecutionContext) {\n const outputPath = resolve(`${context.id}/public`);\n return outputPath;\n }\n\n getPathsFromMap(\n capsule: Capsule,\n moduleMap: ComponentMap<AbstractVinyl[]>,\n context: BuildContext\n ): ComponentMap<string[]> {\n const compiler: Compiler = context.env.getCompiler(context);\n return moduleMap.map((files) => {\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAUO,MAAMA,iBAAiB,GAAG,iBAA1B;;;AACA,MAAMC,WAAN,CAAuC;EAC5CC,WAAW;EACT;AACJ;AACA;EACYC,OAJC;EAMT;AACJ;AACA;EACYC,OATC,EAWDC,kBAXC,EAYDC,MAZC,EAaT;IAAA,KATQH,OASR,GATQA,OASR;IAAA,KAJQC,OAIR,GAJQA,OAIR;IAAA,KAFQC,kBAER,GAFQA,kBAER;IAAA,KADQC,MACR,GADQA,MACR;IAAA,kDAES,yBAFT;IAAA,8CAGKN,iBAHL;IAAA,kDAIuB,KAJvB;EAAE;;EAKJ;EAEa,MAAPO,OAAO,CAACC,OAAD,EAAkD;IAAA;;IAC7D,MAAMC,IAAI,GAAG,KAAKL,OAAL,CAAaM,OAAb,EAAb;IACA,MAAMC,GAAG,GAAI,YAAWH,OAAO,CAACI,UAAR,CAAmBC,EAAG,EAA9C;IACA,MAAMC,gBAAgB,GAAG,KAAKV,OAAL,CAAaW,mBAAb,CAAiCP,OAAO,CAACQ,GAAzC,CAAzB;IACA,MAAMC,gBAAgB,GAAG,KAAKb,OAAL,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K,EAAG,SAAtB,CAAnB;IACA,OAAOgC,UAAP;EACD;;EAEDE,eAAe,CACbC,OADa,EAEbC,SAFa,EAGbzC,OAHa,EAIW;IACxB,MAAM0C,QAAkB,GAAG1C,OAAO,CAACQ,GAAR,CAAYmC,WAAZ,CAAwB3C,OAAxB,CAA3B;IACA,OAAOyC,SAAS,CAACG,GAAV,CAAeC,KAAD,IAAW;MAC9B,OAAOA,KAAK,CAACD,GAAN,CAAWE,IAAD,IAAU,IAAAX,YAAA,EAAKK,OAAO,CAACO,IAAb,EAAmBL,QAAQ,CAACM,oBAAT,CAA8BF,IAAI,CAACG,QAAnC,CAAnB,CAApB,CAAP;IACD,CAFM,CAAP;EAGD;;AArE2C"}
|
|
@@ -2,7 +2,7 @@ import { Component } from '@teambit/component';
|
|
|
2
2
|
import { ComponentResult } from '@teambit/builder';
|
|
3
3
|
import type { PkgMain } from '@teambit/pkg';
|
|
4
4
|
import type { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
5
|
-
import type { BundlerResult, BundlerContext,
|
|
5
|
+
import type { BundlerResult, BundlerContext, Target } from '@teambit/bundler';
|
|
6
6
|
import { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
|
|
7
7
|
import type { PreviewDefinition } from '../preview-definition';
|
|
8
8
|
import type { PreviewMain } from '../preview.main.runtime';
|
|
@@ -25,11 +25,7 @@ export declare class ComponentBundlingStrategy implements BundlingStrategy {
|
|
|
25
25
|
private dependencyResolver;
|
|
26
26
|
name: string;
|
|
27
27
|
constructor(preview: PreviewMain, pkg: PkgMain, dependencyResolver: DependencyResolverMain);
|
|
28
|
-
computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<
|
|
29
|
-
entries: BundlerEntryMap;
|
|
30
|
-
components: Component[];
|
|
31
|
-
outputPath: string;
|
|
32
|
-
}[]>;
|
|
28
|
+
computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<Target[]>;
|
|
33
29
|
computeComponentEntry(previewDefs: PreviewDefinition[], component: Component, context: ComputeTargetsContext): Promise<ComponentEntry>;
|
|
34
30
|
private getComponentChunkId;
|
|
35
31
|
private getComponentChunkFileName;
|
|
@@ -135,6 +135,7 @@ class ComponentBundlingStrategy {
|
|
|
135
135
|
}, {}));
|
|
136
136
|
const chunkSize = this.preview.config.maxChunkSize;
|
|
137
137
|
const chunks = chunkSize ? (0, _lodash().chunk)(entriesArr, chunkSize) : [entriesArr];
|
|
138
|
+
const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);
|
|
138
139
|
const targets = chunks.map(currentChunk => {
|
|
139
140
|
const entries = {};
|
|
140
141
|
const components = [];
|
|
@@ -145,7 +146,13 @@ class ComponentBundlingStrategy {
|
|
|
145
146
|
return {
|
|
146
147
|
entries,
|
|
147
148
|
components,
|
|
148
|
-
outputPath
|
|
149
|
+
outputPath,
|
|
150
|
+
|
|
151
|
+
/* It's a path to the root of the host component. */
|
|
152
|
+
// hostRootDir, handle this
|
|
153
|
+
hostDependencies: peers,
|
|
154
|
+
aliasHostDependencies: true,
|
|
155
|
+
externalizeHostDependencies: true
|
|
149
156
|
};
|
|
150
157
|
});
|
|
151
158
|
return targets; // const entries = entriesArr.reduce((entriesMap, entry) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","origComponents","capsuleNetwork","originalSeedersCapsules","map","capsule","component","entriesArr","Promise","all","computeComponentEntry","chunkSize","config","maxChunkSize","chunks","chunk","targets","currentChunk","entries","components","forEach","entry","Object","assign","push","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","join","copyAssetsToCapsules","result","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","dirname","fs","copyFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","basename","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","componentsResults","flatten","computeTargetResult","artifacts","getArtifactDef","isEmpty","errors","err","message","warning","warnings","startTime","endTime","globPatterns","rootDir","getDirName","envName","replace","resolve","capsulesRootDir","compiler","env","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","compiledPaths","prefix","paths","moduleMaps","contents","generateComponentLink","writeLinkContents"],"sources":["component-strategy.ts"],"sourcesContent":["import { join, resolve, basename, dirname } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty, chunk } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n\ntype ComponentEntry = {\n component: Component;\n entries: Object;\n};\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const origComponents = context.capsuleNetwork.originalSeedersCapsules.map((capsule) => capsule.component);\n\n const entriesArr = await Promise.all(\n origComponents.map((component) => {\n return this.computeComponentEntry(previewDefs, component, context);\n }, {})\n );\n\n const chunkSize = this.preview.config.maxChunkSize;\n\n const chunks = chunkSize ? chunk(entriesArr, chunkSize) : [entriesArr];\n\n const targets = chunks.map((currentChunk) => {\n const entries: BundlerEntryMap = {};\n const components: Component[] = [];\n currentChunk.forEach((entry) => {\n Object.assign(entries, entry.entries);\n components.push(entry.component);\n });\n\n return {\n entries,\n components,\n outputPath,\n };\n });\n\n return targets;\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n }\n\n async computeComponentEntry(\n previewDefs: PreviewDefinition[],\n component: Component,\n context: ComputeTargetsContext\n ): Promise<ComponentEntry> {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return { component, entries };\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', asset.name);\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(artifactDirFullPath);\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const destFilePath = join(artifactDirFullPath, asset.name);\n mkdirpSync(dirname(destFilePath));\n capsule.fs.copyFileSync(filePath, destFilePath);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const componentsResults = flatten(\n await Promise.all(results.map((result) => this.computeTargetResult(context, result)))\n );\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async computeTargetResult(context: BundlerContext, result: BundlerResult) {\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n return componentsResults;\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n // const files = flatten(paths.toArray().map(([, file]) => file));\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = flatten(await Promise.all(moduleMapsPromise));\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAIA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,MAAMA,oBAAoB,GAAG,SAA7B;;AACA,MAAMC,sBAAsB,GAAG,WAA/B;;AACA,MAAMC,6BAA6B,GAAI,GAAEF,oBAAqB,KAA9D;;AACA,MAAMG,+BAA+B,GAAI,GAAEF,sBAAuB,KAAlE;;AAEA,MAAMG,gCAAgC,GAAG,MAAzC;;AACA,MAAMC,gCAAgC,GAAG,mBAAzC;;;AAMP;AACA;AACA;AACO,MAAMC,yBAAN,CAA4D;EAGjEC,WAAW,CAASC,OAAT,EAAuCC,GAAvC,EAA6DC,kBAA7D,EAAyG;IAAA,KAAhGF,OAAgG,GAAhGA,OAAgG;IAAA,KAAlEC,GAAkE,GAAlEA,GAAkE;IAAA,KAA5CC,kBAA4C,GAA5CA,kBAA4C;IAAA,8CAF7G,WAE6G;EAAE;;EAElG,MAAdC,cAAc,CAACC,OAAD,EAAiCC,WAAjC,EAAmE;IACrF,MAAMC,UAAU,GAAG,KAAKC,aAAL,CAAmBH,OAAnB,CAAnB;IACA,IAAI,CAAC,IAAAI,qBAAA,EAAWF,UAAX,CAAL,EAA6B,IAAAG,qBAAA,EAAWH,UAAX,EAFwD,CAIrF;IACA;IACA;IAC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ApC,iBAAA,EAAQ,MAAM3F,OAAO,CAACC,GAAR,CAAYqH,iBAAZ,CAAd,CAAnB;IAEA,MAAMU,QAAQ,GAAG,IAAAC,8CAAA,EAAsBF,UAAtB,CAAjB;IACA,OAAO,KAAKhJ,OAAL,CAAamJ,iBAAb,CAA+BF,QAA/B,EAAyC,KAAKb,sBAAL,CAA4BtH,OAA5B,CAAzC,EAA+E,SAA/E,CAAP,CAzBiB,CA0BjB;EACD;;AAhVgE"}
|
|
1
|
+
{"version":3,"names":["PREVIEW_CHUNK_SUFFIX","COMPONENT_CHUNK_SUFFIX","PREVIEW_CHUNK_FILENAME_SUFFIX","COMPONENT_CHUNK_FILENAME_SUFFIX","COMPONENT_STRATEGY_SIZE_KEY_NAME","COMPONENT_STRATEGY_ARTIFACT_NAME","ComponentBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","origComponents","capsuleNetwork","originalSeedersCapsules","map","capsule","component","entriesArr","Promise","all","computeComponentEntry","chunkSize","config","maxChunkSize","chunks","chunk","peers","getPeerDependenciesListFromEnv","env","targets","currentChunk","entries","components","forEach","entry","Object","assign","push","hostDependencies","aliasHostDependencies","externalizeHostDependencies","path","computePaths","componentPath","getPaths","mainFile","componentPreviewChunkId","getComponentChunkId","id","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","library","name","type","splitComponentBundle","componentChunkId","toStringWithoutVersion","componentId","idstr","suffix","getAssetAbsolutePath","asset","join","copyAssetsToCapsules","result","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","dirname","fs","copyFileSync","undefined","componentEntryId","componentPreviewEntryId","componentFiles","componentAuxiliaryFiles","auxiliaryAssets","componentPreviewFiles","componentPreviewAuxiliaryFiles","concat","CAPSULE_ARTIFACTS_DIR","computeComponentMetadata","file","basename","size","compressedSize","filesTotalSize","assetsSize","compressedTotalFiles","compressedAssetsSize","assetsTotalSize","auxiliaryAssetsSize","compressedTotalAssets","compressedAuxiliaryAssetsSize","totalSize","compressedTotal","metadata","totalFiles","totalAssets","total","computeResults","results","componentsResults","flatten","computeTargetResult","artifacts","getArtifactDef","isEmpty","errors","err","message","warning","warnings","startTime","endTime","globPatterns","rootDir","getDirName","envName","replace","resolve","capsulesRootDir","compiler","getCompiler","getDistPathBySrcPath","relative","getComponentOutputPath","defs","BitError","moduleMapsPromise","previewDef","moduleMap","getModuleMap","maybeFiles","get","compiledPaths","prefix","paths","moduleMaps","contents","generateComponentLink","writeLinkContents"],"sources":["component-strategy.ts"],"sourcesContent":["import { join, resolve, basename, dirname } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { Component } from '@teambit/component';\nimport { ComponentID } from '@teambit/component-id';\nimport { flatten, isEmpty, chunk } from 'lodash';\nimport { Compiler } from '@teambit/compiler';\nimport type { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport type { Capsule } from '@teambit/isolator';\nimport { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';\nimport type { PkgMain } from '@teambit/pkg';\nimport { BitError } from '@teambit/bit-error';\nimport type { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap, Target } from '@teambit/bundler';\nimport { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport type { PreviewDefinition } from '../preview-definition';\nimport type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';\nimport { generateComponentLink } from './generate-component-link';\nimport { PreviewOutputFileNotFound } from '../exceptions';\n\nexport const PREVIEW_CHUNK_SUFFIX = 'preview';\nexport const COMPONENT_CHUNK_SUFFIX = 'component';\nexport const PREVIEW_CHUNK_FILENAME_SUFFIX = `${PREVIEW_CHUNK_SUFFIX}.js`;\nexport const COMPONENT_CHUNK_FILENAME_SUFFIX = `${COMPONENT_CHUNK_SUFFIX}.js`;\n\nexport const COMPONENT_STRATEGY_SIZE_KEY_NAME = 'size';\nexport const COMPONENT_STRATEGY_ARTIFACT_NAME = 'preview-component';\n\ntype ComponentEntry = {\n component: Component;\n entries: Object;\n};\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class ComponentBundlingStrategy implements BundlingStrategy {\n name = 'component';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<Target[]> {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n\n // const entriesArr = flatten(\n // await Promise.all(\n // context.capsuleNetwork.seedersCapsules.map((capsule) => {\n // return this.computeComponentEntry(previewDefs, capsule.component, context);\n // }, {})\n // )\n // );\n\n const origComponents = context.capsuleNetwork.originalSeedersCapsules.map((capsule) => capsule.component);\n\n const entriesArr = await Promise.all(\n origComponents.map((component) => {\n return this.computeComponentEntry(previewDefs, component, context);\n }, {})\n );\n\n const chunkSize = this.preview.config.maxChunkSize;\n\n const chunks = chunkSize ? chunk(entriesArr, chunkSize) : [entriesArr];\n\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n const targets = chunks.map((currentChunk) => {\n const entries: BundlerEntryMap = {};\n const components: Component[] = [];\n currentChunk.forEach((entry) => {\n Object.assign(entries, entry.entries);\n components.push(entry.component);\n });\n\n return {\n entries,\n components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n externalizeHostDependencies: true,\n };\n });\n\n return targets;\n // const entries = entriesArr.reduce((entriesMap, entry) => {\n // entriesMap[entry.library.name] = entry;\n // return entriesMap;\n // }, {});\n\n // const modules = await Promise.all(entriesArr.map(async (entry) => {\n // const dependencies = await this.dependencyResolver.getDependencies(entry.component);\n // const manifest = dependencies.toDependenciesManifest();\n // const peer = Object.entries(manifest.peerDependencies || {}).reduce((acc, [packageName, version]) => {\n // acc[packageName] = {\n // singleton: true,\n // requiredVersion: version\n // };\n\n // return acc;\n // }, {});\n // // console.log(entry);\n // return {\n // name: entry.library.name,\n // exposes: {\n // '.': entry.import || ''\n // },\n // shared: {\n // ...manifest.dependencies,\n // ...peer\n // },\n // };\n // }));\n }\n\n async computeComponentEntry(\n previewDefs: PreviewDefinition[],\n component: Component,\n context: ComputeTargetsContext\n ): Promise<ComponentEntry> {\n const path = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n const componentPreviewChunkId = this.getComponentChunkId(component.id, 'preview');\n\n const entries = {\n [componentPreviewChunkId]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: path,\n // dependOn: component.id.toStringWithoutVersion(),\n library: {\n name: componentPreviewChunkId,\n type: 'umd',\n },\n },\n };\n if (context.splitComponentBundle) {\n const componentChunkId = component.id.toStringWithoutVersion();\n entries[componentChunkId] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n import: componentPath,\n library: {\n name: componentChunkId,\n type: 'umd',\n },\n };\n }\n return { component, entries };\n }\n\n private getComponentChunkId(componentId: ComponentID, type: 'component' | 'preview') {\n const id =\n type === 'component'\n ? componentId.toStringWithoutVersion()\n : `${componentId.toStringWithoutVersion()}-${PREVIEW_CHUNK_SUFFIX}`;\n return id;\n }\n\n private getComponentChunkFileName(idstr: string, type: 'component' | 'preview') {\n const suffix = type === 'component' ? COMPONENT_CHUNK_FILENAME_SUFFIX : PREVIEW_CHUNK_FILENAME_SUFFIX;\n return `${idstr}-${suffix}`;\n }\n\n private getAssetAbsolutePath(context: BundlerContext, asset: Asset): string {\n const path = this.getOutputPath(context);\n return join(path, 'public', asset.name);\n }\n\n copyAssetsToCapsules(context: BundlerContext, result: BundlerResult) {\n context.components.forEach((component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return;\n const files = this.findAssetsForComponent(component, result.assets, result.entriesAssetsMap || {});\n if (!files) return;\n const artifactDirFullPath = join(capsule.path, this.getArtifactDirectory());\n // We don't use the mkdirSync as it uses the capsule fs which uses memfs, which doesn't know to handle nested none existing folders\n mkdirpSync(artifactDirFullPath);\n\n files.forEach((asset) => {\n const filePath = this.getAssetAbsolutePath(context, asset);\n if (!existsSync(filePath)) {\n throw new PreviewOutputFileNotFound(component.id, filePath);\n }\n const destFilePath = join(artifactDirFullPath, asset.name);\n mkdirpSync(dirname(destFilePath));\n capsule.fs.copyFileSync(filePath, destFilePath);\n });\n });\n }\n\n // private getCssFileName(componentId: ComponentID): string {\n // return `${componentId.toString({ ignoreVersion: true, fsCompatible: true })}.css`;\n // }\n\n private findAssetsForComponent(\n component: Component,\n assets: Asset[],\n entriesAssetsMap: EntriesAssetsMap\n ): Asset[] | undefined {\n if (!assets) return undefined;\n\n const componentEntryId = component.id.toStringWithoutVersion();\n const componentPreviewEntryId = this.getComponentChunkId(component.id, 'preview');\n const componentFiles = entriesAssetsMap[componentEntryId]?.assets || [];\n const componentAuxiliaryFiles = entriesAssetsMap[componentEntryId]?.auxiliaryAssets || [];\n const componentPreviewFiles = entriesAssetsMap[componentPreviewEntryId]?.assets || [];\n const componentPreviewAuxiliaryFiles = entriesAssetsMap[componentPreviewEntryId]?.auxiliaryAssets || [];\n\n const files = componentFiles\n .concat(componentAuxiliaryFiles)\n .concat(componentPreviewFiles)\n .concat(componentPreviewAuxiliaryFiles);\n return files;\n }\n\n private getArtifactDirectory() {\n return join(CAPSULE_ARTIFACTS_DIR, 'preview');\n }\n\n private computeComponentMetadata(\n context: BundlerContext,\n result: BundlerResult,\n component: Component\n ): ComponentPreviewMetaData {\n const componentEntryId = component.id.toStringWithoutVersion();\n if (!result?.entriesAssetsMap || !result?.entriesAssetsMap[componentEntryId]) {\n return {};\n }\n const files = (result.entriesAssetsMap[componentEntryId]?.assets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const filesTotalSize = result.entriesAssetsMap[componentEntryId]?.assetsSize || 0;\n const compressedTotalFiles = result.entriesAssetsMap[componentEntryId]?.compressedAssetsSize || 0;\n const assets = (result.entriesAssetsMap[componentEntryId]?.auxiliaryAssets || []).map((file) => {\n return {\n name: basename(file.name),\n size: file.size,\n compressedSize: file.compressedSize,\n };\n });\n const assetsTotalSize = result.entriesAssetsMap[componentEntryId]?.auxiliaryAssetsSize || 0;\n const compressedTotalAssets = result.entriesAssetsMap[componentEntryId]?.compressedAuxiliaryAssetsSize || 0;\n const totalSize = filesTotalSize + assetsTotalSize;\n const compressedTotal = compressedTotalFiles + compressedTotalAssets;\n\n const metadata = {\n [COMPONENT_STRATEGY_SIZE_KEY_NAME]: {\n files,\n assets,\n totalFiles: filesTotalSize,\n totalAssets: assetsTotalSize,\n total: totalSize,\n compressedTotalFiles,\n compressedTotalAssets,\n compressedTotal,\n },\n };\n\n return metadata;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const componentsResults = flatten(\n await Promise.all(results.map((result) => this.computeTargetResult(context, result)))\n );\n\n const artifacts = this.getArtifactDef();\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n async computeTargetResult(context: BundlerContext, result: BundlerResult) {\n if (isEmpty(result.errors)) {\n // In case there are errors files will not be emitted so trying to copy them will fail anyway\n this.copyAssetsToCapsules(context, result);\n }\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n const metadata = this.computeComponentMetadata(context, result, component);\n return {\n component,\n metadata,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n return componentsResults;\n }\n\n private getArtifactDef() {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n // const env: 'env' = 'env';\n // const rootDir = this.getDirName(context);\n\n return [\n {\n name: COMPONENT_STRATEGY_ARTIFACT_NAME,\n globPatterns: ['**'],\n rootDir: this.getArtifactDirectory(),\n // context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, component: Component, files: AbstractVinyl[]) {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n if (!capsule) return [];\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private getComponentOutputPath(capsule: Capsule) {\n return resolve(`${capsule.path}`);\n }\n\n private async computePaths(\n defs: PreviewDefinition[],\n context: ComputeTargetsContext,\n component: Component\n ): Promise<string> {\n // const previewMain = await this.preview.writePreviewRuntime(context);\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n // if (!capsule) return undefined;\n if (!capsule)\n throw new BitError(\n `could not find capsule for component ${component.id.toString()} during compute paths to bundle`\n );\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap([component]);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n // const files = flatten(paths.toArray().map(([, file]) => file));\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = flatten(await Promise.all(moduleMapsPromise));\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponentOutputPath(capsule), 'preview');\n // return flatten(moduleMaps);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;EAAA;;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IAAAC,8CAAA,EAAsBF,UAAtB,CAAjB;IACA,OAAO,KAAKrJ,OAAL,CAAawJ,iBAAb,CAA+BF,QAA/B,EAAyC,KAAKb,sBAAL,CAA4B3H,OAA5B,CAAzC,EAA+E,SAA/E,CAAP,CAzBiB,CA0BjB;EACD;;AAvVgE"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { ComponentResult } from '@teambit/builder';
|
|
2
2
|
import { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';
|
|
3
|
+
import { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
4
|
+
import { PkgMain } from '@teambit/pkg';
|
|
3
5
|
import type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
|
|
4
6
|
import { PreviewDefinition } from '../preview-definition';
|
|
5
7
|
import { PreviewMain } from '../preview.main.runtime';
|
|
@@ -8,13 +10,17 @@ import { PreviewMain } from '../preview.main.runtime';
|
|
|
8
10
|
*/
|
|
9
11
|
export declare class EnvBundlingStrategy implements BundlingStrategy {
|
|
10
12
|
private preview;
|
|
13
|
+
private pkg;
|
|
14
|
+
private dependencyResolver;
|
|
11
15
|
name: string;
|
|
12
|
-
constructor(preview: PreviewMain);
|
|
16
|
+
constructor(preview: PreviewMain, pkg: PkgMain, dependencyResolver: DependencyResolverMain);
|
|
13
17
|
computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<{
|
|
14
18
|
entries: string[];
|
|
15
19
|
html: BundlerHtmlConfig[];
|
|
16
20
|
components: import("@teambit/component").Component[];
|
|
17
21
|
outputPath: string;
|
|
22
|
+
hostDependencies: string[];
|
|
23
|
+
aliasHostDependencies: boolean;
|
|
18
24
|
}[]>;
|
|
19
25
|
private generateHtmlConfig;
|
|
20
26
|
computeResults(context: BundlerContext, results: BundlerResult[]): Promise<{
|
|
@@ -79,8 +79,10 @@ function _webpack() {
|
|
|
79
79
|
* bundles all components in a given env into the same bundle.
|
|
80
80
|
*/
|
|
81
81
|
class EnvBundlingStrategy {
|
|
82
|
-
constructor(preview) {
|
|
82
|
+
constructor(preview, pkg, dependencyResolver) {
|
|
83
83
|
this.preview = preview;
|
|
84
|
+
this.pkg = pkg;
|
|
85
|
+
this.dependencyResolver = dependencyResolver;
|
|
84
86
|
(0, _defineProperty2().default)(this, "name", 'env');
|
|
85
87
|
}
|
|
86
88
|
|
|
@@ -90,11 +92,17 @@ class EnvBundlingStrategy {
|
|
|
90
92
|
const htmlConfig = this.generateHtmlConfig({
|
|
91
93
|
dev: context.dev
|
|
92
94
|
});
|
|
95
|
+
const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);
|
|
93
96
|
return [{
|
|
94
97
|
entries: await this.computePaths(outputPath, previewDefs, context),
|
|
95
98
|
html: [htmlConfig],
|
|
96
99
|
components: context.components,
|
|
97
|
-
outputPath
|
|
100
|
+
outputPath,
|
|
101
|
+
|
|
102
|
+
/* It's a path to the root of the host component. */
|
|
103
|
+
// hostRootDir, handle this
|
|
104
|
+
hostDependencies: peers,
|
|
105
|
+
aliasHostDependencies: true
|
|
98
106
|
}];
|
|
99
107
|
}
|
|
100
108
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["EnvBundlingStrategy","constructor","preview","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","htmlConfig","generateHtmlConfig","dev","entries","computePaths","html","components","options","config","title","templateContent","cache","minify","computeResults","results","result","componentsResults","map","component","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","env","rootDir","getDirName","name","globPatterns","envName","id","replace","resolve","capsuleNetwork","capsulesRootDir","getPaths","files","capsule","compiler","getCompiler","file","join","path","getDistPathBySrcPath","relative","defs","previewMain","writePreviewRuntime","moduleMapsPromise","previewDef","moduleMap","getModuleMap","paths","ComponentMap","as","graphCapsules","getCapsule","maybeFiles","get","compiledPaths","template","renderTemplatePath","link","writeLink","prefix","undefined","flatten","toArray","concat","moduleMaps","Promise","all"],"sources":["env-strategy.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { flatten } from 'lodash';\nimport { ComponentMap } from '@teambit/component';\nimport { Compiler } from '@teambit/compiler';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { Capsule } from '@teambit/isolator';\nimport { ComponentResult } from '@teambit/builder';\nimport { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';\nimport type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport { PreviewDefinition } from '../preview-definition';\nimport { PreviewMain } from '../preview.main.runtime';\nimport { html } from '../webpack';\n\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class EnvBundlingStrategy implements BundlingStrategy {\n name = 'env';\n\n constructor(private preview: PreviewMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const htmlConfig = this.generateHtmlConfig({ dev: context.dev });\n\n return [\n {\n entries: await this.computePaths(outputPath, previewDefs, context),\n html: [htmlConfig],\n components: context.components,\n outputPath,\n },\n ];\n }\n\n private generateHtmlConfig(options: { dev?: boolean }): BundlerHtmlConfig {\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n cache: false,\n minify: options?.dev ?? true,\n };\n return config;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef(context);\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef(context: ComputeTargetsContext) {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n const env: 'env' = 'env';\n const rootDir = this.getDirName(context);\n\n return [\n {\n name: 'preview',\n globPatterns: ['public/**'],\n rootDir,\n context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, files: AbstractVinyl[], capsule: Capsule) {\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private async computePaths(\n outputPath: string,\n defs: PreviewDefinition[],\n context: ComputeTargetsContext\n ): Promise<string[]> {\n const previewMain = await this.preview.writePreviewRuntime(context);\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap(context.components);\n\n const paths = ComponentMap.as(context.components, (component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, files, capsule);\n return compiledPaths;\n });\n\n const template = previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : 'undefined';\n\n const link = this.preview.writeLink(\n previewDef.prefix,\n paths,\n previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : undefined,\n outputPath,\n false\n );\n\n const files = flatten(paths.toArray().map(([, file]) => file)).concat([link]);\n\n if (template) return files.concat([template]);\n return files;\n });\n\n const moduleMaps = await Promise.all(moduleMapsPromise);\n\n return flatten(moduleMaps.concat([previewMain]));\n }\n}\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;;AASA;EAAA;;EAAA;IAAA;EA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,MAAM4C,KAAK,GAAG,IAAA8B,iBAAA,EAAQd,KAAK,CAACe,OAAN,GAAgBtD,GAAhB,CAAoB,CAAC,GAAG2B,IAAH,CAAD,KAAcA,IAAlC,CAAR,EAAiD4B,MAAjD,CAAwD,CAACN,IAAD,CAAxD,CAAd;MAEA,IAAIF,QAAJ,EAAc,OAAOxB,KAAK,CAACgC,MAAN,CAAa,CAACR,QAAD,CAAb,CAAP;MACd,OAAOxB,KAAP;IACD,CA1ByB,CAA1B;IA4BA,MAAMiC,UAAU,GAAG,MAAMC,OAAO,CAACC,GAAR,CAAYvB,iBAAZ,CAAzB;IAEA,OAAO,IAAAkB,iBAAA,EAAQG,UAAU,CAACD,MAAX,CAAkB,CAACtB,WAAD,CAAlB,CAAR,CAAP;EACD;;AArH0D"}
|
|
1
|
+
{"version":3,"names":["EnvBundlingStrategy","constructor","preview","pkg","dependencyResolver","computeTargets","context","previewDefs","outputPath","getOutputPath","existsSync","mkdirpSync","htmlConfig","generateHtmlConfig","dev","peers","getPeerDependenciesListFromEnv","env","entries","computePaths","html","components","hostDependencies","aliasHostDependencies","options","config","title","templateContent","cache","minify","computeResults","results","result","componentsResults","map","component","errors","err","message","warning","warnings","startTime","endTime","artifacts","getArtifactDef","rootDir","getDirName","name","globPatterns","envName","id","replace","resolve","capsuleNetwork","capsulesRootDir","getPaths","files","capsule","compiler","getCompiler","file","join","path","getDistPathBySrcPath","relative","defs","previewMain","writePreviewRuntime","moduleMapsPromise","previewDef","moduleMap","getModuleMap","paths","ComponentMap","as","graphCapsules","getCapsule","maybeFiles","get","compiledPaths","template","renderTemplatePath","link","writeLink","prefix","undefined","flatten","toArray","concat","moduleMaps","Promise","all"],"sources":["env-strategy.ts"],"sourcesContent":["import { join, resolve } from 'path';\nimport { existsSync, mkdirpSync } from 'fs-extra';\nimport { flatten } from 'lodash';\nimport { ComponentMap } from '@teambit/component';\nimport { Compiler } from '@teambit/compiler';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { Capsule } from '@teambit/isolator';\nimport { ComponentResult } from '@teambit/builder';\nimport { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';\nimport { DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { PkgMain } from '@teambit/pkg';\nimport type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';\nimport { PreviewDefinition } from '../preview-definition';\nimport { PreviewMain } from '../preview.main.runtime';\nimport { html } from '../webpack';\n\n/**\n * bundles all components in a given env into the same bundle.\n */\nexport class EnvBundlingStrategy implements BundlingStrategy {\n name = 'env';\n\n constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}\n\n async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {\n const outputPath = this.getOutputPath(context);\n if (!existsSync(outputPath)) mkdirpSync(outputPath);\n const htmlConfig = this.generateHtmlConfig({ dev: context.dev });\n const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);\n\n return [\n {\n entries: await this.computePaths(outputPath, previewDefs, context),\n html: [htmlConfig],\n components: context.components,\n outputPath,\n /* It's a path to the root of the host component. */\n // hostRootDir, handle this\n hostDependencies: peers,\n aliasHostDependencies: true,\n },\n ];\n }\n\n private generateHtmlConfig(options: { dev?: boolean }): BundlerHtmlConfig {\n const config = {\n title: 'Preview',\n templateContent: html('Preview'),\n cache: false,\n minify: options?.dev ?? true,\n };\n return config;\n }\n\n async computeResults(context: BundlerContext, results: BundlerResult[]) {\n const result = results[0];\n\n const componentsResults: ComponentResult[] = result.components.map((component) => {\n return {\n component,\n errors: result.errors.map((err) => (typeof err === 'string' ? err : err.message)),\n warning: result.warnings,\n startTime: result.startTime,\n endTime: result.endTime,\n };\n });\n\n const artifacts = this.getArtifactDef(context);\n\n return {\n componentsResults,\n artifacts,\n };\n }\n\n private getArtifactDef(context: ComputeTargetsContext) {\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n const env: 'env' = 'env';\n const rootDir = this.getDirName(context);\n\n return [\n {\n name: 'preview',\n globPatterns: ['public/**'],\n rootDir,\n context: env,\n },\n ];\n }\n\n getDirName(context: ComputeTargetsContext) {\n const envName = context.id.replace('/', '__');\n return `${envName}-preview`;\n }\n\n private getOutputPath(context: ComputeTargetsContext) {\n return resolve(`${context.capsuleNetwork.capsulesRootDir}/${this.getDirName(context)}`);\n }\n\n private getPaths(context: ComputeTargetsContext, files: AbstractVinyl[], capsule: Capsule) {\n const compiler: Compiler = context.env.getCompiler();\n return files.map((file) => join(capsule.path, compiler.getDistPathBySrcPath(file.relative)));\n }\n\n private async computePaths(\n outputPath: string,\n defs: PreviewDefinition[],\n context: ComputeTargetsContext\n ): Promise<string[]> {\n const previewMain = await this.preview.writePreviewRuntime(context);\n const moduleMapsPromise = defs.map(async (previewDef) => {\n const moduleMap = await previewDef.getModuleMap(context.components);\n\n const paths = ComponentMap.as(context.components, (component) => {\n const capsule = context.capsuleNetwork.graphCapsules.getCapsule(component.id);\n const maybeFiles = moduleMap.get(component);\n if (!maybeFiles || !capsule) return [];\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, files, capsule);\n return compiledPaths;\n });\n\n const template = previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : 'undefined';\n\n const link = this.preview.writeLink(\n previewDef.prefix,\n paths,\n previewDef.renderTemplatePath ? await previewDef.renderTemplatePath(context) : undefined,\n outputPath,\n false\n );\n\n const files = flatten(paths.toArray().map(([, file]) => file)).concat([link]);\n\n if (template) return files.concat([template]);\n return files;\n });\n\n const moduleMaps = await Promise.all(moduleMapsPromise);\n\n return flatten(moduleMaps.concat([previewMain]));\n }\n}\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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X,GAAgC,MAAMZ,UAAU,CAACY,kBAAX,CAA8B3E,OAA9B,CAAtC,GAA+E,WAAhG;MAEA,MAAM4E,IAAI,GAAG,KAAKhF,OAAL,CAAaiF,SAAb,CACXd,UAAU,CAACe,MADA,EAEXZ,KAFW,EAGXH,UAAU,CAACY,kBAAX,GAAgC,MAAMZ,UAAU,CAACY,kBAAX,CAA8B3E,OAA9B,CAAtC,GAA+E+E,SAHpE,EAIX7E,UAJW,EAKX,KALW,CAAb;MAQA,MAAMgD,KAAK,GAAG,IAAA8B,iBAAA,EAAQd,KAAK,CAACe,OAAN,GAAgBrD,GAAhB,CAAoB,CAAC,GAAG0B,IAAH,CAAD,KAAcA,IAAlC,CAAR,EAAiD4B,MAAjD,CAAwD,CAACN,IAAD,CAAxD,CAAd;MAEA,IAAIF,QAAJ,EAAc,OAAOxB,KAAK,CAACgC,MAAN,CAAa,CAACR,QAAD,CAAb,CAAP;MACd,OAAOxB,KAAP;IACD,CA1ByB,CAA1B;IA4BA,MAAMiC,UAAU,GAAG,MAAMC,OAAO,CAACC,GAAR,CAAYvB,iBAAZ,CAAzB;IAEA,OAAO,IAAAkB,iBAAA,EAAQG,UAAU,CAACD,MAAX,CAAkB,CAACtB,WAAD,CAAlB,CAAR,CAAP;EACD;;AA1H0D"}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teambit/preview",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.739",
|
|
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.
|
|
9
|
+
"version": "0.0.739"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"mime": "2.5.2",
|
|
@@ -21,26 +21,26 @@
|
|
|
21
21
|
"@babel/runtime": "7.12.18",
|
|
22
22
|
"core-js": "^3.0.0",
|
|
23
23
|
"@teambit/harmony": "0.3.3",
|
|
24
|
-
"@teambit/express": "0.0.
|
|
24
|
+
"@teambit/express": "0.0.588",
|
|
25
25
|
"@teambit/logger": "0.0.583",
|
|
26
26
|
"@teambit/ui-foundation.ui.pages.static-error": "0.0.72",
|
|
27
|
-
"@teambit/builder": "0.0.
|
|
28
|
-
"@teambit/bundler": "0.0.
|
|
29
|
-
"@teambit/component": "0.0.
|
|
30
|
-
"@teambit/aspect-loader": "0.0.
|
|
31
|
-
"@teambit/
|
|
32
|
-
"@teambit/
|
|
27
|
+
"@teambit/builder": "0.0.739",
|
|
28
|
+
"@teambit/bundler": "0.0.739",
|
|
29
|
+
"@teambit/component": "0.0.739",
|
|
30
|
+
"@teambit/aspect-loader": "0.0.739",
|
|
31
|
+
"@teambit/dependency-resolver": "0.0.739",
|
|
32
|
+
"@teambit/envs": "0.0.739",
|
|
33
|
+
"@teambit/isolator": "0.0.739",
|
|
33
34
|
"@teambit/toolbox.path.to-windows-compatible-path": "0.0.483",
|
|
34
35
|
"@teambit/component-id": "0.0.402",
|
|
35
36
|
"@teambit/bit-error": "0.0.394",
|
|
36
37
|
"@teambit/cli": "0.0.491",
|
|
37
|
-
"@teambit/
|
|
38
|
-
"@teambit/
|
|
39
|
-
"@teambit/
|
|
40
|
-
"@teambit/
|
|
41
|
-
"@teambit/
|
|
42
|
-
"@teambit/
|
|
43
|
-
"@teambit/compiler": "0.0.738",
|
|
38
|
+
"@teambit/graphql": "0.0.739",
|
|
39
|
+
"@teambit/pkg": "0.0.739",
|
|
40
|
+
"@teambit/pubsub": "0.0.739",
|
|
41
|
+
"@teambit/ui": "0.0.739",
|
|
42
|
+
"@teambit/workspace": "0.0.739",
|
|
43
|
+
"@teambit/compiler": "0.0.739",
|
|
44
44
|
"@teambit/preview.cli.preview-server-status": "0.0.491",
|
|
45
45
|
"@teambit/preview.cli.webpack-events-listener": "0.0.161"
|
|
46
46
|
},
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const compositions = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.
|
|
2
|
-
export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.
|
|
1
|
+
export const compositions = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.739/dist/preview.composition.js')]
|
|
2
|
+
export const overview = [require('/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.739/dist/preview.docs.mdx')]
|
package/preview.main.runtime.tsx
CHANGED
|
@@ -393,7 +393,10 @@ export class PreviewMain {
|
|
|
393
393
|
}
|
|
394
394
|
|
|
395
395
|
private getDefaultStrategies() {
|
|
396
|
-
return [
|
|
396
|
+
return [
|
|
397
|
+
new EnvBundlingStrategy(this, this.pkg, this.dependencyResolver),
|
|
398
|
+
new ComponentBundlingStrategy(this, this.pkg, this.dependencyResolver),
|
|
399
|
+
];
|
|
397
400
|
}
|
|
398
401
|
|
|
399
402
|
// TODO - executionContext should be responsible for updating components list, and emit 'update' events
|
|
@@ -559,8 +562,8 @@ export class PreviewMain {
|
|
|
559
562
|
|
|
560
563
|
if (!config.disabled)
|
|
561
564
|
builder.registerBuildTasks([
|
|
562
|
-
new EnvPreviewTemplateTask(preview, envs, aspectLoader),
|
|
563
|
-
new PreviewTask(bundler, preview),
|
|
565
|
+
new EnvPreviewTemplateTask(preview, envs, aspectLoader, dependencyResolver, logger),
|
|
566
|
+
new PreviewTask(bundler, preview, dependencyResolver, logger),
|
|
564
567
|
]);
|
|
565
568
|
|
|
566
569
|
if (workspace) {
|
|
@@ -10,7 +10,7 @@ import { CAPSULE_ARTIFACTS_DIR, ComponentResult } from '@teambit/builder';
|
|
|
10
10
|
import type { PkgMain } from '@teambit/pkg';
|
|
11
11
|
import { BitError } from '@teambit/bit-error';
|
|
12
12
|
import type { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
13
|
-
import type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap } from '@teambit/bundler';
|
|
13
|
+
import type { BundlerResult, BundlerContext, Asset, BundlerEntryMap, EntriesAssetsMap, Target } from '@teambit/bundler';
|
|
14
14
|
import { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
|
|
15
15
|
import type { PreviewDefinition } from '../preview-definition';
|
|
16
16
|
import type { ComponentPreviewMetaData, PreviewMain } from '../preview.main.runtime';
|
|
@@ -37,7 +37,7 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
|
|
|
37
37
|
|
|
38
38
|
constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}
|
|
39
39
|
|
|
40
|
-
async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {
|
|
40
|
+
async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]): Promise<Target[]> {
|
|
41
41
|
const outputPath = this.getOutputPath(context);
|
|
42
42
|
if (!existsSync(outputPath)) mkdirpSync(outputPath);
|
|
43
43
|
|
|
@@ -61,6 +61,8 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
|
|
|
61
61
|
|
|
62
62
|
const chunks = chunkSize ? chunk(entriesArr, chunkSize) : [entriesArr];
|
|
63
63
|
|
|
64
|
+
const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);
|
|
65
|
+
|
|
64
66
|
const targets = chunks.map((currentChunk) => {
|
|
65
67
|
const entries: BundlerEntryMap = {};
|
|
66
68
|
const components: Component[] = [];
|
|
@@ -73,6 +75,11 @@ export class ComponentBundlingStrategy implements BundlingStrategy {
|
|
|
73
75
|
entries,
|
|
74
76
|
components,
|
|
75
77
|
outputPath,
|
|
78
|
+
/* It's a path to the root of the host component. */
|
|
79
|
+
// hostRootDir, handle this
|
|
80
|
+
hostDependencies: peers,
|
|
81
|
+
aliasHostDependencies: true,
|
|
82
|
+
externalizeHostDependencies: true,
|
|
76
83
|
};
|
|
77
84
|
});
|
|
78
85
|
|
|
@@ -7,6 +7,8 @@ import { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';
|
|
|
7
7
|
import { Capsule } from '@teambit/isolator';
|
|
8
8
|
import { ComponentResult } from '@teambit/builder';
|
|
9
9
|
import { BundlerContext, BundlerHtmlConfig, BundlerResult } from '@teambit/bundler';
|
|
10
|
+
import { DependencyResolverMain } from '@teambit/dependency-resolver';
|
|
11
|
+
import { PkgMain } from '@teambit/pkg';
|
|
10
12
|
import type { BundlingStrategy, ComputeTargetsContext } from '../bundling-strategy';
|
|
11
13
|
import { PreviewDefinition } from '../preview-definition';
|
|
12
14
|
import { PreviewMain } from '../preview.main.runtime';
|
|
@@ -18,12 +20,13 @@ import { html } from '../webpack';
|
|
|
18
20
|
export class EnvBundlingStrategy implements BundlingStrategy {
|
|
19
21
|
name = 'env';
|
|
20
22
|
|
|
21
|
-
constructor(private preview: PreviewMain) {}
|
|
23
|
+
constructor(private preview: PreviewMain, private pkg: PkgMain, private dependencyResolver: DependencyResolverMain) {}
|
|
22
24
|
|
|
23
25
|
async computeTargets(context: ComputeTargetsContext, previewDefs: PreviewDefinition[]) {
|
|
24
26
|
const outputPath = this.getOutputPath(context);
|
|
25
27
|
if (!existsSync(outputPath)) mkdirpSync(outputPath);
|
|
26
28
|
const htmlConfig = this.generateHtmlConfig({ dev: context.dev });
|
|
29
|
+
const peers = await this.dependencyResolver.getPeerDependenciesListFromEnv(context.env);
|
|
27
30
|
|
|
28
31
|
return [
|
|
29
32
|
{
|
|
@@ -31,6 +34,10 @@ export class EnvBundlingStrategy implements BundlingStrategy {
|
|
|
31
34
|
html: [htmlConfig],
|
|
32
35
|
components: context.components,
|
|
33
36
|
outputPath,
|
|
37
|
+
/* It's a path to the root of the host component. */
|
|
38
|
+
// hostRootDir, handle this
|
|
39
|
+
hostDependencies: peers,
|
|
40
|
+
aliasHostDependencies: true,
|
|
34
41
|
},
|
|
35
42
|
];
|
|
36
43
|
}
|
|
Binary file
|