@teambit/preview 1.0.186 → 1.0.187

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.
@@ -1,6 +1,6 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
2
  <testsuites tests="1" failures="0" errors="0" skipped="0">
3
- <testsuite name="teambit.preview/preview@1.0.186" tests="1" failures="0" errors="0" skipped="0">
4
- <testcase classname="dist/bundler/create-peer-link.spec.js" name="should output snapshot" time="0.004"/>
3
+ <testsuite name="teambit.preview/preview@1.0.187" tests="1" failures="0" errors="0" skipped="0">
4
+ <testcase classname="dist/bundler/create-peer-link.spec.js" name="should output snapshot" time="0.003"/>
5
5
  </testsuite>
6
6
  </testsuites>
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["teambit.preview/preview-preview"]=t():e["teambit.preview/preview-preview"]=t()}(self,(()=>(()=>{"use strict";var e={74343:(e,t,n)=>{Object.defineProperty(t,"l",{enumerable:!0,get:function(){return o.default}});var o=r(n(77106));function r(e){return e&&e.__esModule?e:{default:e}}r.__bit_component={id:"teambit.preview/aspect-docs/preview@0.0.167",homepage:"https://bit.cloud/teambit/preview/aspect-docs/preview",exported:!0}},77106:(e,t,n)=>{var o={id:"teambit.preview/aspect-docs/preview@0.0.167",homepage:"https://bit.cloud/teambit/preview/aspect-docs/preview",exported:!0};Object.defineProperty(t,"__esModule",{value:!0}),t.default=m,a(n(41594));var r=n(5016),i=["components"];function a(e){return e&&e.__esModule?e:{default:e}}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},s.apply(this,arguments)}function p(e,t){if(null==e)return{};var n,o,r=d(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function d(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r}a.__bit_component=o,s.__bit_component=o,p.__bit_component=o,d.__bit_component=o;var l={},c="wrapper";function m(e){var t=e.components,n=p(e,i);return(0,r.mdx)(c,s({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.mdx)("p",null,"The Preview aspect handles the bundling and rendering of component compositions and documentation, for the Workspace UI and Scope UI."),(0,r.mdx)("p",null,"Preview is used to display components in development (on ",(0,r.mdx)("inlineCode",{parentName:"p"},"bit start"),") as well as in their released versions (assets for the release version are generated as part of the build process)."),(0,r.mdx)("p",null,"The Preview aspect handles each component according to the configurations set by the environment that is used by that component. That means both the documentation and the component compositions will be bundled and displayed differently for different environments."),(0,r.mdx)("h2",null,"Rational"),(0,r.mdx)("p",null,"In a standard web application, UI components ",(0,r.mdx)("em",{parentName:"p"},"serving the same application")," are bundled together to produce the necessary assets to make them renderable by the browser."),(0,r.mdx)("p",null,"Components in a Bit workspace are not all in the service of the same application. Each component is authored, tagged and exported as an independent component.\nThat means a few things:"),(0,r.mdx)("ol",null,(0,r.mdx)("li",{parentName:"ol"},(0,r.mdx)("p",{parentName:"li"},"Components in a Bit workspace are not consumed ,directly or indirectly, by a single entry file (e.g, the app's ",(0,r.mdx)("inlineCode",{parentName:"p"},"index.js"),"). That makes it impossible for the bundler to follow the files needed to be bundled.")),(0,r.mdx)("li",{parentName:"ol"},(0,r.mdx)("p",{parentName:"li"},"Different components in a single workspace may be implemented using different technologies and bundled using different configurations or even different bundlers."))),(0,r.mdx)("p",null,"Preview solves the above challenges by creating a temporary entry file for each group of components using the same environment.\nIt then serves this file to the Bundler, to be bundled according to the environment and the purpose of bundling. That is, to display components in development or to display the components' release versions (for a \"production-level\" exhibition of the component's documentation and compositions)."),(0,r.mdx)("h2",null,"Usage"),(0,r.mdx)("h3",null,"Extending the Preview aspect"),(0,r.mdx)("p",null,"The preview aspect can be extended to generate other renderable artifacts , either when running Bit's development server or as part of the build pipeline (for a component's tagged version).\nThese artifacts can present additional information that assists in inspecting a component (for example, showing the results of accessibility tests)."))}m.__bit_component=o,m.isMDXComponent=!0},74124:(e,t,n)=>{var o={id:"teambit.preview/preview@1.0.186",homepage:"https://bit.cloud/teambit/preview/preview",exported:!0};function r(){const e=i(n(41594));return r=function(){return e},e}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Logo=void 0,r.__bit_component=o,i.__bit_component=o;const a=()=>r().default.createElement("div",{style:{height:"100%",display:"flex",justifyContent:"center"}},r().default.createElement("img",{style:{width:70},src:"https://static.bit.dev/extensions-icons/preview.svg"}));a.__bit_component=o,t.Logo=a},5016:e=>{e.exports=MdxJsReact},41594:e=>{e.exports=React}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};return(()=>{n.r(o),n.d(o,{compositions:()=>m,compositions_metadata:()=>f,overview:()=>u});var e={};n.r(e),n.d(e,{default:()=>c});var t=n(74124),r=(n(41594),n(5016));const i=TeambitMdxUiMdxScopeContext;var a=n(74343),s=["components"];function p(){return p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},p.apply(this,arguments)}var d={},l="wrapper";function c(e){var t=e.components,n=function(e,t){if(null==e)return{};var n,o,r=function(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(e,s);return(0,r.mdx)(l,p({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.mdx)(i.MDXScopeProvider,{components:{Preview:a.l},mdxType:"MDXScopeProvider"},(0,r.mdx)(a.l,{mdxType:"Preview"})))}c.isMDXComponent=!0;const m=[t],u=[e],f={compositions:[{displayName:"Logo",identifier:"Logo"}]}})(),o})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["teambit.preview/preview-preview"]=t():e["teambit.preview/preview-preview"]=t()}(self,(()=>(()=>{"use strict";var e={74343:(e,t,n)=>{Object.defineProperty(t,"l",{enumerable:!0,get:function(){return o.default}});var o=r(n(77106));function r(e){return e&&e.__esModule?e:{default:e}}r.__bit_component={id:"teambit.preview/aspect-docs/preview@0.0.167",homepage:"https://bit.cloud/teambit/preview/aspect-docs/preview",exported:!0}},77106:(e,t,n)=>{var o={id:"teambit.preview/aspect-docs/preview@0.0.167",homepage:"https://bit.cloud/teambit/preview/aspect-docs/preview",exported:!0};Object.defineProperty(t,"__esModule",{value:!0}),t.default=m,a(n(41594));var r=n(5016),i=["components"];function a(e){return e&&e.__esModule?e:{default:e}}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},s.apply(this,arguments)}function p(e,t){if(null==e)return{};var n,o,r=d(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function d(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r}a.__bit_component=o,s.__bit_component=o,p.__bit_component=o,d.__bit_component=o;var l={},c="wrapper";function m(e){var t=e.components,n=p(e,i);return(0,r.mdx)(c,s({},l,n,{components:t,mdxType:"MDXLayout"}),(0,r.mdx)("p",null,"The Preview aspect handles the bundling and rendering of component compositions and documentation, for the Workspace UI and Scope UI."),(0,r.mdx)("p",null,"Preview is used to display components in development (on ",(0,r.mdx)("inlineCode",{parentName:"p"},"bit start"),") as well as in their released versions (assets for the release version are generated as part of the build process)."),(0,r.mdx)("p",null,"The Preview aspect handles each component according to the configurations set by the environment that is used by that component. That means both the documentation and the component compositions will be bundled and displayed differently for different environments."),(0,r.mdx)("h2",null,"Rational"),(0,r.mdx)("p",null,"In a standard web application, UI components ",(0,r.mdx)("em",{parentName:"p"},"serving the same application")," are bundled together to produce the necessary assets to make them renderable by the browser."),(0,r.mdx)("p",null,"Components in a Bit workspace are not all in the service of the same application. Each component is authored, tagged and exported as an independent component.\nThat means a few things:"),(0,r.mdx)("ol",null,(0,r.mdx)("li",{parentName:"ol"},(0,r.mdx)("p",{parentName:"li"},"Components in a Bit workspace are not consumed ,directly or indirectly, by a single entry file (e.g, the app's ",(0,r.mdx)("inlineCode",{parentName:"p"},"index.js"),"). That makes it impossible for the bundler to follow the files needed to be bundled.")),(0,r.mdx)("li",{parentName:"ol"},(0,r.mdx)("p",{parentName:"li"},"Different components in a single workspace may be implemented using different technologies and bundled using different configurations or even different bundlers."))),(0,r.mdx)("p",null,"Preview solves the above challenges by creating a temporary entry file for each group of components using the same environment.\nIt then serves this file to the Bundler, to be bundled according to the environment and the purpose of bundling. That is, to display components in development or to display the components' release versions (for a \"production-level\" exhibition of the component's documentation and compositions)."),(0,r.mdx)("h2",null,"Usage"),(0,r.mdx)("h3",null,"Extending the Preview aspect"),(0,r.mdx)("p",null,"The preview aspect can be extended to generate other renderable artifacts , either when running Bit's development server or as part of the build pipeline (for a component's tagged version).\nThese artifacts can present additional information that assists in inspecting a component (for example, showing the results of accessibility tests)."))}m.__bit_component=o,m.isMDXComponent=!0},91749:(e,t,n)=>{var o={id:"teambit.preview/preview@1.0.187",homepage:"https://bit.cloud/teambit/preview/preview",exported:!0};function r(){const e=i(n(41594));return r=function(){return e},e}function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Logo=void 0,r.__bit_component=o,i.__bit_component=o;const a=()=>r().default.createElement("div",{style:{height:"100%",display:"flex",justifyContent:"center"}},r().default.createElement("img",{style:{width:70},src:"https://static.bit.dev/extensions-icons/preview.svg"}));a.__bit_component=o,t.Logo=a},5016:e=>{e.exports=MdxJsReact},41594:e=>{e.exports=React}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var o in t)n.o(t,o)&&!n.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var o={};return(()=>{n.r(o),n.d(o,{compositions:()=>m,compositions_metadata:()=>f,overview:()=>u});var e={};n.r(e),n.d(e,{default:()=>c});var t=n(91749),r=(n(41594),n(5016));const i=TeambitMdxUiMdxScopeContext;var a=n(74343),s=["components"];function p(){return p=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},p.apply(this,arguments)}var d={},l="wrapper";function c(e){var t=e.components,n=function(e,t){if(null==e)return{};var n,o,r=function(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}(e,s);return(0,r.mdx)(l,p({},d,n,{components:t,mdxType:"MDXLayout"}),(0,r.mdx)(i.MDXScopeProvider,{components:{Preview:a.l},mdxType:"MDXScopeProvider"},(0,r.mdx)(a.l,{mdxType:"Preview"})))}c.isMDXComponent=!0;const m=[t],u=[e],f={compositions:[{displayName:"Logo",identifier:"Logo"}]}})(),o})()));
@@ -218,7 +218,7 @@
218
218
  "_legacy": {
219
219
  "scope": "teambit.preview",
220
220
  "name": "preview",
221
- "version": "1.0.186"
221
+ "version": "1.0.187"
222
222
  },
223
223
  "_scope": "teambit.preview"
224
224
  }
@@ -6053,7 +6053,7 @@
6053
6053
  "_legacy": {
6054
6054
  "scope": "teambit.preview",
6055
6055
  "name": "preview",
6056
- "version": "1.0.186"
6056
+ "version": "1.0.187"
6057
6057
  },
6058
6058
  "_scope": "teambit.preview"
6059
6059
  }
@@ -12711,7 +12711,7 @@
12711
12711
  "componentId": {
12712
12712
  "scope": "teambit.preview",
12713
12713
  "name": "preview",
12714
- "version": "1.0.186"
12714
+ "version": "1.0.187"
12715
12715
  },
12716
12716
  "taggedModuleExports": []
12717
12717
  }
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@1.0.186/dist/preview.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@1.0.186/dist/preview.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@1.0.187/dist/preview.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.preview_preview@1.0.187/dist/preview.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -4,6 +4,14 @@ import { ProxyEntry, StartPlugin, StartPluginOptions, UiMain } from '@teambit/ui
4
4
  import { Workspace } from '@teambit/workspace';
5
5
  import { Logger } from '@teambit/logger';
6
6
  import { WatcherMain } from '@teambit/watcher';
7
+ type ServerState = {
8
+ isCompiling?: boolean;
9
+ isReady?: boolean;
10
+ errors?: Error[];
11
+ warnings?: Error[];
12
+ results?: any[];
13
+ };
14
+ type ServerStateMap = Record<string, ServerState>;
7
15
  export declare class PreviewStartPlugin implements StartPlugin {
8
16
  private workspace;
9
17
  private bundler;
@@ -13,13 +21,15 @@ export declare class PreviewStartPlugin implements StartPlugin {
13
21
  private watcher;
14
22
  constructor(workspace: Workspace, bundler: BundlerMain, ui: UiMain, pubsub: PubsubMain, logger: Logger, watcher: WatcherMain);
15
23
  previewServers: ComponentServer[];
24
+ serversState: ServerStateMap;
25
+ serversMap: Record<string, ComponentServer>;
16
26
  initiate(options: StartPluginOptions): Promise<void>;
17
27
  getProxy(): ProxyEntry[];
18
28
  private listenToDevServers;
29
+ private handleOnStartCompiling;
30
+ private handleOnDoneCompiling;
19
31
  private setReady;
20
32
  private readyPromise;
21
33
  get whenReady(): Promise<void>;
22
- private initialState;
23
- private updateServers;
24
- render: () => JSX.Element;
25
34
  }
35
+ export {};
@@ -4,13 +4,6 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.PreviewStartPlugin = void 0;
7
- function _react() {
8
- const data = _interopRequireWildcard(require("react"));
9
- _react = function () {
10
- return data;
11
- };
12
- return data;
13
- }
14
7
  function _lodash() {
15
8
  const data = require("lodash");
16
9
  _lodash = function () {
@@ -19,15 +12,8 @@ function _lodash() {
19
12
  return data;
20
13
  }
21
14
  function _previewCli() {
22
- const data = require("@teambit/preview.cli.preview-server-status");
23
- _previewCli = function () {
24
- return data;
25
- };
26
- return data;
27
- }
28
- function _previewCli2() {
29
15
  const data = require("@teambit/preview.cli.webpack-events-listener");
30
- _previewCli2 = function () {
16
+ _previewCli = function () {
31
17
  return data;
32
18
  };
33
19
  return data;
@@ -46,10 +32,14 @@ function _watcher() {
46
32
  };
47
33
  return data;
48
34
  }
49
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
50
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
51
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
52
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
35
+ function _chalk() {
36
+ const data = _interopRequireDefault(require("chalk"));
37
+ _chalk = function () {
38
+ return data;
39
+ };
40
+ return data;
41
+ }
42
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
53
43
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
54
44
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
55
45
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
@@ -62,36 +52,22 @@ class PreviewStartPlugin {
62
52
  this.logger = logger;
63
53
  this.watcher = watcher;
64
54
  _defineProperty(this, "previewServers", []);
55
+ _defineProperty(this, "serversState", {});
56
+ _defineProperty(this, "serversMap", {});
65
57
  _defineProperty(this, "setReady", void 0);
66
58
  _defineProperty(this, "readyPromise", new Promise(resolve => this.setReady = resolve));
67
- _defineProperty(this, "initialState", {});
68
- // implements react-like setter (value or updater)
69
- _defineProperty(this, "updateServers", servers => {
70
- this.initialState = typeof servers === 'function' ? servers(this.initialState) : servers;
71
- return servers;
72
- });
73
- _defineProperty(this, "render", () => {
74
- const [servers, setServers] = (0, _react().useState)(this.initialState);
75
- this.updateServers = setServers;
76
- this.initialState = {};
77
- (0, _react().useEffect)(() => {
78
- const noneAreCompiling = Object.values(servers).every(x => !x.compiling);
79
- if (noneAreCompiling) this.setReady();
80
- }, [servers]);
81
- return /*#__PURE__*/_react().default.createElement(_previewCli().PreviewServerStatus, {
82
- previewServers: this.previewServers,
83
- serverStats: servers
84
- });
85
- });
86
59
  }
87
60
  async initiate(options) {
88
61
  this.listenToDevServers();
89
62
  const components = await this.workspace.getComponentsByUserInput(!options.pattern, options.pattern);
90
63
  // TODO: logic for creating preview servers must be refactored to this aspect from the DevServer aspect.
91
64
  const previewServers = await this.bundler.devServer(components);
92
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
93
- previewServers.forEach(server => server.listen());
94
- // DON'T add wait! this promise never resolves, so it would stop the start process!
65
+ previewServers.forEach(server => {
66
+ this.serversMap[server.context.envRuntime.id] = server;
67
+ // DON'T add wait! this promise never resolves, so it would stop the start process!
68
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
69
+ server.listen();
70
+ });
95
71
  this.watcher.watch({
96
72
  spawnTSServer: true,
97
73
  checkTypes: _watcher().CheckTypes.None,
@@ -122,25 +98,106 @@ class PreviewStartPlugin {
122
98
  // TODO: this should be a part of the devServer
123
99
  listenToDevServers() {
124
100
  // keep state changes immutable!
125
- (0, _previewCli2().SubscribeToWebpackEvents)(this.pubsub, {
101
+ (0, _previewCli().SubscribeToWebpackEvents)(this.pubsub, {
126
102
  onStart: id => {
127
- this.updateServers(state => _objectSpread(_objectSpread({}, state), {}, {
128
- [id]: {
129
- compiling: true
130
- }
131
- }));
103
+ this.handleOnStartCompiling(id);
132
104
  },
133
105
  onDone: (id, results) => {
134
- this.updateServers(state => _objectSpread(_objectSpread({}, state), {}, {
135
- [id]: results
136
- }));
106
+ this.handleOnDoneCompiling(id, results);
137
107
  }
138
108
  });
139
109
  }
110
+ handleOnStartCompiling(id) {
111
+ this.serversState[id] = {
112
+ isCompiling: true
113
+ };
114
+ const spinnerId = getSpinnerId(id);
115
+ const text = getSpinnerCompilingMessage(this.serversMap[id]);
116
+ this.logger.multiSpinner.add(spinnerId, {
117
+ text
118
+ });
119
+ }
120
+ handleOnDoneCompiling(id, results) {
121
+ this.serversState[id] = {
122
+ isCompiling: false,
123
+ isReady: true,
124
+ errors: results.errors,
125
+ warnings: results.warnings
126
+ };
127
+ const previewServer = this.serversMap[id];
128
+ const spinnerId = getSpinnerId(id);
129
+ const errors = results.errors || [];
130
+ const hasErrors = !!errors.length;
131
+ const warnings = getWarningsWithoutIgnored(results.warnings);
132
+ const hasWarnings = !!warnings.length;
133
+ const url = `http://localhost:${previewServer.port}`;
134
+ const text = getSpinnerDoneMessage(this.serversMap[id], errors, warnings, url);
135
+ if (hasErrors) {
136
+ this.logger.multiSpinner.fail(spinnerId, {
137
+ text
138
+ });
139
+ } else if (hasWarnings) {
140
+ this.logger.multiSpinner.warn(spinnerId, {
141
+ text
142
+ });
143
+ } else {
144
+ this.logger.multiSpinner.succeed(spinnerId, {
145
+ text
146
+ });
147
+ }
148
+ const noneAreCompiling = Object.values(this.serversState).every(x => !x.isCompiling);
149
+ if (noneAreCompiling) this.setReady();
150
+ }
140
151
  get whenReady() {
141
152
  return this.readyPromise;
142
153
  }
143
154
  }
144
155
  exports.PreviewStartPlugin = PreviewStartPlugin;
156
+ function getWarningsWithoutIgnored(warnings) {
157
+ if (!warnings || !warnings.length) return [];
158
+ const IGNORE_WARNINGS = [
159
+ // Webpack 5+ has no facility to disable this warning.
160
+ // System.import is used in @angular/core for deprecated string-form lazy routes
161
+ /System.import\(\) is deprecated and will be removed soon/i,
162
+ // We need to include all the files in the compilation because we don't know what people will use in their compositions
163
+ /is part of the TypeScript compilation but it's unused/i,
164
+ // https://github.com/webpack-contrib/source-map-loader/blob/b2de4249c7431dd8432da607e08f0f65e9d64219/src/index.js#L83
165
+ /Failed to parse source map from/];
166
+ warnings.filter(warning => !IGNORE_WARNINGS.find(reg => warning?.message?.match(reg)));
167
+ return warnings;
168
+ }
169
+ function getSpinnerId(envId) {
170
+ return `preview-${envId}`;
171
+ }
172
+ function getSpinnerCompilingMessage(server, verbose = false) {
173
+ const prefix = 'COMPILING';
174
+ const envId = _chalk().default.cyan(server.context.envRuntime.id);
175
+ let includedEnvs = '';
176
+ if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {
177
+ includedEnvs = `on behalf of ${_chalk().default.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;
178
+ }
179
+ return `${prefix} ${envId} ${includedEnvs}`;
180
+ }
181
+ function getSpinnerDoneMessage(server, errors, warnings, url, verbose = false) {
182
+ const hasErrors = !!errors.length;
183
+ const hasWarnings = !!warnings.length;
184
+ const prefix = hasErrors ? 'FAILED' : 'RUNNING';
185
+ const envId = _chalk().default.cyan(server.context.envRuntime.id);
186
+ let includedEnvs = '';
187
+ if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {
188
+ includedEnvs = ` on behalf of ${_chalk().default.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;
189
+ }
190
+ const errorsTxt = hasErrors ? errors.map(err => err.message).join('\n') : '';
191
+ const errorsTxtWithTitle = hasErrors ? _chalk().default.red(`\nErrors:\n${errorsTxt}`) : '';
192
+ const warningsTxt = hasWarnings ? warnings.map(warning => warning.message).join('\n') : '';
193
+ const warningsTxtWithTitle = hasWarnings ? _chalk().default.yellow(`\nWarnings:\n${warningsTxt}`) : '';
194
+ const urlMessage = hasErrors ? '' : `at ${_chalk().default.cyan(url)}`;
195
+ return `${prefix} ${envId}${includedEnvs} ${urlMessage} ${errorsTxtWithTitle} ${warningsTxtWithTitle}`;
196
+ }
197
+ function stringifyIncludedEnvs(includedEnvs = [], verbose = false) {
198
+ if (includedEnvs.length < 2) return '';
199
+ if (includedEnvs.length > 2 && !verbose) return ` ${includedEnvs.length} other envs`;
200
+ return includedEnvs.join(', ');
201
+ }
145
202
 
146
203
  //# sourceMappingURL=preview.start-plugin.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_react","data","_interopRequireWildcard","require","_lodash","_previewCli","_previewCli2","_compiler","_watcher","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","prototype","hasOwnProperty","call","i","set","ownKeys","keys","getOwnPropertySymbols","o","filter","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","obj","key","value","_toPropertyKey","configurable","writable","_toPrimitive","String","Symbol","toPrimitive","TypeError","Number","PreviewStartPlugin","constructor","workspace","bundler","ui","pubsub","logger","watcher","Promise","resolve","setReady","servers","initialState","setServers","useState","updateServers","useEffect","noneAreCompiling","values","every","x","compiling","createElement","PreviewServerStatus","previewServers","serverStats","initiate","options","listenToDevServers","components","getComponentsByUserInput","pattern","devServer","server","listen","watch","spawnTSServer","checkTypes","CheckTypes","None","preCompile","compile","initiator","CompilationInitiator","Start","catch","err","msg","error","console","message","concat","getProxy","proxyConfigs","map","context","envRuntime","id","target","port","ws","flatten","SubscribeToWebpackEvents","onStart","state","onDone","results","whenReady","readyPromise","exports"],"sources":["preview.start-plugin.tsx"],"sourcesContent":["import React, { useState, useEffect, Dispatch, SetStateAction } from 'react';\nimport { flatten } from 'lodash';\nimport { PreviewServerStatus } from '@teambit/preview.cli.preview-server-status';\nimport { BundlerMain, ComponentServer } from '@teambit/bundler';\nimport { PubsubMain } from '@teambit/pubsub';\nimport { ProxyEntry, StartPlugin, StartPluginOptions, UiMain } from '@teambit/ui';\nimport { Workspace } from '@teambit/workspace';\nimport { SubscribeToWebpackEvents, CompilationResult } from '@teambit/preview.cli.webpack-events-listener';\nimport { CompilationInitiator } from '@teambit/compiler';\nimport { Logger } from '@teambit/logger';\nimport { CheckTypes, WatcherMain } from '@teambit/watcher';\n\ntype CompilationServers = Record<string, CompilationResult>;\ntype ServersSetter = Dispatch<SetStateAction<CompilationServers>>;\n\nexport class PreviewStartPlugin implements StartPlugin {\n constructor(\n private workspace: Workspace,\n private bundler: BundlerMain,\n private ui: UiMain,\n private pubsub: PubsubMain,\n private logger: Logger,\n private watcher: WatcherMain\n ) {}\n\n previewServers: ComponentServer[] = [];\n\n async initiate(options: StartPluginOptions) {\n this.listenToDevServers();\n\n const components = await this.workspace.getComponentsByUserInput(!options.pattern, options.pattern);\n // TODO: logic for creating preview servers must be refactored to this aspect from the DevServer aspect.\n const previewServers = await this.bundler.devServer(components);\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n previewServers.forEach((server) => server.listen());\n // DON'T add wait! this promise never resolves, so it would stop the start process!\n this.watcher\n .watch({\n spawnTSServer: true,\n checkTypes: CheckTypes.None,\n preCompile: false,\n compile: true,\n initiator: CompilationInitiator.Start,\n })\n .catch((err) => {\n const msg = `watcher found an error`;\n this.logger.error(msg, err);\n this.logger.console(`${msg}, ${err.message}`);\n });\n this.previewServers = this.previewServers.concat(previewServers);\n }\n\n getProxy(): ProxyEntry[] {\n const proxyConfigs = this.previewServers.map<ProxyEntry[]>((server) => {\n return [\n {\n context: [`/preview/${server.context.envRuntime.id}`],\n target: `http://localhost:${server.port}`,\n },\n {\n context: [`/_hmr/${server.context.envRuntime.id}`],\n target: `http://localhost:${server.port}`,\n ws: true,\n },\n ];\n });\n\n return flatten(proxyConfigs);\n }\n\n // TODO: this should be a part of the devServer\n private listenToDevServers() {\n // keep state changes immutable!\n SubscribeToWebpackEvents(this.pubsub, {\n onStart: (id) => {\n this.updateServers((state) => ({\n ...state,\n [id]: { compiling: true },\n }));\n },\n onDone: (id, results) => {\n this.updateServers((state) => ({\n ...state,\n [id]: results,\n }));\n },\n });\n }\n\n private setReady: () => void;\n private readyPromise = new Promise<void>((resolve) => (this.setReady = resolve));\n get whenReady(): Promise<void> {\n return this.readyPromise;\n }\n\n private initialState: CompilationServers = {};\n // implements react-like setter (value or updater)\n private updateServers: ServersSetter = (servers) => {\n this.initialState = typeof servers === 'function' ? servers(this.initialState) : servers;\n return servers;\n };\n\n render = () => {\n const [servers, setServers] = useState<CompilationServers>(this.initialState);\n this.updateServers = setServers;\n this.initialState = {};\n\n useEffect(() => {\n const noneAreCompiling = Object.values(servers).every((x) => !x.compiling);\n if (noneAreCompiling) this.setReady();\n }, [servers]);\n\n return <PreviewServerStatus previewServers={this.previewServers} serverStats={servers} />;\n };\n}\n"],"mappings":";;;;;;AAAA,SAAAA,OAAA;EAAA,MAAAC,IAAA,GAAAC,uBAAA,CAAAC,OAAA;EAAAH,MAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,QAAA;EAAA,MAAAH,IAAA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,MAAM,EAAG,oBAAmBzB,MAAM,CAAC0B,IAAK,EAAC;QACzCC,EAAE,EAAE;MACN,CAAC,CACF;IACH,CAAC,CAAC;IAEF,OAAO,IAAAC,iBAAO,EAACR,YAAY,CAAC;EAC9B;;EAEA;EACQzB,kBAAkBA,CAAA,EAAG;IAC3B;IACA,IAAAkC,uCAAwB,EAAC,IAAI,CAACzD,MAAM,EAAE;MACpC0D,OAAO,EAAGN,EAAE,IAAK;QACf,IAAI,CAAC1C,aAAa,CAAEiD,KAAK,IAAAnF,aAAA,CAAAA,aAAA,KACpBmF,KAAK;UACR,CAACP,EAAE,GAAG;YAAEpC,SAAS,EAAE;UAAK;QAAC,EACzB,CAAC;MACL,CAAC;MACD4C,MAAM,EAAEA,CAACR,EAAE,EAAES,OAAO,KAAK;QACvB,IAAI,CAACnD,aAAa,CAAEiD,KAAK,IAAAnF,aAAA,CAAAA,aAAA,KACpBmF,KAAK;UACR,CAACP,EAAE,GAAGS;QAAO,EACb,CAAC;MACL;IACF,CAAC,CAAC;EACJ;EAIA,IAAIC,SAASA,CAAA,EAAkB;IAC7B,OAAO,IAAI,CAACC,YAAY;EAC1B;AAqBF;AAACC,OAAA,CAAArE,kBAAA,GAAAA,kBAAA"}
1
+ {"version":3,"names":["_lodash","data","require","_previewCli","_compiler","_watcher","_chalk","_interopRequireDefault","obj","__esModule","default","_defineProperty","key","value","_toPropertyKey","Object","defineProperty","enumerable","configurable","writable","t","i","_toPrimitive","String","r","e","Symbol","toPrimitive","call","TypeError","Number","PreviewStartPlugin","constructor","workspace","bundler","ui","pubsub","logger","watcher","Promise","resolve","setReady","initiate","options","listenToDevServers","components","getComponentsByUserInput","pattern","previewServers","devServer","forEach","server","serversMap","context","envRuntime","id","listen","watch","spawnTSServer","checkTypes","CheckTypes","None","preCompile","compile","initiator","CompilationInitiator","Start","catch","err","msg","error","console","message","concat","getProxy","proxyConfigs","map","target","port","ws","flatten","SubscribeToWebpackEvents","onStart","handleOnStartCompiling","onDone","results","handleOnDoneCompiling","serversState","isCompiling","spinnerId","getSpinnerId","text","getSpinnerCompilingMessage","multiSpinner","add","isReady","errors","warnings","previewServer","hasErrors","length","getWarningsWithoutIgnored","hasWarnings","url","getSpinnerDoneMessage","fail","warn","succeed","noneAreCompiling","values","every","x","whenReady","readyPromise","exports","IGNORE_WARNINGS","filter","warning","find","reg","match","envId","verbose","prefix","chalk","cyan","includedEnvs","relatedContexts","stringifyIncludedEnvs","errorsTxt","join","errorsTxtWithTitle","red","warningsTxt","warningsTxtWithTitle","yellow","urlMessage"],"sources":["preview.start-plugin.tsx"],"sourcesContent":["import { flatten } from 'lodash';\nimport { BundlerMain, ComponentServer } from '@teambit/bundler';\nimport { PubsubMain } from '@teambit/pubsub';\nimport { ProxyEntry, StartPlugin, StartPluginOptions, UiMain } from '@teambit/ui';\nimport { Workspace } from '@teambit/workspace';\nimport { SubscribeToWebpackEvents, CompilationResult } from '@teambit/preview.cli.webpack-events-listener';\nimport { CompilationInitiator } from '@teambit/compiler';\nimport { Logger } from '@teambit/logger';\nimport { CheckTypes, WatcherMain } from '@teambit/watcher';\nimport chalk from 'chalk';\n\ntype ServerState = {\n isCompiling?: boolean;\n isReady?: boolean;\n errors?: Error[];\n warnings?: Error[];\n results?: any[];\n};\n\ntype ServerStateMap = Record<string, ServerState>;\n\nexport class PreviewStartPlugin implements StartPlugin {\n constructor(\n private workspace: Workspace,\n private bundler: BundlerMain,\n private ui: UiMain,\n private pubsub: PubsubMain,\n private logger: Logger,\n private watcher: WatcherMain\n ) {}\n\n previewServers: ComponentServer[] = [];\n serversState: ServerStateMap = {};\n serversMap: Record<string, ComponentServer> = {};\n\n async initiate(options: StartPluginOptions) {\n this.listenToDevServers();\n\n const components = await this.workspace.getComponentsByUserInput(!options.pattern, options.pattern);\n // TODO: logic for creating preview servers must be refactored to this aspect from the DevServer aspect.\n const previewServers = await this.bundler.devServer(components);\n previewServers.forEach((server) => {\n this.serversMap[server.context.envRuntime.id] = server;\n // DON'T add wait! this promise never resolves, so it would stop the start process!\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n server.listen();\n });\n this.watcher\n .watch({\n spawnTSServer: true,\n checkTypes: CheckTypes.None,\n preCompile: false,\n compile: true,\n initiator: CompilationInitiator.Start,\n })\n .catch((err) => {\n const msg = `watcher found an error`;\n this.logger.error(msg, err);\n this.logger.console(`${msg}, ${err.message}`);\n });\n this.previewServers = this.previewServers.concat(previewServers);\n }\n\n getProxy(): ProxyEntry[] {\n const proxyConfigs = this.previewServers.map<ProxyEntry[]>((server) => {\n return [\n {\n context: [`/preview/${server.context.envRuntime.id}`],\n target: `http://localhost:${server.port}`,\n },\n {\n context: [`/_hmr/${server.context.envRuntime.id}`],\n target: `http://localhost:${server.port}`,\n ws: true,\n },\n ];\n });\n\n return flatten(proxyConfigs);\n }\n\n // TODO: this should be a part of the devServer\n private listenToDevServers() {\n // keep state changes immutable!\n SubscribeToWebpackEvents(this.pubsub, {\n onStart: (id) => {\n this.handleOnStartCompiling(id);\n },\n onDone: (id, results) => {\n this.handleOnDoneCompiling(id, results);\n },\n });\n }\n\n private handleOnStartCompiling(id: string) {\n this.serversState[id] = { isCompiling: true };\n const spinnerId = getSpinnerId(id);\n const text = getSpinnerCompilingMessage(this.serversMap[id]);\n this.logger.multiSpinner.add(spinnerId, { text });\n }\n\n private handleOnDoneCompiling(id: string, results: CompilationResult) {\n this.serversState[id] = {\n isCompiling: false,\n isReady: true,\n errors: results.errors,\n warnings: results.warnings,\n };\n const previewServer = this.serversMap[id];\n const spinnerId = getSpinnerId(id);\n const errors = results.errors || [];\n const hasErrors = !!errors.length;\n const warnings = getWarningsWithoutIgnored(results.warnings);\n const hasWarnings = !!warnings.length;\n const url = `http://localhost:${previewServer.port}`;\n const text = getSpinnerDoneMessage(this.serversMap[id], errors, warnings, url);\n if (hasErrors) {\n this.logger.multiSpinner.fail(spinnerId, { text });\n } else if (hasWarnings) {\n this.logger.multiSpinner.warn(spinnerId, { text });\n } else {\n this.logger.multiSpinner.succeed(spinnerId, { text });\n }\n\n const noneAreCompiling = Object.values(this.serversState).every((x) => !x.isCompiling);\n if (noneAreCompiling) this.setReady();\n }\n\n private setReady: () => void;\n private readyPromise = new Promise<void>((resolve) => (this.setReady = resolve));\n get whenReady(): Promise<void> {\n return this.readyPromise;\n }\n}\n\nfunction getWarningsWithoutIgnored(warnings?: Error[]): Error[] {\n if (!warnings || !warnings.length) return [];\n const IGNORE_WARNINGS = [\n // Webpack 5+ has no facility to disable this warning.\n // System.import is used in @angular/core for deprecated string-form lazy routes\n /System.import\\(\\) is deprecated and will be removed soon/i,\n // We need to include all the files in the compilation because we don't know what people will use in their compositions\n /is part of the TypeScript compilation but it's unused/i,\n // https://github.com/webpack-contrib/source-map-loader/blob/b2de4249c7431dd8432da607e08f0f65e9d64219/src/index.js#L83\n /Failed to parse source map from/,\n ];\n warnings.filter((warning) => !IGNORE_WARNINGS.find((reg) => warning?.message?.match(reg)));\n return warnings;\n}\n\nfunction getSpinnerId(envId: string) {\n return `preview-${envId}`;\n}\n\nfunction getSpinnerCompilingMessage(server: ComponentServer, verbose = false) {\n const prefix = 'COMPILING';\n const envId = chalk.cyan(server.context.envRuntime.id);\n let includedEnvs = '';\n if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {\n includedEnvs = `on behalf of ${chalk.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;\n }\n return `${prefix} ${envId} ${includedEnvs}`;\n}\n\nfunction getSpinnerDoneMessage(\n server: ComponentServer,\n errors: Error[],\n warnings: Error[],\n url: string,\n verbose = false\n) {\n const hasErrors = !!errors.length;\n const hasWarnings = !!warnings.length;\n const prefix = hasErrors ? 'FAILED' : 'RUNNING';\n const envId = chalk.cyan(server.context.envRuntime.id);\n let includedEnvs = '';\n if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {\n includedEnvs = ` on behalf of ${chalk.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;\n }\n const errorsTxt = hasErrors ? errors.map((err) => err.message).join('\\n') : '';\n const errorsTxtWithTitle = hasErrors ? chalk.red(`\\nErrors:\\n${errorsTxt}`) : '';\n const warningsTxt = hasWarnings ? warnings.map((warning) => warning.message).join('\\n') : '';\n const warningsTxtWithTitle = hasWarnings ? chalk.yellow(`\\nWarnings:\\n${warningsTxt}`) : '';\n\n const urlMessage = hasErrors ? '' : `at ${chalk.cyan(url)}`;\n return `${prefix} ${envId}${includedEnvs} ${urlMessage} ${errorsTxtWithTitle} ${warningsTxtWithTitle}`;\n}\n\nfunction stringifyIncludedEnvs(includedEnvs: string[] = [], verbose = false) {\n if (includedEnvs.length < 2) return '';\n if (includedEnvs.length > 2 && !verbose) return ` ${includedEnvs.length} other envs`;\n return includedEnvs.join(', ');\n}\n"],"mappings":";;;;;;AAAA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAKA,SAAAE,YAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,WAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,UAAA;EAAA,MAAAH,IAAA,GAAAC,OAAA;EAAAE,SAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAEA,SAAAI,SAAA;EAAA,MAAAJ,IAAA,GAAAC,OAAA;EAAAG,QAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,OAAA;EAAA,MAAAL,IAAA,GAAAM,sBAAA,CAAAL,OAAA;EAAAI,MAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAA0B,SAAAM,uBAAAC,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,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AAC;EAC3D,OAAQ,GAAEoB,MAAO,IAAGF,KAAM,GAAEK,YAAa,IAAGU,UAAW,IAAGL,kBAAmB,IAAGG,oBAAqB,EAAC;AACxG;AAEA,SAASN,qBAAqBA,CAACF,YAAsB,GAAG,EAAE,EAAEJ,OAAO,GAAG,KAAK,EAAE;EAC3E,IAAII,YAAY,CAAC1B,MAAM,GAAG,CAAC,EAAE,OAAO,EAAE;EACtC,IAAI0B,YAAY,CAAC1B,MAAM,GAAG,CAAC,IAAI,CAACsB,OAAO,EAAE,OAAQ,IAAGI,YAAY,CAAC1B,MAAO,aAAY;EACpF,OAAO0B,YAAY,CAACI,IAAI,CAAC,IAAI,CAAC;AAChC"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/preview",
3
- "version": "1.0.186",
3
+ "version": "1.0.187",
4
4
  "homepage": "https://bit.cloud/teambit/preview/preview",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.preview",
8
8
  "name": "preview",
9
- "version": "1.0.186"
9
+ "version": "1.0.187"
10
10
  },
11
11
  "dependencies": {
12
12
  "mime": "2.5.2",
@@ -17,6 +17,7 @@
17
17
  "webpack": "5.84.1",
18
18
  "graphql-tag": "2.12.1",
19
19
  "object-hash": "2.1.1",
20
+ "chalk": "2.4.2",
20
21
  "lodash.compact": "3.0.1",
21
22
  "graphql-request": "6.1.0",
22
23
  "webpack-manifest-plugin": "5.0.0",
@@ -27,31 +28,30 @@
27
28
  "@teambit/component-id": "1.2.0",
28
29
  "@teambit/bit-error": "0.0.404",
29
30
  "@teambit/react.webpack.react-webpack": "1.0.23",
30
- "@teambit/express": "0.0.953",
31
- "@teambit/logger": "0.0.947",
32
- "@teambit/builder": "1.0.186",
33
- "@teambit/bundler": "1.0.186",
34
- "@teambit/component": "1.0.186",
31
+ "@teambit/express": "0.0.954",
32
+ "@teambit/logger": "0.0.948",
33
+ "@teambit/builder": "1.0.187",
34
+ "@teambit/bundler": "1.0.187",
35
+ "@teambit/component": "1.0.187",
35
36
  "@teambit/preview.ui.component-preview": "1.0.5",
36
- "@teambit/aspect-loader": "1.0.186",
37
- "@teambit/cli": "0.0.854",
38
- "@teambit/dependency-resolver": "1.0.186",
39
- "@teambit/envs": "1.0.186",
37
+ "@teambit/aspect-loader": "1.0.187",
38
+ "@teambit/cli": "0.0.855",
39
+ "@teambit/dependency-resolver": "1.0.187",
40
+ "@teambit/envs": "1.0.187",
40
41
  "@teambit/toolbox.path.to-windows-compatible-path": "0.0.496",
41
- "@teambit/ui": "1.0.186",
42
- "@teambit/isolator": "1.0.186",
42
+ "@teambit/ui": "1.0.187",
43
+ "@teambit/isolator": "1.0.187",
43
44
  "@teambit/harmony.modules.harmony-root-generator": "0.0.4",
44
- "@teambit/cache": "0.0.947",
45
- "@teambit/graphql": "1.0.186",
46
- "@teambit/pkg": "1.0.186",
47
- "@teambit/pubsub": "1.0.186",
48
- "@teambit/scope": "1.0.186",
49
- "@teambit/watcher": "1.0.186",
50
- "@teambit/workspace": "1.0.186",
51
- "@teambit/compiler": "1.0.186",
52
- "@teambit/preview.cli.preview-server-status": "0.0.506",
53
- "@teambit/preview.cli.webpack-events-listener": "0.0.174",
54
- "@teambit/webpack": "1.0.186"
45
+ "@teambit/cache": "0.0.948",
46
+ "@teambit/graphql": "1.0.187",
47
+ "@teambit/pkg": "1.0.187",
48
+ "@teambit/pubsub": "1.0.187",
49
+ "@teambit/scope": "1.0.187",
50
+ "@teambit/watcher": "1.0.187",
51
+ "@teambit/workspace": "1.0.187",
52
+ "@teambit/compiler": "1.0.187",
53
+ "@teambit/preview.cli.webpack-events-listener": "0.0.175",
54
+ "@teambit/webpack": "1.0.187"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/mime": "2.0.3",
@@ -1,6 +1,4 @@
1
- import React, { useState, useEffect, Dispatch, SetStateAction } from 'react';
2
1
  import { flatten } from 'lodash';
3
- import { PreviewServerStatus } from '@teambit/preview.cli.preview-server-status';
4
2
  import { BundlerMain, ComponentServer } from '@teambit/bundler';
5
3
  import { PubsubMain } from '@teambit/pubsub';
6
4
  import { ProxyEntry, StartPlugin, StartPluginOptions, UiMain } from '@teambit/ui';
@@ -9,9 +7,17 @@ import { SubscribeToWebpackEvents, CompilationResult } from '@teambit/preview.cl
9
7
  import { CompilationInitiator } from '@teambit/compiler';
10
8
  import { Logger } from '@teambit/logger';
11
9
  import { CheckTypes, WatcherMain } from '@teambit/watcher';
10
+ import chalk from 'chalk';
12
11
 
13
- type CompilationServers = Record<string, CompilationResult>;
14
- type ServersSetter = Dispatch<SetStateAction<CompilationServers>>;
12
+ type ServerState = {
13
+ isCompiling?: boolean;
14
+ isReady?: boolean;
15
+ errors?: Error[];
16
+ warnings?: Error[];
17
+ results?: any[];
18
+ };
19
+
20
+ type ServerStateMap = Record<string, ServerState>;
15
21
 
16
22
  export class PreviewStartPlugin implements StartPlugin {
17
23
  constructor(
@@ -24,6 +30,8 @@ export class PreviewStartPlugin implements StartPlugin {
24
30
  ) {}
25
31
 
26
32
  previewServers: ComponentServer[] = [];
33
+ serversState: ServerStateMap = {};
34
+ serversMap: Record<string, ComponentServer> = {};
27
35
 
28
36
  async initiate(options: StartPluginOptions) {
29
37
  this.listenToDevServers();
@@ -31,9 +39,12 @@ export class PreviewStartPlugin implements StartPlugin {
31
39
  const components = await this.workspace.getComponentsByUserInput(!options.pattern, options.pattern);
32
40
  // TODO: logic for creating preview servers must be refactored to this aspect from the DevServer aspect.
33
41
  const previewServers = await this.bundler.devServer(components);
34
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
35
- previewServers.forEach((server) => server.listen());
36
- // DON'T add wait! this promise never resolves, so it would stop the start process!
42
+ previewServers.forEach((server) => {
43
+ this.serversMap[server.context.envRuntime.id] = server;
44
+ // DON'T add wait! this promise never resolves, so it would stop the start process!
45
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
46
+ server.listen();
47
+ });
37
48
  this.watcher
38
49
  .watch({
39
50
  spawnTSServer: true,
@@ -73,43 +84,110 @@ export class PreviewStartPlugin implements StartPlugin {
73
84
  // keep state changes immutable!
74
85
  SubscribeToWebpackEvents(this.pubsub, {
75
86
  onStart: (id) => {
76
- this.updateServers((state) => ({
77
- ...state,
78
- [id]: { compiling: true },
79
- }));
87
+ this.handleOnStartCompiling(id);
80
88
  },
81
89
  onDone: (id, results) => {
82
- this.updateServers((state) => ({
83
- ...state,
84
- [id]: results,
85
- }));
90
+ this.handleOnDoneCompiling(id, results);
86
91
  },
87
92
  });
88
93
  }
89
94
 
95
+ private handleOnStartCompiling(id: string) {
96
+ this.serversState[id] = { isCompiling: true };
97
+ const spinnerId = getSpinnerId(id);
98
+ const text = getSpinnerCompilingMessage(this.serversMap[id]);
99
+ this.logger.multiSpinner.add(spinnerId, { text });
100
+ }
101
+
102
+ private handleOnDoneCompiling(id: string, results: CompilationResult) {
103
+ this.serversState[id] = {
104
+ isCompiling: false,
105
+ isReady: true,
106
+ errors: results.errors,
107
+ warnings: results.warnings,
108
+ };
109
+ const previewServer = this.serversMap[id];
110
+ const spinnerId = getSpinnerId(id);
111
+ const errors = results.errors || [];
112
+ const hasErrors = !!errors.length;
113
+ const warnings = getWarningsWithoutIgnored(results.warnings);
114
+ const hasWarnings = !!warnings.length;
115
+ const url = `http://localhost:${previewServer.port}`;
116
+ const text = getSpinnerDoneMessage(this.serversMap[id], errors, warnings, url);
117
+ if (hasErrors) {
118
+ this.logger.multiSpinner.fail(spinnerId, { text });
119
+ } else if (hasWarnings) {
120
+ this.logger.multiSpinner.warn(spinnerId, { text });
121
+ } else {
122
+ this.logger.multiSpinner.succeed(spinnerId, { text });
123
+ }
124
+
125
+ const noneAreCompiling = Object.values(this.serversState).every((x) => !x.isCompiling);
126
+ if (noneAreCompiling) this.setReady();
127
+ }
128
+
90
129
  private setReady: () => void;
91
130
  private readyPromise = new Promise<void>((resolve) => (this.setReady = resolve));
92
131
  get whenReady(): Promise<void> {
93
132
  return this.readyPromise;
94
133
  }
134
+ }
135
+
136
+ function getWarningsWithoutIgnored(warnings?: Error[]): Error[] {
137
+ if (!warnings || !warnings.length) return [];
138
+ const IGNORE_WARNINGS = [
139
+ // Webpack 5+ has no facility to disable this warning.
140
+ // System.import is used in @angular/core for deprecated string-form lazy routes
141
+ /System.import\(\) is deprecated and will be removed soon/i,
142
+ // We need to include all the files in the compilation because we don't know what people will use in their compositions
143
+ /is part of the TypeScript compilation but it's unused/i,
144
+ // https://github.com/webpack-contrib/source-map-loader/blob/b2de4249c7431dd8432da607e08f0f65e9d64219/src/index.js#L83
145
+ /Failed to parse source map from/,
146
+ ];
147
+ warnings.filter((warning) => !IGNORE_WARNINGS.find((reg) => warning?.message?.match(reg)));
148
+ return warnings;
149
+ }
150
+
151
+ function getSpinnerId(envId: string) {
152
+ return `preview-${envId}`;
153
+ }
154
+
155
+ function getSpinnerCompilingMessage(server: ComponentServer, verbose = false) {
156
+ const prefix = 'COMPILING';
157
+ const envId = chalk.cyan(server.context.envRuntime.id);
158
+ let includedEnvs = '';
159
+ if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {
160
+ includedEnvs = `on behalf of ${chalk.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;
161
+ }
162
+ return `${prefix} ${envId} ${includedEnvs}`;
163
+ }
164
+
165
+ function getSpinnerDoneMessage(
166
+ server: ComponentServer,
167
+ errors: Error[],
168
+ warnings: Error[],
169
+ url: string,
170
+ verbose = false
171
+ ) {
172
+ const hasErrors = !!errors.length;
173
+ const hasWarnings = !!warnings.length;
174
+ const prefix = hasErrors ? 'FAILED' : 'RUNNING';
175
+ const envId = chalk.cyan(server.context.envRuntime.id);
176
+ let includedEnvs = '';
177
+ if (server.context.relatedContexts && server.context.relatedContexts.length > 1) {
178
+ includedEnvs = ` on behalf of ${chalk.cyan(stringifyIncludedEnvs(server.context.relatedContexts, verbose))}`;
179
+ }
180
+ const errorsTxt = hasErrors ? errors.map((err) => err.message).join('\n') : '';
181
+ const errorsTxtWithTitle = hasErrors ? chalk.red(`\nErrors:\n${errorsTxt}`) : '';
182
+ const warningsTxt = hasWarnings ? warnings.map((warning) => warning.message).join('\n') : '';
183
+ const warningsTxtWithTitle = hasWarnings ? chalk.yellow(`\nWarnings:\n${warningsTxt}`) : '';
184
+
185
+ const urlMessage = hasErrors ? '' : `at ${chalk.cyan(url)}`;
186
+ return `${prefix} ${envId}${includedEnvs} ${urlMessage} ${errorsTxtWithTitle} ${warningsTxtWithTitle}`;
187
+ }
95
188
 
96
- private initialState: CompilationServers = {};
97
- // implements react-like setter (value or updater)
98
- private updateServers: ServersSetter = (servers) => {
99
- this.initialState = typeof servers === 'function' ? servers(this.initialState) : servers;
100
- return servers;
101
- };
102
-
103
- render = () => {
104
- const [servers, setServers] = useState<CompilationServers>(this.initialState);
105
- this.updateServers = setServers;
106
- this.initialState = {};
107
-
108
- useEffect(() => {
109
- const noneAreCompiling = Object.values(servers).every((x) => !x.compiling);
110
- if (noneAreCompiling) this.setReady();
111
- }, [servers]);
112
-
113
- return <PreviewServerStatus previewServers={this.previewServers} serverStats={servers} />;
114
- };
189
+ function stringifyIncludedEnvs(includedEnvs: string[] = [], verbose = false) {
190
+ if (includedEnvs.length < 2) return '';
191
+ if (includedEnvs.length > 2 && !verbose) return ` ${includedEnvs.length} other envs`;
192
+ return includedEnvs.join(', ');
115
193
  }