@teambit/preview 0.0.775 → 0.0.778
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/bundler/chunks.ts +2 -7
- package/bundler/create-peer-link.spec.ts +33 -0
- package/bundler/create-peers-link.ts +48 -0
- package/dist/bundler/chunks.d.ts +1 -1
- package/dist/bundler/chunks.js +1 -6
- package/dist/bundler/chunks.js.map +1 -1
- package/dist/bundler/create-peer-link.spec.d.ts +1 -0
- package/dist/bundler/create-peer-link.spec.js +42 -0
- package/dist/bundler/create-peer-link.spec.js.map +1 -0
- package/dist/bundler/create-peers-link.d.ts +2 -0
- package/dist/bundler/create-peers-link.js +100 -0
- package/dist/bundler/create-peers-link.js.map +1 -0
- package/dist/env-preview-template.task.js +13 -3
- package/dist/env-preview-template.task.js.map +1 -1
- package/dist/generate-link.js +11 -7
- package/dist/generate-link.js.map +1 -1
- package/dist/html-utils.d.ts +6 -0
- package/dist/html-utils.js +43 -0
- package/dist/html-utils.js.map +1 -0
- package/dist/preview.preview.runtime.js +27 -31
- package/dist/preview.preview.runtime.js.map +1 -1
- package/dist/strategies/component-strategy.js +13 -10
- package/dist/strategies/component-strategy.js.map +1 -1
- package/dist/strategies/generate-component-link.js +3 -3
- package/dist/strategies/generate-component-link.js.map +1 -1
- package/html-utils.tsx +29 -0
- package/package-tar/teambit-preview-0.0.778.tgz +0 -0
- package/package.json +21 -20
- package/{preview-1656559717916.js → preview-1656905226178.js} +3 -3
- package/preview.preview.runtime.tsx +19 -32
- package/strategies/component-strategy.ts +16 -16
- package/strategies/generate-component-link.ts +3 -3
- package/package-tar/teambit-preview-0.0.775.tgz +0 -0
|
@@ -141,6 +141,16 @@ function _previewModules() {
|
|
|
141
141
|
return data;
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
+
function _htmlUtils() {
|
|
145
|
+
const data = require("./html-utils");
|
|
146
|
+
|
|
147
|
+
_htmlUtils = function () {
|
|
148
|
+
return data;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
return data;
|
|
152
|
+
}
|
|
153
|
+
|
|
144
154
|
// forward linkModules() for generate-link.ts
|
|
145
155
|
class PreviewPreview {
|
|
146
156
|
constructor(
|
|
@@ -249,14 +259,15 @@ class PreviewPreview {
|
|
|
249
259
|
const allFiles = await this.fetchComponentPreviewFiles(id, name); // It's a component bundled with the env
|
|
250
260
|
|
|
251
261
|
if (allFiles === null) return {};
|
|
252
|
-
allFiles.
|
|
262
|
+
await Promise.all(allFiles.map(file => {
|
|
253
263
|
// We want to run the preview file always last
|
|
254
264
|
if (file.endsWith('-preview.js')) {
|
|
255
265
|
previewFile = file;
|
|
256
|
-
|
|
257
|
-
this.addComponentFileElement(id, file);
|
|
266
|
+
return undefined;
|
|
258
267
|
}
|
|
259
|
-
|
|
268
|
+
|
|
269
|
+
return this.addComponentFileElement(id, file);
|
|
270
|
+
}));
|
|
260
271
|
if (!previewFile) return {};
|
|
261
272
|
return this.loadPreviewScript(id, name, previewFile);
|
|
262
273
|
}
|
|
@@ -293,45 +304,30 @@ class PreviewPreview {
|
|
|
293
304
|
}
|
|
294
305
|
|
|
295
306
|
addComponentFileScriptElement(id, previewBundleFileName) {
|
|
296
|
-
const script = document.createElement('script');
|
|
297
|
-
script.setAttribute('defer', 'defer');
|
|
298
|
-
const stringId = id.toString();
|
|
299
307
|
const previewRoute = `~aspect/component-preview`;
|
|
308
|
+
const stringId = id.toString();
|
|
300
309
|
const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
310
|
+
return (0, _htmlUtils().loadScript)({
|
|
311
|
+
src
|
|
312
|
+
});
|
|
304
313
|
}
|
|
305
314
|
|
|
306
315
|
addComponentFileLinkElement(id, previewBundleFileName) {
|
|
307
|
-
const link = document.createElement('link');
|
|
308
316
|
const stringId = id.toString();
|
|
309
317
|
const previewRoute = `~aspect/component-preview`;
|
|
310
318
|
const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
link.setAttribute('rel', 'stylesheet');
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
document.head.appendChild(link);
|
|
318
|
-
return link;
|
|
319
|
+
return (0, _htmlUtils().loadLink)({
|
|
320
|
+
href
|
|
321
|
+
});
|
|
319
322
|
}
|
|
320
323
|
|
|
321
324
|
async loadPreviewScript(id, previewName, previewBundleFileName) {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
script.setAttribute('defer', 'defer');
|
|
328
|
-
|
|
329
|
-
script.onload = () => resolve();
|
|
330
|
-
|
|
331
|
-
script.onerror = (message, _, _1, _2, error) => reject(error || new Error(`[preview.preview] failed to load preview script: ${message}`));
|
|
325
|
+
const previewRoute = `~aspect/component-preview`;
|
|
326
|
+
const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;
|
|
327
|
+
await (0, _htmlUtils().loadScript)({
|
|
328
|
+
src
|
|
329
|
+
}); // TODO - replace with jsonp
|
|
332
330
|
|
|
333
|
-
document.head.appendChild(script);
|
|
334
|
-
});
|
|
335
331
|
const globalId = `${id.toStringWithoutVersion()}-preview`;
|
|
336
332
|
const componentPreview = window[globalId];
|
|
337
333
|
if (!componentPreview) throw new (_exceptions().PreviewNotFound)(previewName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","forEach","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","script","document","createElement","setAttribute","previewRoute","src","head","appendChild","link","href","reject","onload","onerror","message","_","_1","_2","error","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n allFiles.forEach((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n } else {\n this.addComponentFileElement(id, file);\n }\n });\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const script = document.createElement('script');\n script.setAttribute('defer', 'defer');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n document.head.appendChild(script);\n return script;\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const link = document.createElement('link');\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n link.setAttribute('href', href);\n if (previewBundleFileName.endsWith('.css')) {\n link.setAttribute('rel', 'stylesheet');\n }\n document.head.appendChild(link);\n return link;\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n await new Promise<void>((resolve, reject) => {\n const script = document.createElement('script');\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n script.src = src;\n script.setAttribute('defer', 'defer');\n script.onload = () => resolve();\n script.onerror = (message, _, _1, _2, error) =>\n reject(error || new Error(`[preview.preview] failed to load preview script: ${message}`));\n document.head.appendChild(script);\n });\n\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;AASO,MAAMA,cAAN,CAAqB;EAC1BC,WAAW;EACT;AACJ;AACA;EACYC,MAJC;EAMT;AACJ;AACA;EACYC,WATC,EAWDC,oBAXC,EAYT;IAAA,KARQF,MAQR,GARQA,MAQR;IAAA,KAH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I,WAAD,EAAcC,oBAAd,CAHmB,EAInB;IACA,MAAMe,OAAO,GAAG,IAAInB,cAAJ,CAAmBE,MAAnB,EAA2BC,WAA3B,EAAwCC,oBAAxC,CAAhB;IAEA0C,MAAM,CAACC,gBAAP,CAAwB,YAAxB,EAAsC,MAAM;MAC1C;MACA5B,OAAO,CAACoB,MAAR;IACD,CAHD;IAKA,OAAOpB,OAAP;EACD;;AAnRyB;;;gCAAfnB,c,aAgQMgJ,yB;gCAhQNhJ,c,kBAkQW,CAACiJ,iBAAD,C;gCAlQXjJ,c,WAoQI,CAACkJ,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB3F,wBAAA,CAAc4F,UAAd,CAAyBpJ,cAAzB"}
|
|
1
|
+
{"version":3,"names":["PreviewPreview","constructor","pubsub","previewSlot","renderingContextSlot","isReady","Promise","resolve","_setupPromise","PREVIEW_MODULES","onSet","add","rootExt","previewName","componentId","getLocation","name","getDefault","isDev","preview","getPreview","PreviewNotFound","includesAll","all","include","map","inclPreviewName","includedPreview","undefined","inclPreviewModule","getPreviewModule","selectPreviewModel","fullName","includes","filter","module","componentAspects","getComponentAspects","toString","render","getRenderingContext","memoize","fetchComponentAspects","max","maxAge","registerClickPubSub","window","addEventListener","e","timestamp","Date","now","clickEvent","Object","assign","pub","PreviewAspect","id","ClickInsideAnIframeEvent","has","includedReady","every","included","compShortId","relevantModel","get","Error","componentMap","componentPreviews","fetchComponentPreview","loadComponentPreviews","component","mainModule","previewFile","allFiles","fetchComponentPreviewFiles","file","endsWith","addComponentFileElement","loadPreviewScript","previewBundleFileName","addComponentFileScriptElement","addComponentFileLinkElement","previewAssetsRoute","stringId","url","res","crossFetch","status","parsed","json","isBundledWithEnv","files","length","previewRoute","src","loadScript","href","loadLink","globalId","toStringWithoutVersion","componentPreview","registerPreview","register","aspectsFilter","RenderingContext","registerRenderContext","renderContext","previews","values","defaultOne","find","previewCandidate","default","getParam","query","param","params","URLSearchParams","withoutHash","location","hash","substring","before","after","split","ComponentID","tryFromString","provider","config","PreviewRuntime","PubsubAspect","Slot","withType","addRuntime"],"sources":["preview.preview.runtime.tsx"],"sourcesContent":["import PubsubAspect, { PubsubPreview } from '@teambit/pubsub';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { ComponentID } from '@teambit/component-id';\nimport crossFetch from 'cross-fetch';\nimport memoize from 'memoizee';\n\nimport { PreviewNotFound } from './exceptions';\nimport { PreviewType } from './preview-type';\nimport { PreviewAspect, PreviewRuntime } from './preview.aspect';\nimport { ClickInsideAnIframeEvent } from './events';\nimport { ModuleFile, PreviewModule } from './types/preview-module';\nimport { RenderingContext } from './rendering-context';\nimport { fetchComponentAspects } from './gql/fetch-component-aspects';\nimport { PREVIEW_MODULES } from './preview-modules';\nimport { loadScript, loadLink } from './html-utils';\n\n// forward linkModules() for generate-link.ts\nexport { linkModules } from './preview-modules';\n\nexport type PreviewSlot = SlotRegistry<PreviewType>;\n\nexport type RenderingContextOptions = { aspectsFilter?: string[] };\nexport type RenderingContextProvider = (options: RenderingContextOptions) => { [key: string]: any };\nexport type RenderingContextSlot = SlotRegistry<RenderingContextProvider>;\n\nexport class PreviewPreview {\n constructor(\n /**\n * register to pubsub\n */\n private pubsub: PubsubPreview,\n\n /**\n * preview slot.\n */\n private previewSlot: PreviewSlot,\n\n private renderingContextSlot: RenderingContextSlot\n ) {\n this.registerClickPubSub();\n }\n\n private registerClickPubSub() {\n window.addEventListener('click', (e) => {\n const timestamp = Date.now();\n const clickEvent = Object.assign({}, e);\n this.pubsub.pub(PreviewAspect.id, new ClickInsideAnIframeEvent(timestamp, clickEvent));\n });\n }\n\n private isDev = false;\n\n private isReady() {\n const { previewName } = this.getLocation();\n const name = previewName || this.getDefault();\n\n if (!PREVIEW_MODULES.has(name)) return false;\n const preview = this.getPreview(name);\n if (!preview) return false;\n const includedReady = preview.include?.every((included) => PREVIEW_MODULES.has(included)) ?? true;\n if (!includedReady) return false;\n\n return true;\n }\n\n private _setupPromise?: Promise<void>;\n setup = () => {\n if (this.isReady()) return Promise.resolve();\n\n this._setupPromise ??= new Promise((resolve) => {\n PREVIEW_MODULES.onSet.add(() => {\n if (this.isReady()) resolve();\n });\n });\n\n return this._setupPromise;\n };\n\n /**\n * render the preview.\n */\n render = async (rootExt?: string) => {\n const { previewName, componentId } = this.getLocation();\n const name = previewName || this.getDefault();\n if (rootExt) this.isDev = rootExt === 'teambit.workspace/workspace';\n\n const preview = this.getPreview(name);\n if (!preview || !componentId) {\n throw new PreviewNotFound(previewName);\n }\n\n const includesAll = await Promise.all(\n (preview.include || []).map(async (inclPreviewName) => {\n const includedPreview = this.getPreview(inclPreviewName);\n if (!includedPreview) return undefined;\n\n const inclPreviewModule = await this.getPreviewModule(inclPreviewName, componentId);\n return includedPreview.selectPreviewModel?.(componentId.fullName, inclPreviewModule);\n })\n );\n\n const includes = includesAll.filter((module) => !!module);\n // during build / tag, the component is isolated, so all aspects are relevant, and do not require filtering\n const componentAspects = this.isDev ? await this.getComponentAspects(componentId.toString()) : undefined;\n\n return preview.render(\n componentId,\n await this.getPreviewModule(name, componentId),\n includes,\n this.getRenderingContext(componentAspects)\n );\n };\n\n async getPreviewModule(previewName: string, id: ComponentID): Promise<PreviewModule> {\n const compShortId = id.fullName;\n\n const relevantModel = PREVIEW_MODULES.get(previewName);\n if (!relevantModel) throw new Error(`[preview.preview] missing preview \"${previewName}\"`);\n if (relevantModel.componentMap[compShortId]) return relevantModel;\n\n const componentPreviews = await this.fetchComponentPreview(id, previewName);\n PREVIEW_MODULES.loadComponentPreviews(compShortId, componentPreviews);\n\n const component = componentPreviews[previewName];\n\n return {\n mainModule: relevantModel.mainModule,\n componentMap: {\n [id.fullName]: component,\n },\n };\n }\n\n async fetchComponentPreview(id: ComponentID, name: string): Promise<Record<string, ModuleFile[]>> {\n let previewFile: string | undefined;\n const allFiles = await this.fetchComponentPreviewFiles(id, name);\n // It's a component bundled with the env\n if (allFiles === null) return {};\n\n await Promise.all(\n allFiles.map((file) => {\n // We want to run the preview file always last\n if (file.endsWith('-preview.js')) {\n previewFile = file;\n return undefined;\n }\n\n return this.addComponentFileElement(id, file);\n })\n );\n\n if (!previewFile) return {};\n return this.loadPreviewScript(id, name, previewFile);\n }\n\n private addComponentFileElement(id: ComponentID, previewBundleFileName: string) {\n if (previewBundleFileName.endsWith('.js')) {\n return this.addComponentFileScriptElement(id, previewBundleFileName);\n }\n return this.addComponentFileLinkElement(id, previewBundleFileName);\n }\n\n private async fetchComponentPreviewFiles(id: ComponentID, previewName: string): Promise<string[] | null> {\n const previewAssetsRoute = `~aspect/preview-assets`;\n const stringId = id.toString();\n const url = `/api/${stringId}/${previewAssetsRoute}`;\n\n const res = await crossFetch(url);\n if (res.status >= 400) {\n throw new PreviewNotFound(previewName);\n }\n const parsed = await res.json();\n // This is component bundled with the env, no reason to bring the files, as they will be the files of the env\n if (parsed.isBundledWithEnv) {\n return null;\n }\n if (!parsed.files || !parsed.files.length) {\n throw new PreviewNotFound(previewName);\n }\n return parsed.files;\n }\n\n private addComponentFileScriptElement(id: ComponentID, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const stringId = id.toString();\n const src = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadScript({ src });\n }\n\n private addComponentFileLinkElement(id: ComponentID, previewBundleFileName: string) {\n const stringId = id.toString();\n const previewRoute = `~aspect/component-preview`;\n const href = `/api/${stringId}/${previewRoute}/${previewBundleFileName}`;\n return loadLink({ href });\n }\n\n private async loadPreviewScript(id: ComponentID, previewName: string, previewBundleFileName: string) {\n const previewRoute = `~aspect/component-preview`;\n const src = `/api/${id.toString()}/${previewRoute}/${previewBundleFileName}`;\n await loadScript({ src });\n\n // TODO - replace with jsonp\n const globalId = `${id.toStringWithoutVersion()}-preview`;\n const componentPreview = window[globalId];\n if (!componentPreview) throw new PreviewNotFound(previewName);\n\n return componentPreview as Record<string, ModuleFile[]>;\n }\n\n private getComponentAspects = memoize(fetchComponentAspects, {\n max: 100,\n maxAge: 12 * 60 * 60 * 1000,\n });\n\n /**\n * register a new preview.\n */\n registerPreview(preview: PreviewType) {\n this.previewSlot.register(preview);\n return this;\n }\n\n /**\n * get the preview rendering context.\n */\n getRenderingContext(aspectsFilter?: string[]) {\n return new RenderingContext(this.renderingContextSlot, { aspectsFilter });\n }\n\n /**\n * allows aspects to add rendering contexts.\n * render context is available through all preview definitions.\n */\n registerRenderContext(renderContext: RenderingContextProvider) {\n this.renderingContextSlot.register(renderContext);\n return this;\n }\n\n getDefault() {\n const previews = this.previewSlot.values();\n const defaultOne = previews.find((previewCandidate) => previewCandidate.default);\n\n return defaultOne?.name || previews[0].name;\n }\n\n private getPreview(previewName: string): undefined | PreviewType {\n const previews = this.previewSlot.values();\n const preview = previews.find((previewCandidate) => previewCandidate.name === previewName);\n\n return preview;\n }\n\n private getParam(query: string, param: string) {\n const params = new URLSearchParams(query);\n return params.get(param);\n }\n\n private getLocation() {\n const withoutHash = window.location.hash.substring(1);\n const [before, after] = withoutHash.split('?');\n\n return {\n previewName: this.getParam(after, 'preview'),\n componentId: ComponentID.tryFromString(before),\n };\n }\n\n static runtime = PreviewRuntime;\n\n static dependencies = [PubsubAspect];\n\n static slots = [Slot.withType<PreviewType>(), Slot.withType<RenderingContextProvider>()];\n\n static async provider(\n [pubsub]: [PubsubPreview],\n config,\n [previewSlot, renderingContextSlot]: [PreviewSlot, RenderingContextSlot]\n ) {\n const preview = new PreviewPreview(pubsub, previewSlot, renderingContextSlot);\n\n window.addEventListener('hashchange', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n preview.render();\n });\n\n return preview;\n }\n}\n\nPreviewAspect.addRuntime(PreviewPreview);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA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kPMkI,yB;gCAlPNlI,c,kBAoPW,CAACmI,iBAAD,C;gCApPXnI,c,WAsPI,CAACoI,eAAA,CAAKC,QAAL,EAAD,EAA+BD,eAAA,CAAKC,QAAL,EAA/B,C;;AAkBjB7E,wBAAA,CAAc8E,UAAd,CAAyBtI,cAAzB"}
|
|
@@ -184,34 +184,37 @@ class ComponentBundlingStrategy {
|
|
|
184
184
|
}
|
|
185
185
|
|
|
186
186
|
async computeComponentEntry(previewDefs, component, context) {
|
|
187
|
-
const
|
|
187
|
+
const componentPreviewPath = await this.computePaths(previewDefs, context, component);
|
|
188
188
|
const [componentPath] = this.getPaths(context, component, [component.mainFile]);
|
|
189
|
-
const
|
|
189
|
+
const chunks = {
|
|
190
|
+
componentPreview: this.getComponentChunkId(component.id, 'preview'),
|
|
191
|
+
component: context.splitComponentBundle ? component.id.toStringWithoutVersion() : undefined
|
|
192
|
+
};
|
|
190
193
|
const entries = {
|
|
191
|
-
[
|
|
194
|
+
[chunks.componentPreview]: {
|
|
192
195
|
filename: this.getComponentChunkFileName(component.id.toString({
|
|
193
196
|
fsCompatible: true,
|
|
194
197
|
ignoreVersion: true
|
|
195
198
|
}), 'preview'),
|
|
196
|
-
import:
|
|
197
|
-
|
|
199
|
+
import: componentPreviewPath,
|
|
200
|
+
dependOn: chunks.component,
|
|
198
201
|
library: {
|
|
199
|
-
name:
|
|
202
|
+
name: chunks.componentPreview,
|
|
200
203
|
type: 'umd'
|
|
201
204
|
}
|
|
202
205
|
}
|
|
203
206
|
};
|
|
204
207
|
|
|
205
|
-
if (
|
|
206
|
-
|
|
207
|
-
entries[componentChunkId] = {
|
|
208
|
+
if (chunks.component) {
|
|
209
|
+
entries[chunks.component] = {
|
|
208
210
|
filename: this.getComponentChunkFileName(component.id.toString({
|
|
209
211
|
fsCompatible: true,
|
|
210
212
|
ignoreVersion: true
|
|
211
213
|
}), 'component'),
|
|
214
|
+
dependOn: undefined,
|
|
212
215
|
import: componentPath,
|
|
213
216
|
library: {
|
|
214
|
-
name:
|
|
217
|
+
name: chunks.component,
|
|
215
218
|
type: 'umd'
|
|
216
219
|
}
|
|
217
220
|
};
|
|
@@ -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","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","getAssetFilename","split","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","prefix","paths","compiledPaths","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', this.getAssetFilename(asset));\n }\n\n private getAssetFilename(asset: Asset): string {\n // handle cases where the asset name is something like my-image.svg?hash (while the filename in the fs is just my-image.svg)\n const [name] = asset.name.split('?');\n return 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, this.getAssetFilename(asset));\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 { prefix: previewDef.prefix, paths: [] };\n\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = 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;;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AAK,EAAEC;MAFF,CAAP;IAID,CAZyB,CAA1B;IAcA,MAAMC,UAAU,GAAG,MAAMtI,OAAO,CAACC,GAAR,CAAY4H,iBAAZ,CAAzB;IAEA,MAAMU,QAAQ,GAAG,IAAAC,8CAAA,EAAsBF,UAAtB,CAAjB;IACA,OAAO,KAAKvJ,OAAL,CAAa0J,iBAAb,CAA+BF,QAA/B,EAAyC,KAAKb,sBAAL,CAA4B7H,OAA5B,CAAzC,EAA+E,SAA/E,CAAP,CAzBiB,CA0BjB;EACD;;AA7VgE"}
|
|
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","componentPreviewPath","computePaths","componentPath","getPaths","mainFile","componentPreview","getComponentChunkId","id","splitComponentBundle","toStringWithoutVersion","undefined","filename","getComponentChunkFileName","toString","fsCompatible","ignoreVersion","import","dependOn","library","name","type","componentId","idstr","suffix","getAssetAbsolutePath","asset","path","join","getAssetFilename","split","copyAssetsToCapsules","result","graphCapsules","getCapsule","files","findAssetsForComponent","assets","entriesAssetsMap","artifactDirFullPath","getArtifactDirectory","filePath","PreviewOutputFileNotFound","destFilePath","dirname","fs","copyFileSync","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","prefix","paths","compiledPaths","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 componentPreviewPath = await this.computePaths(previewDefs, context, component);\n const [componentPath] = this.getPaths(context, component, [component.mainFile]);\n\n const chunks = {\n componentPreview: this.getComponentChunkId(component.id, 'preview'),\n component: context.splitComponentBundle ? component.id.toStringWithoutVersion() : undefined,\n };\n\n const entries = {\n [chunks.componentPreview]: {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'preview'\n ),\n import: componentPreviewPath,\n dependOn: chunks.component,\n library: { name: chunks.componentPreview, type: 'umd' },\n },\n };\n\n if (chunks.component) {\n entries[chunks.component] = {\n filename: this.getComponentChunkFileName(\n component.id.toString({\n fsCompatible: true,\n ignoreVersion: true,\n }),\n 'component'\n ),\n dependOn: undefined,\n import: componentPath,\n library: { name: chunks.component, 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', this.getAssetFilename(asset));\n }\n\n private getAssetFilename(asset: Asset): string {\n // handle cases where the asset name is something like my-image.svg?hash (while the filename in the fs is just my-image.svg)\n const [name] = asset.name.split('?');\n return 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, this.getAssetFilename(asset));\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 { prefix: previewDef.prefix, paths: [] };\n\n const [, files] = maybeFiles;\n const compiledPaths = this.getPaths(context, component, files);\n\n return {\n prefix: previewDef.prefix,\n paths: compiledPaths,\n };\n });\n\n const moduleMaps = await Promise.all(moduleMapsPromise);\n\n const contents = generateComponentLink(moduleMaps);\n return this.preview.writeLinkContents(contents, this.getComponent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,UAAU,CAACE,YAAX,CAAwB,CAACnI,SAAD,CAAxB,CAAxB;MACA,MAAMoI,UAAU,GAAGF,SAAS,CAACG,GAAV,CAAcrI,SAAd,CAAnB;MACA,IAAI,CAACoI,UAAD,IAAe,CAACrI,OAApB,EAA6B,OAAO;QAAEuI,MAAM,EAAEL,UAAU,CAACK,MAArB;QAA6BC,KAAK,EAAE;MAApC,CAAP;MAE7B,MAAM,GAAG5E,KAAH,IAAYyE,UAAlB;MACA,MAAMI,aAAa,GAAG,KAAK5G,QAAL,CAAcvC,OAAd,EAAuBW,SAAvB,EAAkC2D,KAAlC,CAAtB;MAEA,OAAO;QACL2E,MAAM,EAAEL,UAAU,CAACK,MADd;QAELC,KAAK,EAAEC;MAFF,CAAP;IAID,CAZyB,CAA1B;IAcA,MAAMC,UAAU,GAAG,MAAMvI,OAAO,CAACC,GAAR,CAAY6H,iBAAZ,CAAzB;IAEA,MAAMU,QAAQ,GAAG,IAAAC,8CAAA,EAAsBF,UAAtB,CAAjB;IACA,OAAO,KAAKxJ,OAAL,CAAa2J,iBAAb,CAA+BF,QAA/B,EAAyC,KAAKb,sBAAL,CAA4B9H,OAA5B,CAAzC,EAA+E,SAA/E,CAAP,CAzBiB,CA0BjB;EACD;;AA7VgE"}
|
|
@@ -34,15 +34,15 @@ function generateComponentLink(modules) {
|
|
|
34
34
|
}) => entries.map(({
|
|
35
35
|
path,
|
|
36
36
|
linkName
|
|
37
|
-
}) => `import * as ${linkName} from '${path}'`).join(';\n')).join('
|
|
37
|
+
}) => `import * as ${linkName} from '${path}'`).join(';\n')).join(';\n'); // export files group per preview
|
|
38
38
|
|
|
39
39
|
const exportsString = links.map(({
|
|
40
40
|
name,
|
|
41
41
|
entries
|
|
42
42
|
}) => `export const ${name} = [${entries.map(entry => entry.linkName).join(', ')}]`).join(';\n');
|
|
43
|
-
return `${importStr}
|
|
43
|
+
return `${importStr};
|
|
44
44
|
|
|
45
|
-
${exportsString}
|
|
45
|
+
${exportsString};
|
|
46
46
|
`;
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["generateComponentLink","modules","links","map","prefix","paths","name","entries","path","idx","toWindowsCompatiblePath","linkName","importStr","join","exportsString","entry"],"sources":["generate-component-link.ts"],"sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\n\nexport type ModuleVar = {\n prefix: string;\n paths: string[];\n};\n\nexport function generateComponentLink(modules: ModuleVar[]): string {\n const links = modules.map(({ prefix, paths }) => ({\n name: prefix,\n entries: paths.map((path, idx) => ({\n path: toWindowsCompatiblePath(path),\n linkName: `${prefix}_${idx}`,\n })),\n }));\n\n // import per preview file\n const importStr: string = links\n .map(({ entries }) => entries.map(({ path, linkName }) => `import * as ${linkName} from '${path}'`).join(';\\n'))\n .join('
|
|
1
|
+
{"version":3,"names":["generateComponentLink","modules","links","map","prefix","paths","name","entries","path","idx","toWindowsCompatiblePath","linkName","importStr","join","exportsString","entry"],"sources":["generate-component-link.ts"],"sourcesContent":["import { toWindowsCompatiblePath } from '@teambit/toolbox.path.to-windows-compatible-path';\n\nexport type ModuleVar = {\n prefix: string;\n paths: string[];\n};\n\nexport function generateComponentLink(modules: ModuleVar[]): string {\n const links = modules.map(({ prefix, paths }) => ({\n name: prefix,\n entries: paths.map((path, idx) => ({\n path: toWindowsCompatiblePath(path),\n linkName: `${prefix}_${idx}`,\n })),\n }));\n\n // import per preview file\n const importStr: string = links\n .map(({ entries }) => entries.map(({ path, linkName }) => `import * as ${linkName} from '${path}'`).join(';\\n'))\n .join(';\\n');\n\n // export files group per preview\n const exportsString: string = links\n .map(({ name, entries }) => `export const ${name} = [${entries.map((entry) => entry.linkName).join(', ')}]`)\n .join(';\\n');\n\n return `${importStr};\n\n${exportsString};\n`;\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAOO,SAASA,qBAAT,CAA+BC,OAA/B,EAA6D;EAClE,MAAMC,KAAK,GAAGD,OAAO,CAACE,GAAR,CAAY,CAAC;IAAEC,MAAF;IAAUC;EAAV,CAAD,MAAwB;IAChDC,IAAI,EAAEF,MAD0C;IAEhDG,OAAO,EAAEF,KAAK,CAACF,GAAN,CAAU,CAACK,IAAD,EAAOC,GAAP,MAAgB;MACjCD,IAAI,EAAE,IAAAE,sCAAA,EAAwBF,IAAxB,CAD2B;MAEjCG,QAAQ,EAAG,GAAEP,MAAO,IAAGK,GAAI;IAFM,CAAhB,CAAV;EAFuC,CAAxB,CAAZ,CAAd,CADkE,CASlE;;EACA,MAAMG,SAAiB,GAAGV,KAAK,CAC5BC,GADuB,CACnB,CAAC;IAAEI;EAAF,CAAD,KAAiBA,OAAO,CAACJ,GAAR,CAAY,CAAC;IAAEK,IAAF;IAAQG;EAAR,CAAD,KAAyB,eAAcA,QAAS,UAASH,IAAK,GAA1E,EAA8EK,IAA9E,CAAmF,KAAnF,CADE,EAEvBA,IAFuB,CAElB,KAFkB,CAA1B,CAVkE,CAclE;;EACA,MAAMC,aAAqB,GAAGZ,KAAK,CAChCC,GAD2B,CACvB,CAAC;IAAEG,IAAF;IAAQC;EAAR,CAAD,KAAwB,gBAAeD,IAAK,OAAMC,OAAO,CAACJ,GAAR,CAAaY,KAAD,IAAWA,KAAK,CAACJ,QAA7B,EAAuCE,IAAvC,CAA4C,IAA5C,CAAkD,GAD7E,EAE3BA,IAF2B,CAEtB,KAFsB,CAA9B;EAIA,OAAQ,GAAED,SAAU;AACtB;AACA,EAAEE,aAAc;AAChB,CAHE;AAID"}
|
package/html-utils.tsx
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export function loadScript({ src }: { src: string }) {
|
|
2
|
+
return new Promise<void>((resolve, reject) => {
|
|
3
|
+
const script = document.createElement('script');
|
|
4
|
+
|
|
5
|
+
script.setAttribute('defer', 'defer');
|
|
6
|
+
script.src = src;
|
|
7
|
+
|
|
8
|
+
script.onload = () => resolve();
|
|
9
|
+
script.onerror = (message, _, _1, _2, error) =>
|
|
10
|
+
reject(error || new Error(`[preview.preview] failed to load script: ${message}`));
|
|
11
|
+
|
|
12
|
+
document.head.appendChild(script);
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function loadLink({ href }: { href: string }) {
|
|
17
|
+
return new Promise<void>((resolve, reject) => {
|
|
18
|
+
const link = document.createElement('link');
|
|
19
|
+
|
|
20
|
+
if (href.endsWith('.css')) link.setAttribute('rel', 'stylesheet');
|
|
21
|
+
link.setAttribute('href', href);
|
|
22
|
+
|
|
23
|
+
link.onload = () => resolve();
|
|
24
|
+
link.onerror = (message, _, _1, _2, error) =>
|
|
25
|
+
reject(error || new Error(`[preview.preview] failed to load link: ${message}`));
|
|
26
|
+
|
|
27
|
+
document.head.appendChild(link);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
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.778",
|
|
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.778"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"mime": "2.5.2",
|
|
@@ -17,33 +17,34 @@
|
|
|
17
17
|
"object-hash": "2.1.1",
|
|
18
18
|
"cross-fetch": "3.0.6",
|
|
19
19
|
"memoizee": "0.4.15",
|
|
20
|
+
"camelcase": "6.2.0",
|
|
20
21
|
"lodash.compact": "3.0.1",
|
|
21
22
|
"graphql-request": "3.4.0",
|
|
22
23
|
"@babel/runtime": "7.12.18",
|
|
23
24
|
"core-js": "^3.0.0",
|
|
24
25
|
"@teambit/harmony": "0.3.3",
|
|
25
|
-
"@teambit/express": "0.0.
|
|
26
|
-
"@teambit/logger": "0.0.
|
|
26
|
+
"@teambit/express": "0.0.613",
|
|
27
|
+
"@teambit/logger": "0.0.608",
|
|
27
28
|
"@teambit/ui-foundation.ui.pages.static-error": "0.0.73",
|
|
28
|
-
"@teambit/builder": "0.0.
|
|
29
|
-
"@teambit/bundler": "0.0.
|
|
30
|
-
"@teambit/component": "0.0.
|
|
31
|
-
"@teambit/aspect-loader": "0.0.
|
|
32
|
-
"@teambit/dependency-resolver": "0.0.
|
|
33
|
-
"@teambit/envs": "0.0.
|
|
29
|
+
"@teambit/builder": "0.0.778",
|
|
30
|
+
"@teambit/bundler": "0.0.778",
|
|
31
|
+
"@teambit/component": "0.0.778",
|
|
32
|
+
"@teambit/aspect-loader": "0.0.778",
|
|
33
|
+
"@teambit/dependency-resolver": "0.0.778",
|
|
34
|
+
"@teambit/envs": "0.0.778",
|
|
34
35
|
"@teambit/toolbox.path.to-windows-compatible-path": "0.0.483",
|
|
35
36
|
"@teambit/component-id": "0.0.402",
|
|
36
37
|
"@teambit/bit-error": "0.0.394",
|
|
37
|
-
"@teambit/cli": "0.0.
|
|
38
|
-
"@teambit/graphql": "0.0.
|
|
39
|
-
"@teambit/pkg": "0.0.
|
|
40
|
-
"@teambit/pubsub": "0.0.
|
|
41
|
-
"@teambit/ui": "0.0.
|
|
42
|
-
"@teambit/workspace": "0.0.
|
|
43
|
-
"@teambit/compiler": "0.0.
|
|
38
|
+
"@teambit/cli": "0.0.515",
|
|
39
|
+
"@teambit/graphql": "0.0.778",
|
|
40
|
+
"@teambit/pkg": "0.0.778",
|
|
41
|
+
"@teambit/pubsub": "0.0.778",
|
|
42
|
+
"@teambit/ui": "0.0.778",
|
|
43
|
+
"@teambit/workspace": "0.0.778",
|
|
44
|
+
"@teambit/compiler": "0.0.778",
|
|
44
45
|
"@teambit/preview.cli.preview-server-status": "0.0.491",
|
|
45
46
|
"@teambit/preview.cli.webpack-events-listener": "0.0.161",
|
|
46
|
-
"@teambit/isolator": "0.0.
|
|
47
|
+
"@teambit/isolator": "0.0.778"
|
|
47
48
|
},
|
|
48
49
|
"devDependencies": {
|
|
49
50
|
"@types/mime": "2.0.3",
|
|
@@ -61,7 +62,7 @@
|
|
|
61
62
|
"@teambit/preview.aspect-docs.preview": "0.0.138"
|
|
62
63
|
},
|
|
63
64
|
"peerDependencies": {
|
|
64
|
-
"@teambit/legacy": "1.0.
|
|
65
|
+
"@teambit/legacy": "1.0.296",
|
|
65
66
|
"react-dom": "^16.8.0 || ^17.0.0",
|
|
66
67
|
"react": "^16.8.0 || ^17.0.0"
|
|
67
68
|
},
|
|
@@ -89,7 +90,7 @@
|
|
|
89
90
|
"react": "-"
|
|
90
91
|
},
|
|
91
92
|
"peerDependencies": {
|
|
92
|
-
"@teambit/legacy": "1.0.
|
|
93
|
+
"@teambit/legacy": "1.0.296",
|
|
93
94
|
"react-dom": "^16.8.0 || ^17.0.0",
|
|
94
95
|
"react": "^16.8.0 || ^17.0.0"
|
|
95
96
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.
|
|
2
|
-
import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.
|
|
1
|
+
import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.778/dist/preview.composition.js';
|
|
2
|
+
import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@0.0.778/dist/preview.docs.mdx';
|
|
3
3
|
|
|
4
4
|
export const compositions = [compositions_0];
|
|
5
|
-
export const overview = [overview_0]
|
|
5
|
+
export const overview = [overview_0];
|