index.js 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. /*!
  2. Stencil CLI v2.18.1 | MIT Licensed | https://stenciljs.com
  3. */
  4. /**
  5. * Convert a string from PascalCase to dash-case
  6. *
  7. * @param str the string to convert
  8. * @returns a converted string
  9. */
  10. const toDashCase = (str) => str
  11. .replace(/([A-Z0-9])/g, (match) => ` ${match[0]}`)
  12. .trim()
  13. .split(' ')
  14. .join('-')
  15. .toLowerCase();
  16. /**
  17. * Convert a string from dash-case / kebab-case to PascalCase (or CamelCase,
  18. * or whatever you call it!)
  19. *
  20. * @param str a string to convert
  21. * @returns a converted string
  22. */
  23. const dashToPascalCase = (str) => str
  24. .toLowerCase()
  25. .split('-')
  26. .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
  27. .join('');
  28. const isFunction = (v) => typeof v === 'function';
  29. const isString = (v) => typeof v === 'string';
  30. /**
  31. * Builds a template `Diagnostic` entity for a build error. The created `Diagnostic` is returned, and have little
  32. * detail attached to it regarding the specifics of the error - it is the responsibility of the caller of this method
  33. * to attach the specifics of the error message.
  34. *
  35. * The created `Diagnostic` is pushed to the `diagnostics` argument as a side effect of calling this method.
  36. *
  37. * @param diagnostics the existing diagnostics that the created template `Diagnostic` should be added to
  38. * @returns the created `Diagnostic`
  39. */
  40. const buildError = (diagnostics) => {
  41. const diagnostic = {
  42. level: 'error',
  43. type: 'build',
  44. header: 'Build Error',
  45. messageText: 'build error',
  46. relFilePath: null,
  47. absFilePath: null,
  48. lines: [],
  49. };
  50. if (diagnostics) {
  51. diagnostics.push(diagnostic);
  52. }
  53. return diagnostic;
  54. };
  55. /**
  56. * Builds a diagnostic from an `Error`, appends it to the `diagnostics` parameter, and returns the created diagnostic
  57. * @param diagnostics the series of diagnostics the newly created diagnostics should be added to
  58. * @param err the error to derive information from in generating the diagnostic
  59. * @param msg an optional message to use in place of `err` to generate the diagnostic
  60. * @returns the generated diagnostic
  61. */
  62. const catchError = (diagnostics, err, msg) => {
  63. const diagnostic = {
  64. level: 'error',
  65. type: 'build',
  66. header: 'Build Error',
  67. messageText: 'build error',
  68. relFilePath: null,
  69. absFilePath: null,
  70. lines: [],
  71. };
  72. if (isString(msg)) {
  73. diagnostic.messageText = msg.length ? msg : 'UNKNOWN ERROR';
  74. }
  75. else if (err != null) {
  76. if (err.stack != null) {
  77. diagnostic.messageText = err.stack.toString();
  78. }
  79. else {
  80. if (err.message != null) {
  81. diagnostic.messageText = err.message.length ? err.message : 'UNKNOWN ERROR';
  82. }
  83. else {
  84. diagnostic.messageText = err.toString();
  85. }
  86. }
  87. }
  88. if (diagnostics != null && !shouldIgnoreError(diagnostic.messageText)) {
  89. diagnostics.push(diagnostic);
  90. }
  91. return diagnostic;
  92. };
  93. /**
  94. * Determine if the provided diagnostics have any build errors
  95. * @param diagnostics the diagnostics to inspect
  96. * @returns true if any of the diagnostics in the list provided are errors that did not occur at runtime. false
  97. * otherwise.
  98. */
  99. const hasError = (diagnostics) => {
  100. if (diagnostics == null || diagnostics.length === 0) {
  101. return false;
  102. }
  103. return diagnostics.some((d) => d.level === 'error' && d.type !== 'runtime');
  104. };
  105. const shouldIgnoreError = (msg) => {
  106. return msg === TASK_CANCELED_MSG;
  107. };
  108. const TASK_CANCELED_MSG = `task canceled`;
  109. /**
  110. * Convert Windows backslash paths to slash paths: foo\\bar ➔ foo/bar
  111. * Forward-slash paths can be used in Windows as long as they're not
  112. * extended-length paths and don't contain any non-ascii characters.
  113. * This was created since the path methods in Node.js outputs \\ paths on Windows.
  114. * @param path the Windows-based path to convert
  115. * @returns the converted path
  116. */
  117. const normalizePath = (path) => {
  118. if (typeof path !== 'string') {
  119. throw new Error(`invalid path to normalize`);
  120. }
  121. path = normalizeSlashes(path.trim());
  122. const components = pathComponents(path, getRootLength(path));
  123. const reducedComponents = reducePathComponents(components);
  124. const rootPart = reducedComponents[0];
  125. const secondPart = reducedComponents[1];
  126. const normalized = rootPart + reducedComponents.slice(1).join('/');
  127. if (normalized === '') {
  128. return '.';
  129. }
  130. if (rootPart === '' &&
  131. secondPart &&
  132. path.includes('/') &&
  133. !secondPart.startsWith('.') &&
  134. !secondPart.startsWith('@')) {
  135. return './' + normalized;
  136. }
  137. return normalized;
  138. };
  139. const normalizeSlashes = (path) => path.replace(backslashRegExp, '/');
  140. const altDirectorySeparator = '\\';
  141. const urlSchemeSeparator = '://';
  142. const backslashRegExp = /\\/g;
  143. const reducePathComponents = (components) => {
  144. if (!Array.isArray(components) || components.length === 0) {
  145. return [];
  146. }
  147. const reduced = [components[0]];
  148. for (let i = 1; i < components.length; i++) {
  149. const component = components[i];
  150. if (!component)
  151. continue;
  152. if (component === '.')
  153. continue;
  154. if (component === '..') {
  155. if (reduced.length > 1) {
  156. if (reduced[reduced.length - 1] !== '..') {
  157. reduced.pop();
  158. continue;
  159. }
  160. }
  161. else if (reduced[0])
  162. continue;
  163. }
  164. reduced.push(component);
  165. }
  166. return reduced;
  167. };
  168. const getRootLength = (path) => {
  169. const rootLength = getEncodedRootLength(path);
  170. return rootLength < 0 ? ~rootLength : rootLength;
  171. };
  172. const getEncodedRootLength = (path) => {
  173. if (!path)
  174. return 0;
  175. const ch0 = path.charCodeAt(0);
  176. // POSIX or UNC
  177. if (ch0 === 47 /* CharacterCodes.slash */ || ch0 === 92 /* CharacterCodes.backslash */) {
  178. if (path.charCodeAt(1) !== ch0)
  179. return 1; // POSIX: "/" (or non-normalized "\")
  180. const p1 = path.indexOf(ch0 === 47 /* CharacterCodes.slash */ ? '/' : altDirectorySeparator, 2);
  181. if (p1 < 0)
  182. return path.length; // UNC: "//server" or "\\server"
  183. return p1 + 1; // UNC: "//server/" or "\\server\"
  184. }
  185. // DOS
  186. if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* CharacterCodes.colon */) {
  187. const ch2 = path.charCodeAt(2);
  188. if (ch2 === 47 /* CharacterCodes.slash */ || ch2 === 92 /* CharacterCodes.backslash */)
  189. return 3; // DOS: "c:/" or "c:\"
  190. if (path.length === 2)
  191. return 2; // DOS: "c:" (but not "c:d")
  192. }
  193. // URL
  194. const schemeEnd = path.indexOf(urlSchemeSeparator);
  195. if (schemeEnd !== -1) {
  196. const authorityStart = schemeEnd + urlSchemeSeparator.length;
  197. const authorityEnd = path.indexOf('/', authorityStart);
  198. if (authorityEnd !== -1) {
  199. // URL: "file:///", "file://server/", "file://server/path"
  200. // For local "file" URLs, include the leading DOS volume (if present).
  201. // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
  202. // special case interpreted as "the machine from which the URL is being interpreted".
  203. const scheme = path.slice(0, schemeEnd);
  204. const authority = path.slice(authorityStart, authorityEnd);
  205. if (scheme === 'file' &&
  206. (authority === '' || authority === 'localhost') &&
  207. isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
  208. const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
  209. if (volumeSeparatorEnd !== -1) {
  210. if (path.charCodeAt(volumeSeparatorEnd) === 47 /* CharacterCodes.slash */) {
  211. // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
  212. return ~(volumeSeparatorEnd + 1);
  213. }
  214. if (volumeSeparatorEnd === path.length) {
  215. // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
  216. // but not "file:///c:d" or "file:///c%3ad"
  217. return ~volumeSeparatorEnd;
  218. }
  219. }
  220. }
  221. return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
  222. }
  223. return ~path.length; // URL: "file://server", "http://server"
  224. }
  225. // relative
  226. return 0;
  227. };
  228. const isVolumeCharacter = (charCode) => (charCode >= 97 /* CharacterCodes.a */ && charCode <= 122 /* CharacterCodes.z */) ||
  229. (charCode >= 65 /* CharacterCodes.A */ && charCode <= 90 /* CharacterCodes.Z */);
  230. const getFileUrlVolumeSeparatorEnd = (url, start) => {
  231. const ch0 = url.charCodeAt(start);
  232. if (ch0 === 58 /* CharacterCodes.colon */)
  233. return start + 1;
  234. if (ch0 === 37 /* CharacterCodes.percent */ && url.charCodeAt(start + 1) === 51 /* CharacterCodes._3 */) {
  235. const ch2 = url.charCodeAt(start + 2);
  236. if (ch2 === 97 /* CharacterCodes.a */ || ch2 === 65 /* CharacterCodes.A */)
  237. return start + 3;
  238. }
  239. return -1;
  240. };
  241. const pathComponents = (path, rootLength) => {
  242. const root = path.substring(0, rootLength);
  243. const rest = path.substring(rootLength).split('/');
  244. const restLen = rest.length;
  245. if (restLen > 0 && !rest[restLen - 1]) {
  246. rest.pop();
  247. }
  248. return [root, ...rest];
  249. };
  250. /**
  251. * Check whether a string is a member of a ReadonlyArray<string>
  252. *
  253. * We need a little helper for this because unfortunately `includes` is typed
  254. * on `ReadonlyArray<T>` as `(el: T): boolean` so a `string` cannot be passed
  255. * to `includes` on a `ReadonlyArray` 😢 thus we have a little helper function
  256. * where we do the type coercion just once.
  257. *
  258. * see microsoft/TypeScript#31018 for some discussion of this
  259. *
  260. * @param readOnlyArray the array we're checking
  261. * @param maybeMember a value which is possibly a member of the array
  262. * @returns whether the array contains the member or not
  263. */
  264. const readOnlyArrayHasStringMember = (readOnlyArray, maybeMember) => readOnlyArray.includes(maybeMember);
  265. /**
  266. * Validates that a component tag meets required naming conventions to be used for a web component
  267. * @param tag the tag to validate
  268. * @returns an error message if the tag has an invalid name, undefined if the tag name passes all checks
  269. */
  270. const validateComponentTag = (tag) => {
  271. // we want to check this first since we call some String.prototype methods below
  272. if (typeof tag !== 'string') {
  273. return `Tag "${tag}" must be a string type`;
  274. }
  275. if (tag !== tag.trim()) {
  276. return `Tag can not contain white spaces`;
  277. }
  278. if (tag !== tag.toLowerCase()) {
  279. return `Tag can not contain upper case characters`;
  280. }
  281. if (tag.length === 0) {
  282. return `Received empty tag value`;
  283. }
  284. if (tag.indexOf(' ') > -1) {
  285. return `"${tag}" tag cannot contain a space`;
  286. }
  287. if (tag.indexOf(',') > -1) {
  288. return `"${tag}" tag cannot be used for multiple tags`;
  289. }
  290. const invalidChars = tag.replace(/\w|-/g, '');
  291. if (invalidChars !== '') {
  292. return `"${tag}" tag contains invalid characters: ${invalidChars}`;
  293. }
  294. if (tag.indexOf('-') === -1) {
  295. return `"${tag}" tag must contain a dash (-) to work as a valid web component`;
  296. }
  297. if (tag.indexOf('--') > -1) {
  298. return `"${tag}" tag cannot contain multiple dashes (--) next to each other`;
  299. }
  300. if (tag.indexOf('-') === 0) {
  301. return `"${tag}" tag cannot start with a dash (-)`;
  302. }
  303. if (tag.lastIndexOf('-') === tag.length - 1) {
  304. return `"${tag}" tag cannot end with a dash (-)`;
  305. }
  306. return undefined;
  307. };
  308. /**
  309. * This sets the log level hierarchy for our terminal logger, ranging from
  310. * most to least verbose.
  311. *
  312. * Ordering the levels like this lets us easily check whether we should log a
  313. * message at a given time. For instance, if the log level is set to `'warn'`,
  314. * then anything passed to the logger with level `'warn'` or `'error'` should
  315. * be logged, but we should _not_ log anything with level `'info'` or `'debug'`.
  316. *
  317. * If we have a current log level `currentLevel` and a message with level
  318. * `msgLevel` is passed to the logger, we can determine whether or not we should
  319. * log it by checking if the log level on the message is further up or at the
  320. * same level in the hierarchy than `currentLevel`, like so:
  321. *
  322. * ```ts
  323. * LOG_LEVELS.indexOf(msgLevel) >= LOG_LEVELS.indexOf(currentLevel)
  324. * ```
  325. *
  326. * NOTE: for the reasons described above, do not change the order of the entries
  327. * in this array without good reason!
  328. */
  329. const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
  330. /**
  331. * All the Boolean options supported by the Stencil CLI
  332. */
  333. const BOOLEAN_CLI_ARGS = [
  334. 'build',
  335. 'cache',
  336. 'checkVersion',
  337. 'ci',
  338. 'compare',
  339. 'debug',
  340. 'dev',
  341. 'devtools',
  342. 'docs',
  343. 'e2e',
  344. 'es5',
  345. 'esm',
  346. 'headless',
  347. 'help',
  348. 'log',
  349. 'open',
  350. 'prerender',
  351. 'prerenderExternal',
  352. 'prod',
  353. 'profile',
  354. 'serviceWorker',
  355. 'screenshot',
  356. 'serve',
  357. 'skipNodeCheck',
  358. 'spec',
  359. 'ssr',
  360. 'stats',
  361. 'updateScreenshot',
  362. 'verbose',
  363. 'version',
  364. 'watch',
  365. // JEST CLI OPTIONS
  366. 'all',
  367. 'automock',
  368. 'bail',
  369. // 'cache', Stencil already supports this argument
  370. 'changedFilesWithAncestor',
  371. // 'ci', Stencil already supports this argument
  372. 'clearCache',
  373. 'clearMocks',
  374. 'collectCoverage',
  375. 'color',
  376. 'colors',
  377. 'coverage',
  378. // 'debug', Stencil already supports this argument
  379. 'detectLeaks',
  380. 'detectOpenHandles',
  381. 'errorOnDeprecated',
  382. 'expand',
  383. 'findRelatedTests',
  384. 'forceExit',
  385. 'init',
  386. 'injectGlobals',
  387. 'json',
  388. 'lastCommit',
  389. 'listTests',
  390. 'logHeapUsage',
  391. 'noStackTrace',
  392. 'notify',
  393. 'onlyChanged',
  394. 'onlyFailures',
  395. 'passWithNoTests',
  396. 'resetMocks',
  397. 'resetModules',
  398. 'restoreMocks',
  399. 'runInBand',
  400. 'runTestsByPath',
  401. 'showConfig',
  402. 'silent',
  403. 'skipFilter',
  404. 'testLocationInResults',
  405. 'updateSnapshot',
  406. 'useStderr',
  407. // 'verbose', Stencil already supports this argument
  408. // 'version', Stencil already supports this argument
  409. // 'watch', Stencil already supports this argument
  410. 'watchAll',
  411. 'watchman',
  412. ];
  413. /**
  414. * All the Number options supported by the Stencil CLI
  415. */
  416. const NUMBER_CLI_ARGS = [
  417. 'port',
  418. // JEST CLI ARGS
  419. 'maxConcurrency',
  420. 'testTimeout',
  421. ];
  422. /**
  423. * All the String options supported by the Stencil CLI
  424. */
  425. const STRING_CLI_ARGS = [
  426. 'address',
  427. 'config',
  428. 'docsApi',
  429. 'docsJson',
  430. 'emulate',
  431. 'root',
  432. 'screenshotConnector',
  433. // JEST CLI ARGS
  434. 'cacheDirectory',
  435. 'changedSince',
  436. 'collectCoverageFrom',
  437. // 'config', Stencil already supports this argument
  438. 'coverageDirectory',
  439. 'coverageThreshold',
  440. 'env',
  441. 'filter',
  442. 'globalSetup',
  443. 'globalTeardown',
  444. 'globals',
  445. 'haste',
  446. 'moduleNameMapper',
  447. 'notifyMode',
  448. 'outputFile',
  449. 'preset',
  450. 'prettierPath',
  451. 'resolver',
  452. 'rootDir',
  453. 'runner',
  454. 'testEnvironment',
  455. 'testEnvironmentOptions',
  456. 'testFailureExitCode',
  457. 'testNamePattern',
  458. 'testResultsProcessor',
  459. 'testRunner',
  460. 'testSequencer',
  461. 'testURL',
  462. 'timers',
  463. 'transform',
  464. // ARRAY ARGS
  465. 'collectCoverageOnlyFrom',
  466. 'coveragePathIgnorePatterns',
  467. 'coverageReporters',
  468. 'moduleDirectories',
  469. 'moduleFileExtensions',
  470. 'modulePathIgnorePatterns',
  471. 'modulePaths',
  472. 'projects',
  473. 'reporters',
  474. 'roots',
  475. 'selectProjects',
  476. 'setupFiles',
  477. 'setupFilesAfterEnv',
  478. 'snapshotSerializers',
  479. 'testMatch',
  480. 'testPathIgnorePatterns',
  481. 'testPathPattern',
  482. 'testRegex',
  483. 'transformIgnorePatterns',
  484. 'unmockedModulePathPatterns',
  485. 'watchPathIgnorePatterns',
  486. ];
  487. /**
  488. * All the CLI arguments which may have string or number values
  489. *
  490. * `maxWorkers` is an argument which is used both by Stencil _and_ by Jest,
  491. * which means that we need to support parsing both string and number values.
  492. */
  493. const STRING_NUMBER_CLI_ARGS = ['maxWorkers'];
  494. /**
  495. * All the LogLevel-type options supported by the Stencil CLI
  496. *
  497. * This is a bit silly since there's only one such argument atm,
  498. * but this approach lets us make sure that we're handling all
  499. * our arguments in a type-safe way.
  500. */
  501. const LOG_LEVEL_CLI_ARGS = ['logLevel'];
  502. /**
  503. * For a small subset of CLI options we support a short alias e.g. `'h'` for `'help'`
  504. */
  505. const CLI_ARG_ALIASES = {
  506. config: 'c',
  507. help: 'h',
  508. port: 'p',
  509. version: 'v',
  510. };
  511. /**
  512. * Helper function for initializing a `ConfigFlags` object. Provide any overrides
  513. * for default values and off you go!
  514. *
  515. * @param init an object with any overrides for default values
  516. * @returns a complete CLI flag object
  517. */
  518. const createConfigFlags = (init = {}) => {
  519. const flags = {
  520. task: null,
  521. args: [],
  522. knownArgs: [],
  523. unknownArgs: [],
  524. ...init,
  525. };
  526. return flags;
  527. };
  528. /**
  529. * Parse command line arguments into a structured `ConfigFlags` object
  530. *
  531. * @param args an array of CLI flags
  532. * @param _sys an optional compiler system
  533. * @returns a structured ConfigFlags object
  534. */
  535. const parseFlags = (args, _sys) => {
  536. // TODO(STENCIL-509): remove the _sys parameter here ^^ (for v3)
  537. const flags = createConfigFlags();
  538. // cmd line has more priority over npm scripts cmd
  539. flags.args = Array.isArray(args) ? args.slice() : [];
  540. if (flags.args.length > 0 && flags.args[0] && !flags.args[0].startsWith('-')) {
  541. flags.task = flags.args[0];
  542. }
  543. parseArgs(flags, flags.args);
  544. if (flags.task != null) {
  545. const i = flags.args.indexOf(flags.task);
  546. if (i > -1) {
  547. flags.args.splice(i, 1);
  548. }
  549. }
  550. // to find unknown / unrecognized arguments we filter `args`, including only
  551. // arguments whose normalized form is not found in `knownArgs`. `knownArgs`
  552. // is populated during the call to `parseArgs` above. For arguments like
  553. // `--foobar` the string `"--foobar"` will be added, while for more
  554. // complicated arguments like `--bizBoz=bop` or `--bizBoz bop` just the
  555. // string `"--bizBoz"` will be added.
  556. flags.unknownArgs = flags.args.filter((arg) => !flags.knownArgs.includes(parseEqualsArg(arg)[0]));
  557. return flags;
  558. };
  559. /**
  560. * Parse command line arguments that are enumerated in the `config-flags`
  561. * module. Handles leading dashes on arguments, aliases that are defined for a
  562. * small number of arguments, and parsing values for non-boolean arguments
  563. * (e.g. port number for the dev server).
  564. *
  565. * @param flags a ConfigFlags object to which parsed arguments will be added
  566. * @param args an array of command-line arguments to parse
  567. */
  568. const parseArgs = (flags, args) => {
  569. BOOLEAN_CLI_ARGS.forEach((argName) => parseBooleanArg(flags, args, argName));
  570. STRING_CLI_ARGS.forEach((argName) => parseStringArg(flags, args, argName));
  571. NUMBER_CLI_ARGS.forEach((argName) => parseNumberArg(flags, args, argName));
  572. STRING_NUMBER_CLI_ARGS.forEach((argName) => parseStringNumberArg(flags, args, argName));
  573. LOG_LEVEL_CLI_ARGS.forEach((argName) => parseLogLevelArg(flags, args, argName));
  574. };
  575. /**
  576. * Parse a boolean CLI argument. For these, we support the following formats:
  577. *
  578. * - `--booleanArg`
  579. * - `--boolean-arg`
  580. * - `--noBooleanArg`
  581. * - `--no-boolean-arg`
  582. *
  583. * The final two variants should be parsed to a value of `false` on the config
  584. * object.
  585. *
  586. * @param flags the config flags object, while we'll modify
  587. * @param args our CLI arguments
  588. * @param configCaseName the argument we want to look at right now
  589. */
  590. const parseBooleanArg = (flags, args, configCaseName) => {
  591. // we support both dash-case and PascalCase versions of the parameter
  592. // argName is 'configCase' version which can be found in BOOLEAN_ARG_OPTS
  593. const alias = CLI_ARG_ALIASES[configCaseName];
  594. const dashCaseName = toDashCase(configCaseName);
  595. if (typeof flags[configCaseName] !== 'boolean') {
  596. flags[configCaseName] = null;
  597. }
  598. args.forEach((cmdArg) => {
  599. let value;
  600. if (cmdArg === `--${configCaseName}` || cmdArg === `--${dashCaseName}`) {
  601. value = true;
  602. }
  603. else if (cmdArg === `--no-${dashCaseName}` || cmdArg === `--no${dashToPascalCase(dashCaseName)}`) {
  604. value = false;
  605. }
  606. else if (alias && cmdArg === `-${alias}`) {
  607. value = true;
  608. }
  609. if (value !== undefined && cmdArg !== undefined) {
  610. flags[configCaseName] = value;
  611. flags.knownArgs.push(cmdArg);
  612. }
  613. });
  614. };
  615. /**
  616. * Parse a string CLI argument
  617. *
  618. * @param flags the config flags object, while we'll modify
  619. * @param args our CLI arguments
  620. * @param configCaseName the argument we want to look at right now
  621. */
  622. const parseStringArg = (flags, args, configCaseName) => {
  623. if (typeof flags[configCaseName] !== 'string') {
  624. flags[configCaseName] = null;
  625. }
  626. const { value, matchingArg } = getValue(args, configCaseName);
  627. if (value !== undefined && matchingArg !== undefined) {
  628. flags[configCaseName] = value;
  629. flags.knownArgs.push(matchingArg);
  630. flags.knownArgs.push(value);
  631. }
  632. };
  633. /**
  634. * Parse a number CLI argument
  635. *
  636. * @param flags the config flags object, while we'll modify
  637. * @param args our CLI arguments
  638. * @param configCaseName the argument we want to look at right now
  639. */
  640. const parseNumberArg = (flags, args, configCaseName) => {
  641. if (typeof flags[configCaseName] !== 'number') {
  642. flags[configCaseName] = null;
  643. }
  644. const { value, matchingArg } = getValue(args, configCaseName);
  645. if (value !== undefined && matchingArg !== undefined) {
  646. flags[configCaseName] = parseInt(value, 10);
  647. flags.knownArgs.push(matchingArg);
  648. flags.knownArgs.push(value);
  649. }
  650. };
  651. /**
  652. * Parse a CLI argument which may be either a string or a number
  653. *
  654. * @param flags the config flags object, while we'll modify
  655. * @param args our CLI arguments
  656. * @param configCaseName the argument we want to look at right now
  657. */
  658. const parseStringNumberArg = (flags, args, configCaseName) => {
  659. if (!['number', 'string'].includes(typeof flags[configCaseName])) {
  660. flags[configCaseName] = null;
  661. }
  662. const { value, matchingArg } = getValue(args, configCaseName);
  663. if (value !== undefined && matchingArg !== undefined) {
  664. if (CLI_ARG_STRING_REGEX.test(value)) {
  665. // if it matches the regex we treat it like a string
  666. flags[configCaseName] = value;
  667. }
  668. else {
  669. // it was a number, great!
  670. flags[configCaseName] = Number(value);
  671. }
  672. flags.knownArgs.push(matchingArg);
  673. flags.knownArgs.push(value);
  674. }
  675. };
  676. /**
  677. * We use this regular expression to detect CLI parameters which
  678. * should be parsed as string values (as opposed to numbers) for
  679. * the argument types for which we support both a string and a
  680. * number value.
  681. *
  682. * The regex tests for the presence of at least one character which is
  683. * _not_ a digit (`\d`), a period (`\.`), or one of the characters `"e"`,
  684. * `"E"`, `"+"`, or `"-"` (the latter four characters are necessary to
  685. * support the admittedly unlikely use of scientific notation, like `"4e+0"`
  686. * for `4`).
  687. *
  688. * Thus we'll match a string like `"50%"`, but not a string like `"50"` or
  689. * `"5.0"`. If it matches a given string we conclude that the string should
  690. * be parsed as a string literal, rather than using `Number` to convert it
  691. * to a number.
  692. */
  693. const CLI_ARG_STRING_REGEX = /[^\d\.Ee\+\-]+/g;
  694. /**
  695. * Parse a LogLevel CLI argument. These can be only a specific
  696. * set of strings, so this function takes care of validating that
  697. * the value is correct.
  698. *
  699. * @param flags the config flags object, while we'll modify
  700. * @param args our CLI arguments
  701. * @param configCaseName the argument we want to look at right now
  702. */
  703. const parseLogLevelArg = (flags, args, configCaseName) => {
  704. if (typeof flags[configCaseName] !== 'string') {
  705. flags[configCaseName] = null;
  706. }
  707. const { value, matchingArg } = getValue(args, configCaseName);
  708. if (value !== undefined && matchingArg !== undefined && isLogLevel(value)) {
  709. flags[configCaseName] = value;
  710. flags.knownArgs.push(matchingArg);
  711. flags.knownArgs.push(value);
  712. }
  713. };
  714. /**
  715. * Helper for pulling values out from the raw array of CLI arguments. This logic
  716. * is shared between a few different types of CLI args.
  717. *
  718. * We look for arguments in the following formats:
  719. *
  720. * - `--my-cli-argument value`
  721. * - `--my-cli-argument=value`
  722. * - `--myCliArgument value`
  723. * - `--myCliArgument=value`
  724. *
  725. * We also check for shortened aliases, which we define for a few arguments.
  726. *
  727. * @param args the CLI args we're dealing with
  728. * @param configCaseName the ConfigFlag key which we're looking to pull out a value for
  729. * @returns the value for the flag as well as the exact string which it matched from
  730. * the user input.
  731. */
  732. const getValue = (args, configCaseName) => {
  733. // for some CLI args we have a short alias, like 'c' for 'config'
  734. const alias = CLI_ARG_ALIASES[configCaseName];
  735. // we support supplying arguments in both dash-case and configCase
  736. // for ease of use
  737. const dashCaseName = toDashCase(configCaseName);
  738. let value;
  739. let matchingArg;
  740. args.forEach((arg, i) => {
  741. if (arg.startsWith(`--${dashCaseName}=`) || arg.startsWith(`--${configCaseName}=`)) {
  742. // our argument was passed at the command-line in the format --argName=arg-value
  743. [matchingArg, value] = parseEqualsArg(arg);
  744. }
  745. else if (arg === `--${dashCaseName}` || arg === `--${configCaseName}`) {
  746. // the next value in the array is assumed to be a value for this argument
  747. value = args[i + 1];
  748. matchingArg = arg;
  749. }
  750. else if (alias) {
  751. if (arg.startsWith(`-${alias}=`)) {
  752. [matchingArg, value] = parseEqualsArg(arg);
  753. }
  754. else if (arg === `-${alias}`) {
  755. value = args[i + 1];
  756. matchingArg = arg;
  757. }
  758. }
  759. });
  760. return { value, matchingArg };
  761. };
  762. /**
  763. * Parse an 'equals' argument, which is a CLI argument-value pair in the
  764. * format `--foobar=12` (as opposed to a space-separated format like
  765. * `--foobar 12`).
  766. *
  767. * To parse this we split on the `=`, returning the first part as the argument
  768. * name and the second part as the value. We join the value on `"="` in case
  769. * there is another `"="` in the argument.
  770. *
  771. * This function is safe to call with any arg, and can therefore be used as
  772. * an argument 'normalizer'. If CLI argument is not an 'equals' argument then
  773. * the return value will be a tuple of the original argument and an empty
  774. * string `""` for the value.
  775. *
  776. * In code terms, if you do:
  777. *
  778. * ```ts
  779. * const [arg, value] = parseEqualsArg("--myArgument")
  780. * ```
  781. *
  782. * Then `arg` will be `"--myArgument"` and `value` will be `""`, whereas if
  783. * you do:
  784. *
  785. *
  786. * ```ts
  787. * const [arg, value] = parseEqualsArg("--myArgument=myValue")
  788. * ```
  789. *
  790. * Then `arg` will be `"--myArgument"` and `value` will be `"myValue"`.
  791. *
  792. * @param arg the arg in question
  793. * @returns a tuple containing the arg name and the value (if present)
  794. */
  795. const parseEqualsArg = (arg) => {
  796. const [originalArg, ...value] = arg.split('=');
  797. return [originalArg, value.join('=')];
  798. };
  799. /**
  800. * Small helper for getting type-system-level assurance that a `string` can be
  801. * narrowed to a `LogLevel`
  802. *
  803. * @param maybeLogLevel the string to check
  804. * @returns whether this is a `LogLevel`
  805. */
  806. const isLogLevel = (maybeLogLevel) => readOnlyArrayHasStringMember(LOG_LEVELS, maybeLogLevel);
  807. const dependencies = [
  808. {
  809. name: "@stencil/core",
  810. version: "2.18.1",
  811. main: "compiler/stencil.js",
  812. resources: [
  813. "package.json",
  814. "compiler/lib.d.ts",
  815. "compiler/lib.dom.d.ts",
  816. "compiler/lib.dom.iterable.d.ts",
  817. "compiler/lib.es2015.collection.d.ts",
  818. "compiler/lib.es2015.core.d.ts",
  819. "compiler/lib.es2015.d.ts",
  820. "compiler/lib.es2015.generator.d.ts",
  821. "compiler/lib.es2015.iterable.d.ts",
  822. "compiler/lib.es2015.promise.d.ts",
  823. "compiler/lib.es2015.proxy.d.ts",
  824. "compiler/lib.es2015.reflect.d.ts",
  825. "compiler/lib.es2015.symbol.d.ts",
  826. "compiler/lib.es2015.symbol.wellknown.d.ts",
  827. "compiler/lib.es2016.array.include.d.ts",
  828. "compiler/lib.es2016.d.ts",
  829. "compiler/lib.es2016.full.d.ts",
  830. "compiler/lib.es2017.d.ts",
  831. "compiler/lib.es2017.full.d.ts",
  832. "compiler/lib.es2017.intl.d.ts",
  833. "compiler/lib.es2017.object.d.ts",
  834. "compiler/lib.es2017.sharedmemory.d.ts",
  835. "compiler/lib.es2017.string.d.ts",
  836. "compiler/lib.es2017.typedarrays.d.ts",
  837. "compiler/lib.es2018.asyncgenerator.d.ts",
  838. "compiler/lib.es2018.asynciterable.d.ts",
  839. "compiler/lib.es2018.d.ts",
  840. "compiler/lib.es2018.full.d.ts",
  841. "compiler/lib.es2018.intl.d.ts",
  842. "compiler/lib.es2018.promise.d.ts",
  843. "compiler/lib.es2018.regexp.d.ts",
  844. "compiler/lib.es2019.array.d.ts",
  845. "compiler/lib.es2019.d.ts",
  846. "compiler/lib.es2019.full.d.ts",
  847. "compiler/lib.es2019.object.d.ts",
  848. "compiler/lib.es2019.string.d.ts",
  849. "compiler/lib.es2019.symbol.d.ts",
  850. "compiler/lib.es2020.bigint.d.ts",
  851. "compiler/lib.es2020.d.ts",
  852. "compiler/lib.es2020.date.d.ts",
  853. "compiler/lib.es2020.full.d.ts",
  854. "compiler/lib.es2020.intl.d.ts",
  855. "compiler/lib.es2020.number.d.ts",
  856. "compiler/lib.es2020.promise.d.ts",
  857. "compiler/lib.es2020.sharedmemory.d.ts",
  858. "compiler/lib.es2020.string.d.ts",
  859. "compiler/lib.es2020.symbol.wellknown.d.ts",
  860. "compiler/lib.es2021.d.ts",
  861. "compiler/lib.es2021.full.d.ts",
  862. "compiler/lib.es2021.intl.d.ts",
  863. "compiler/lib.es2021.promise.d.ts",
  864. "compiler/lib.es2021.string.d.ts",
  865. "compiler/lib.es2021.weakref.d.ts",
  866. "compiler/lib.es2022.array.d.ts",
  867. "compiler/lib.es2022.d.ts",
  868. "compiler/lib.es2022.error.d.ts",
  869. "compiler/lib.es2022.full.d.ts",
  870. "compiler/lib.es2022.intl.d.ts",
  871. "compiler/lib.es2022.object.d.ts",
  872. "compiler/lib.es2022.string.d.ts",
  873. "compiler/lib.es5.d.ts",
  874. "compiler/lib.es6.d.ts",
  875. "compiler/lib.esnext.d.ts",
  876. "compiler/lib.esnext.full.d.ts",
  877. "compiler/lib.esnext.intl.d.ts",
  878. "compiler/lib.esnext.promise.d.ts",
  879. "compiler/lib.esnext.string.d.ts",
  880. "compiler/lib.esnext.weakref.d.ts",
  881. "compiler/lib.scripthost.d.ts",
  882. "compiler/lib.webworker.d.ts",
  883. "compiler/lib.webworker.importscripts.d.ts",
  884. "compiler/lib.webworker.iterable.d.ts",
  885. "internal/index.d.ts",
  886. "internal/index.js",
  887. "internal/package.json",
  888. "internal/stencil-ext-modules.d.ts",
  889. "internal/stencil-private.d.ts",
  890. "internal/stencil-public-compiler.d.ts",
  891. "internal/stencil-public-docs.d.ts",
  892. "internal/stencil-public-runtime.d.ts",
  893. "mock-doc/index.js",
  894. "mock-doc/package.json",
  895. "internal/client/css-shim.js",
  896. "internal/client/dom.js",
  897. "internal/client/index.js",
  898. "internal/client/package.json",
  899. "internal/client/patch-browser.js",
  900. "internal/client/patch-esm.js",
  901. "internal/client/shadow-css.js",
  902. "internal/hydrate/index.js",
  903. "internal/hydrate/package.json",
  904. "internal/hydrate/runner.js",
  905. "internal/hydrate/shadow-css.js",
  906. "internal/stencil-core/index.d.ts",
  907. "internal/stencil-core/index.js"
  908. ]
  909. },
  910. {
  911. name: "rollup",
  912. version: "2.42.3",
  913. main: "dist/es/rollup.browser.js"
  914. },
  915. {
  916. name: "terser",
  917. version: "5.6.1",
  918. main: "dist/bundle.min.js"
  919. },
  920. {
  921. name: "typescript",
  922. version: "4.7.4",
  923. main: "lib/typescript.js"
  924. }
  925. ];
  926. const IS_NODE_ENV = typeof global !== 'undefined' &&
  927. typeof require === 'function' &&
  928. !!global.process &&
  929. typeof __filename === 'string' &&
  930. (!global.origin || typeof global.origin !== 'string');
  931. const IS_BROWSER_ENV = typeof location !== 'undefined' && typeof navigator !== 'undefined' && typeof XMLHttpRequest !== 'undefined';
  932. /**
  933. * Creates an instance of a logger
  934. * @returns the new logger instance
  935. */
  936. const createLogger = () => {
  937. let useColors = IS_BROWSER_ENV;
  938. let level = 'info';
  939. return {
  940. enableColors: (uc) => (useColors = uc),
  941. getLevel: () => level,
  942. setLevel: (l) => (level = l),
  943. emoji: (e) => e,
  944. info: console.log.bind(console),
  945. warn: console.warn.bind(console),
  946. error: console.error.bind(console),
  947. debug: console.debug.bind(console),
  948. red: (msg) => msg,
  949. green: (msg) => msg,
  950. yellow: (msg) => msg,
  951. blue: (msg) => msg,
  952. magenta: (msg) => msg,
  953. cyan: (msg) => msg,
  954. gray: (msg) => msg,
  955. bold: (msg) => msg,
  956. dim: (msg) => msg,
  957. bgRed: (msg) => msg,
  958. createTimeSpan: (_startMsg, _debug = false) => ({
  959. duration: () => 0,
  960. finish: () => 0,
  961. }),
  962. printDiagnostics(diagnostics) {
  963. diagnostics.forEach((diagnostic) => logDiagnostic(diagnostic, useColors));
  964. },
  965. };
  966. };
  967. const logDiagnostic = (diagnostic, useColors) => {
  968. let color = BLUE;
  969. let prefix = 'Build';
  970. let msg = '';
  971. if (diagnostic.level === 'error') {
  972. color = RED;
  973. prefix = 'Error';
  974. }
  975. else if (diagnostic.level === 'warn') {
  976. color = YELLOW;
  977. prefix = 'Warning';
  978. }
  979. if (diagnostic.header) {
  980. prefix = diagnostic.header;
  981. }
  982. const filePath = diagnostic.relFilePath || diagnostic.absFilePath;
  983. if (filePath) {
  984. msg += filePath;
  985. if (typeof diagnostic.lineNumber === 'number' && diagnostic.lineNumber > 0) {
  986. msg += ', line ' + diagnostic.lineNumber;
  987. if (typeof diagnostic.columnNumber === 'number' && diagnostic.columnNumber > 0) {
  988. msg += ', column ' + diagnostic.columnNumber;
  989. }
  990. }
  991. msg += '\n';
  992. }
  993. msg += diagnostic.messageText;
  994. if (diagnostic.lines && diagnostic.lines.length > 0) {
  995. diagnostic.lines.forEach((l) => {
  996. msg += '\n' + l.lineNumber + ': ' + l.text;
  997. });
  998. msg += '\n';
  999. }
  1000. if (useColors) {
  1001. const styledPrefix = [
  1002. '%c' + prefix,
  1003. `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`,
  1004. ];
  1005. console.log(...styledPrefix, msg);
  1006. }
  1007. else if (diagnostic.level === 'error') {
  1008. console.error(msg);
  1009. }
  1010. else if (diagnostic.level === 'warn') {
  1011. console.warn(msg);
  1012. }
  1013. else {
  1014. console.log(msg);
  1015. }
  1016. };
  1017. const YELLOW = `#f39c12`;
  1018. const RED = `#c0392b`;
  1019. const BLUE = `#3498db`;
  1020. /**
  1021. * Attempt to find a Stencil configuration file on the file system
  1022. * @param opts the options needed to find the configuration file
  1023. * @returns the results of attempting to find a configuration file on disk
  1024. */
  1025. const findConfig = async (opts) => {
  1026. const sys = opts.sys;
  1027. const cwd = sys.getCurrentDirectory();
  1028. const rootDir = normalizePath(cwd);
  1029. let configPath = opts.configPath;
  1030. if (isString(configPath)) {
  1031. if (!sys.platformPath.isAbsolute(configPath)) {
  1032. // passed in a custom stencil config location,
  1033. // but it's relative, so prefix the cwd
  1034. configPath = normalizePath(sys.platformPath.join(cwd, configPath));
  1035. }
  1036. else {
  1037. // config path already an absolute path, we're good here
  1038. configPath = normalizePath(opts.configPath);
  1039. }
  1040. }
  1041. else {
  1042. // nothing was passed in, use the current working directory
  1043. configPath = rootDir;
  1044. }
  1045. const results = {
  1046. configPath,
  1047. rootDir: normalizePath(cwd),
  1048. diagnostics: [],
  1049. };
  1050. const stat = await sys.stat(configPath);
  1051. if (stat.error) {
  1052. const diagnostic = buildError(results.diagnostics);
  1053. diagnostic.absFilePath = configPath;
  1054. diagnostic.header = `Invalid config path`;
  1055. diagnostic.messageText = `Config path "${configPath}" not found`;
  1056. return results;
  1057. }
  1058. if (stat.isFile) {
  1059. results.configPath = configPath;
  1060. results.rootDir = sys.platformPath.dirname(configPath);
  1061. }
  1062. else if (stat.isDirectory) {
  1063. // this is only a directory, so let's make some assumptions
  1064. for (const configName of ['stencil.config.ts', 'stencil.config.js']) {
  1065. const testConfigFilePath = sys.platformPath.join(configPath, configName);
  1066. const stat = await sys.stat(testConfigFilePath);
  1067. if (stat.isFile) {
  1068. results.configPath = testConfigFilePath;
  1069. results.rootDir = sys.platformPath.dirname(testConfigFilePath);
  1070. break;
  1071. }
  1072. }
  1073. }
  1074. return results;
  1075. };
  1076. const loadCoreCompiler = async (sys) => {
  1077. await sys.dynamicImport(sys.getCompilerExecutingPath());
  1078. return globalThis.stencil;
  1079. };
  1080. /**
  1081. * Log the name of this package (`@stencil/core`) to an output stream
  1082. *
  1083. * The output stream is determined by the {@link Logger} instance that is provided as an argument to this function
  1084. *
  1085. * The name of the package may not be logged, by design, for certain `task` types and logging levels
  1086. *
  1087. * @param logger the logging entity to use to output the name of the package
  1088. * @param task the current task
  1089. */
  1090. const startupLog = (logger, task) => {
  1091. if (task === 'info' || task === 'serve' || task === 'version') {
  1092. return;
  1093. }
  1094. logger.info(logger.cyan(`@stencil/core`));
  1095. };
  1096. /**
  1097. * Log this package's version to an output stream
  1098. *
  1099. * The output stream is determined by the {@link Logger} instance that is provided as an argument to this function
  1100. *
  1101. * The package version may not be logged, by design, for certain `task` types and logging levels
  1102. *
  1103. * @param logger the logging entity to use for output
  1104. * @param task the current task
  1105. * @param coreCompiler the compiler instance to derive version information from
  1106. */
  1107. const startupLogVersion = (logger, task, coreCompiler) => {
  1108. if (task === 'info' || task === 'serve' || task === 'version') {
  1109. return;
  1110. }
  1111. const isDevBuild = coreCompiler.version.includes('-dev.');
  1112. let startupMsg;
  1113. if (isDevBuild) {
  1114. startupMsg = logger.yellow('[LOCAL DEV]');
  1115. }
  1116. else {
  1117. startupMsg = logger.cyan(`v${coreCompiler.version}`);
  1118. }
  1119. startupMsg += logger.emoji(' ' + coreCompiler.vermoji);
  1120. logger.info(startupMsg);
  1121. };
  1122. /**
  1123. * Log details from a {@link CompilerSystem} used by Stencil to an output stream
  1124. *
  1125. * The output stream is determined by the {@link Logger} instance that is provided as an argument to this function
  1126. *
  1127. * @param sys the `CompilerSystem` to report details on
  1128. * @param logger the logging entity to use for output
  1129. * @param flags user set flags for the current invocation of Stencil
  1130. * @param coreCompiler the compiler instance being used for this invocation of Stencil
  1131. */
  1132. const loadedCompilerLog = (sys, logger, flags, coreCompiler) => {
  1133. const sysDetails = sys.details;
  1134. const runtimeInfo = `${sys.name} ${sys.version}`;
  1135. const platformInfo = sysDetails
  1136. ? `${sysDetails.platform}, ${sysDetails.cpuModel}`
  1137. : `Unknown Platform, Unknown CPU Model`;
  1138. const statsInfo = sysDetails
  1139. ? `cpus: ${sys.hardwareConcurrency}, freemem: ${Math.round(sysDetails.freemem() / 1000000)}MB, totalmem: ${Math.round(sysDetails.totalmem / 1000000)}MB`
  1140. : 'Unknown CPU Core Count, Unknown Memory';
  1141. if (logger.getLevel() === 'debug') {
  1142. logger.debug(runtimeInfo);
  1143. logger.debug(platformInfo);
  1144. logger.debug(statsInfo);
  1145. logger.debug(`compiler: ${sys.getCompilerExecutingPath()}`);
  1146. logger.debug(`build: ${coreCompiler.buildId}`);
  1147. }
  1148. else if (flags.ci) {
  1149. logger.info(runtimeInfo);
  1150. logger.info(platformInfo);
  1151. logger.info(statsInfo);
  1152. }
  1153. };
  1154. /**
  1155. * Log various warnings to an output stream
  1156. *
  1157. * The output stream is determined by the {@link Logger} instance attached to the `config` argument to this function
  1158. *
  1159. * @param coreCompiler the compiler instance being used for this invocation of Stencil
  1160. * @param config a validated configuration object to be used for this run of Stencil
  1161. */
  1162. const startupCompilerLog = (coreCompiler, config) => {
  1163. if (config.suppressLogs === true) {
  1164. return;
  1165. }
  1166. const { logger } = config;
  1167. const isDebug = logger.getLevel() === 'debug';
  1168. const isPrerelease = coreCompiler.version.includes('-');
  1169. const isDevBuild = coreCompiler.version.includes('-dev.');
  1170. if (isPrerelease && !isDevBuild) {
  1171. logger.warn(logger.yellow(`This is a prerelease build, undocumented changes might happen at any time. Technical support is not available for prereleases, but any assistance testing is appreciated.`));
  1172. }
  1173. if (config.devMode && !isDebug) {
  1174. if (config.buildEs5) {
  1175. logger.warn(`Generating ES5 during development is a very task expensive, initial and incremental builds will be much slower. Drop the '--es5' flag and use a modern browser for development.`);
  1176. }
  1177. if (!config.enableCache) {
  1178. logger.warn(`Disabling cache during development will slow down incremental builds.`);
  1179. }
  1180. }
  1181. };
  1182. const startCheckVersion = async (config, currentVersion) => {
  1183. if (config.devMode && !config.flags.ci && !currentVersion.includes('-dev.') && isFunction(config.sys.checkVersion)) {
  1184. return config.sys.checkVersion(config.logger, currentVersion);
  1185. }
  1186. return null;
  1187. };
  1188. const printCheckVersionResults = async (versionChecker) => {
  1189. if (versionChecker) {
  1190. const checkVersionResults = await versionChecker;
  1191. if (isFunction(checkVersionResults)) {
  1192. checkVersionResults();
  1193. }
  1194. }
  1195. };
  1196. const taskPrerender = async (coreCompiler, config) => {
  1197. startupCompilerLog(coreCompiler, config);
  1198. const hydrateAppFilePath = config.flags.unknownArgs[0];
  1199. if (typeof hydrateAppFilePath !== 'string') {
  1200. config.logger.error(`Missing hydrate app script path`);
  1201. return config.sys.exit(1);
  1202. }
  1203. const srcIndexHtmlPath = config.srcIndexHtml;
  1204. const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, null, srcIndexHtmlPath);
  1205. config.logger.printDiagnostics(diagnostics);
  1206. if (diagnostics.some((d) => d.level === 'error')) {
  1207. return config.sys.exit(1);
  1208. }
  1209. };
  1210. const runPrerenderTask = async (coreCompiler, config, hydrateAppFilePath, componentGraph, srcIndexHtmlPath) => {
  1211. const diagnostics = [];
  1212. try {
  1213. const prerenderer = await coreCompiler.createPrerenderer(config);
  1214. const results = await prerenderer.start({
  1215. hydrateAppFilePath,
  1216. componentGraph,
  1217. srcIndexHtmlPath,
  1218. });
  1219. diagnostics.push(...results.diagnostics);
  1220. }
  1221. catch (e) {
  1222. catchError(diagnostics, e);
  1223. }
  1224. return diagnostics;
  1225. };
  1226. const taskWatch = async (coreCompiler, config) => {
  1227. let devServer = null;
  1228. let exitCode = 0;
  1229. try {
  1230. startupCompilerLog(coreCompiler, config);
  1231. const versionChecker = startCheckVersion(config, coreCompiler.version);
  1232. const compiler = await coreCompiler.createCompiler(config);
  1233. const watcher = await compiler.createWatcher();
  1234. if (config.flags.serve) {
  1235. const devServerPath = config.sys.getDevServerExecutingPath();
  1236. const { start } = await config.sys.dynamicImport(devServerPath);
  1237. devServer = await start(config.devServer, config.logger, watcher);
  1238. }
  1239. config.sys.onProcessInterrupt(() => {
  1240. config.logger.debug(`close watch`);
  1241. compiler && compiler.destroy();
  1242. });
  1243. const rmVersionCheckerLog = watcher.on('buildFinish', async () => {
  1244. // log the version check one time
  1245. rmVersionCheckerLog();
  1246. printCheckVersionResults(versionChecker);
  1247. });
  1248. if (devServer) {
  1249. const rmDevServerLog = watcher.on('buildFinish', () => {
  1250. // log the dev server url one time
  1251. rmDevServerLog();
  1252. config.logger.info(`${config.logger.cyan(devServer.browserUrl)}\n`);
  1253. });
  1254. }
  1255. const closeResults = await watcher.start();
  1256. if (closeResults.exitCode > 0) {
  1257. exitCode = closeResults.exitCode;
  1258. }
  1259. }
  1260. catch (e) {
  1261. exitCode = 1;
  1262. config.logger.error(e);
  1263. }
  1264. if (devServer) {
  1265. await devServer.close();
  1266. }
  1267. if (exitCode > 0) {
  1268. return config.sys.exit(exitCode);
  1269. }
  1270. };
  1271. const isOutputTargetHydrate = (o) => o.type === DIST_HYDRATE_SCRIPT;
  1272. const isOutputTargetDocs = (o) => o.type === DOCS_README || o.type === DOCS_JSON || o.type === DOCS_CUSTOM || o.type === DOCS_VSCODE;
  1273. const DIST_HYDRATE_SCRIPT = 'dist-hydrate-script';
  1274. const DOCS_CUSTOM = 'docs-custom';
  1275. const DOCS_JSON = 'docs-json';
  1276. const DOCS_README = 'docs-readme';
  1277. const DOCS_VSCODE = 'docs-vscode';
  1278. const WWW = 'www';
  1279. const tryFn = async (fn, ...args) => {
  1280. try {
  1281. return await fn(...args);
  1282. }
  1283. catch (_a) {
  1284. // ignore
  1285. }
  1286. return null;
  1287. };
  1288. const isInteractive = (sys, flags, object) => {
  1289. const terminalInfo = object ||
  1290. Object.freeze({
  1291. tty: sys.isTTY() ? true : false,
  1292. ci: ['CI', 'BUILD_ID', 'BUILD_NUMBER', 'BITBUCKET_COMMIT', 'CODEBUILD_BUILD_ARN'].filter((v) => { var _a; return !!((_a = sys.getEnvironmentVar) === null || _a === void 0 ? void 0 : _a.call(sys, v)); }).length > 0 || !!flags.ci,
  1293. });
  1294. return terminalInfo.tty && !terminalInfo.ci;
  1295. };
  1296. const UUID_REGEX = new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i);
  1297. // Plucked from https://github.com/ionic-team/capacitor/blob/b893a57aaaf3a16e13db9c33037a12f1a5ac92e0/cli/src/util/uuid.ts
  1298. function uuidv4() {
  1299. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  1300. const r = (Math.random() * 16) | 0;
  1301. const v = c == 'x' ? r : (r & 0x3) | 0x8;
  1302. return v.toString(16);
  1303. });
  1304. }
  1305. /**
  1306. * Reads and parses a JSON file from the given `path`
  1307. * @param sys The system where the command is invoked
  1308. * @param path the path on the file system to read and parse
  1309. * @returns the parsed JSON
  1310. */
  1311. async function readJson(sys, path) {
  1312. const file = await sys.readFile(path);
  1313. return !!file && JSON.parse(file);
  1314. }
  1315. /**
  1316. * Does the command have the debug flag?
  1317. * @param flags The configuration flags passed into the Stencil command
  1318. * @returns true if --debug has been passed, otherwise false
  1319. */
  1320. function hasDebug(flags) {
  1321. return !!flags.debug;
  1322. }
  1323. /**
  1324. * Does the command have the verbose and debug flags?
  1325. * @param flags The configuration flags passed into the Stencil command
  1326. * @returns true if both --debug and --verbose have been passed, otherwise false
  1327. */
  1328. function hasVerbose(flags) {
  1329. return !!flags.verbose && hasDebug(flags);
  1330. }
  1331. const isTest$1 = () => process.env.JEST_WORKER_ID !== undefined;
  1332. const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest$1() ? 'tmp-config.json' : 'config.json'}`);
  1333. const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
  1334. /**
  1335. * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
  1336. * values are deemed to be malformed
  1337. * @param sys The system where the command is invoked
  1338. * @returns the config read from disk that has been potentially been updated
  1339. */
  1340. async function readConfig(sys) {
  1341. let config = await readJson(sys, defaultConfig(sys));
  1342. if (!config) {
  1343. config = {
  1344. 'tokens.telemetry': uuidv4(),
  1345. 'telemetry.stencil': true,
  1346. };
  1347. await writeConfig(sys, config);
  1348. }
  1349. else if (!config['tokens.telemetry'] || !UUID_REGEX.test(config['tokens.telemetry'])) {
  1350. const newUuid = uuidv4();
  1351. await writeConfig(sys, { ...config, 'tokens.telemetry': newUuid });
  1352. config['tokens.telemetry'] = newUuid;
  1353. }
  1354. return config;
  1355. }
  1356. /**
  1357. * Writes an Ionic configuration file to disk.
  1358. * @param sys The system where the command is invoked
  1359. * @param config The config passed into the Stencil command
  1360. * @returns boolean If the command was successful
  1361. */
  1362. async function writeConfig(sys, config) {
  1363. let result = false;
  1364. try {
  1365. await sys.createDir(defaultConfigDirectory(sys), { recursive: true });
  1366. await sys.writeFile(defaultConfig(sys), JSON.stringify(config, null, 2));
  1367. result = true;
  1368. }
  1369. catch (error) {
  1370. console.error(`Stencil Telemetry: couldn't write configuration file to ${defaultConfig(sys)} - ${error}.`);
  1371. }
  1372. return result;
  1373. }
  1374. /**
  1375. * Update a subset of the Ionic config.
  1376. * @param sys The system where the command is invoked
  1377. * @param newOptions The new options to save
  1378. * @returns boolean If the command was successful
  1379. */
  1380. async function updateConfig(sys, newOptions) {
  1381. const config = await readConfig(sys);
  1382. return await writeConfig(sys, Object.assign(config, newOptions));
  1383. }
  1384. /**
  1385. * Used to determine if tracking should occur.
  1386. * @param config The config passed into the Stencil command
  1387. * @param sys The system where the command is invoked
  1388. * @param ci whether or not the process is running in a Continuous Integration (CI) environment
  1389. * @returns true if telemetry should be sent, false otherwise
  1390. */
  1391. async function shouldTrack(config, sys, ci) {
  1392. return !ci && isInteractive(sys, config.flags) && (await checkTelemetry(sys));
  1393. }
  1394. /**
  1395. * Used to within taskBuild to provide the component_count property.
  1396. *
  1397. * @param sys The system where the command is invoked
  1398. * @param config The config passed into the Stencil command
  1399. * @param coreCompiler The compiler used to do builds
  1400. * @param result The results of a compiler build.
  1401. */
  1402. async function telemetryBuildFinishedAction(sys, config, coreCompiler, result) {
  1403. const tracking = await shouldTrack(config, sys, !!config.flags.ci);
  1404. if (!tracking) {
  1405. return;
  1406. }
  1407. const component_count = result.componentGraph ? Object.keys(result.componentGraph).length : undefined;
  1408. const data = await prepareData(coreCompiler, config, sys, result.duration, component_count);
  1409. await sendMetric(sys, config, 'stencil_cli_command', data);
  1410. config.logger.debug(`${config.logger.blue('Telemetry')}: ${config.logger.gray(JSON.stringify(data))}`);
  1411. }
  1412. /**
  1413. * A function to wrap a compiler task function around. Will send telemetry if, and only if, the machine allows.
  1414. *
  1415. * @param sys The system where the command is invoked
  1416. * @param config The config passed into the Stencil command
  1417. * @param coreCompiler The compiler used to do builds
  1418. * @param action A Promise-based function to call in order to get the duration of any given command.
  1419. * @returns void
  1420. */
  1421. async function telemetryAction(sys, config, coreCompiler, action) {
  1422. const tracking = await shouldTrack(config, sys, !!config.flags.ci);
  1423. let duration = undefined;
  1424. let error;
  1425. if (action) {
  1426. const start = new Date();
  1427. try {
  1428. await action();
  1429. }
  1430. catch (e) {
  1431. error = e;
  1432. }
  1433. const end = new Date();
  1434. duration = end.getTime() - start.getTime();
  1435. }
  1436. // We'll get componentCount details inside the taskBuild, so let's not send two messages.
  1437. if (!tracking || (config.flags.task == 'build' && !config.flags.args.includes('--watch'))) {
  1438. return;
  1439. }
  1440. const data = await prepareData(coreCompiler, config, sys, duration);
  1441. await sendMetric(sys, config, 'stencil_cli_command', data);
  1442. config.logger.debug(`${config.logger.blue('Telemetry')}: ${config.logger.gray(JSON.stringify(data))}`);
  1443. if (error) {
  1444. throw error;
  1445. }
  1446. }
  1447. /**
  1448. * Helper function to determine if a Stencil configuration builds an application.
  1449. *
  1450. * This function is a rough approximation whether an application is generated as a part of a Stencil build, based on
  1451. * contents of the project's `stencil.config.ts` file.
  1452. *
  1453. * @param config the configuration used by the Stencil project
  1454. * @returns true if we believe the project generates an application, false otherwise
  1455. */
  1456. function hasAppTarget(config) {
  1457. return config.outputTargets.some((target) => target.type === WWW && (!!target.serviceWorker || (!!target.baseUrl && target.baseUrl !== '/')));
  1458. }
  1459. function isUsingYarn(sys) {
  1460. var _a;
  1461. return ((_a = sys.getEnvironmentVar('npm_execpath')) === null || _a === void 0 ? void 0 : _a.includes('yarn')) || false;
  1462. }
  1463. /**
  1464. * Build a list of the different types of output targets used in a Stencil configuration.
  1465. *
  1466. * Duplicate entries will not be returned from the list
  1467. *
  1468. * @param config the configuration used by the Stencil project
  1469. * @returns a unique list of output target types found in the Stencil configuration
  1470. */
  1471. function getActiveTargets(config) {
  1472. const result = config.outputTargets.map((t) => t.type);
  1473. return Array.from(new Set(result));
  1474. }
  1475. /**
  1476. * Prepare data for telemetry
  1477. *
  1478. * @param coreCompiler the core compiler
  1479. * @param config the current Stencil config
  1480. * @param sys the compiler system instance in use
  1481. * @param duration_ms the duration of the action being tracked
  1482. * @param component_count the number of components being built (optional)
  1483. * @returns a Promise wrapping data for the telemetry endpoint
  1484. */
  1485. const prepareData = async (coreCompiler, config, sys, duration_ms, component_count = undefined) => {
  1486. var _a, _b, _c;
  1487. const { typescript, rollup } = coreCompiler.versions || { typescript: 'unknown', rollup: 'unknown' };
  1488. const { packages, packagesNoVersions } = await getInstalledPackages(sys, config);
  1489. const targets = getActiveTargets(config);
  1490. const yarn = isUsingYarn(sys);
  1491. const stencil = coreCompiler.version || 'unknown';
  1492. const system = `${sys.name} ${sys.version}`;
  1493. const os_name = (_a = sys.details) === null || _a === void 0 ? void 0 : _a.platform;
  1494. const os_version = (_b = sys.details) === null || _b === void 0 ? void 0 : _b.release;
  1495. const cpu_model = (_c = sys.details) === null || _c === void 0 ? void 0 : _c.cpuModel;
  1496. const build = coreCompiler.buildId || 'unknown';
  1497. const has_app_pwa_config = hasAppTarget(config);
  1498. const anonymizedConfig = anonymizeConfigForTelemetry(config);
  1499. return {
  1500. yarn,
  1501. duration_ms,
  1502. component_count,
  1503. targets,
  1504. packages,
  1505. packages_no_versions: packagesNoVersions,
  1506. arguments: config.flags.args,
  1507. task: config.flags.task,
  1508. stencil,
  1509. system,
  1510. system_major: getMajorVersion(system),
  1511. os_name,
  1512. os_version,
  1513. cpu_model,
  1514. build,
  1515. typescript,
  1516. rollup,
  1517. has_app_pwa_config,
  1518. config: anonymizedConfig,
  1519. };
  1520. };
  1521. // props in output targets for which we retain their original values when
  1522. // preparing a config for telemetry
  1523. //
  1524. // we omit the values of all other fields on output targets.
  1525. const OUTPUT_TARGET_KEYS_TO_KEEP = ['type'];
  1526. // top-level config props that we anonymize for telemetry
  1527. const CONFIG_PROPS_TO_ANONYMIZE = [
  1528. 'rootDir',
  1529. 'fsNamespace',
  1530. 'packageJsonFilePath',
  1531. 'namespace',
  1532. 'srcDir',
  1533. 'srcIndexHtml',
  1534. 'buildLogFilePath',
  1535. 'cacheDir',
  1536. 'configPath',
  1537. 'tsconfig',
  1538. ];
  1539. // Props we delete entirely from the config for telemetry
  1540. //
  1541. // TODO(STENCIL-469): Investigate improving anonymization for tsCompilerOptions and devServer
  1542. const CONFIG_PROPS_TO_DELETE = ['sys', 'logger', 'tsCompilerOptions', 'devServer'];
  1543. /**
  1544. * Anonymize the config for telemetry, replacing potentially revealing config props
  1545. * with a placeholder string if they are present (this lets us still track how frequently
  1546. * these config options are being used)
  1547. *
  1548. * @param config the config to anonymize
  1549. * @returns an anonymized copy of the same config
  1550. */
  1551. const anonymizeConfigForTelemetry = (config) => {
  1552. const anonymizedConfig = { ...config };
  1553. for (const prop of CONFIG_PROPS_TO_ANONYMIZE) {
  1554. if (anonymizedConfig[prop] !== undefined) {
  1555. anonymizedConfig[prop] = 'omitted';
  1556. }
  1557. }
  1558. anonymizedConfig.outputTargets = config.outputTargets.map((target) => {
  1559. // Anonymize the outputTargets on our configuration, taking advantage of the
  1560. // optional 2nd argument to `JSON.stringify`. If anything is not a string
  1561. // we retain it so that any nested properties are handled, else we check
  1562. // whether it's in our 'keep' list to decide whether to keep it or replace it
  1563. // with `"omitted"`.
  1564. const anonymizedOT = JSON.parse(JSON.stringify(target, (key, value) => {
  1565. if (!(typeof value === 'string')) {
  1566. return value;
  1567. }
  1568. if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) {
  1569. return value;
  1570. }
  1571. return 'omitted';
  1572. }));
  1573. // this prop has to be handled separately because it is an array
  1574. // so the replace function above will be called with all of its
  1575. // members, giving us `["omitted", "omitted", ...]`.
  1576. //
  1577. // Instead, we check for its presence and manually copy over.
  1578. if (isOutputTargetHydrate(target) && target.external) {
  1579. anonymizedOT['external'] = target.external.concat();
  1580. }
  1581. return anonymizedOT;
  1582. });
  1583. // TODO(STENCIL-469): Investigate improving anonymization for tsCompilerOptions and devServer
  1584. for (const prop of CONFIG_PROPS_TO_DELETE) {
  1585. delete anonymizedConfig[prop];
  1586. }
  1587. return anonymizedConfig;
  1588. };
  1589. /**
  1590. * Reads package-lock.json, yarn.lock, and package.json files in order to cross-reference
  1591. * the dependencies and devDependencies properties. Pulls up the current installed version
  1592. * of each package under the @stencil, @ionic, and @capacitor scopes.
  1593. *
  1594. * @param sys the system instance where telemetry is invoked
  1595. * @param config the Stencil configuration associated with the current task that triggered telemetry
  1596. * @returns an object listing all dev and production dependencies under the aforementioned scopes
  1597. */
  1598. async function getInstalledPackages(sys, config) {
  1599. let packages = [];
  1600. let packagesNoVersions = [];
  1601. const yarn = isUsingYarn(sys);
  1602. try {
  1603. // Read package.json and package-lock.json
  1604. const appRootDir = sys.getCurrentDirectory();
  1605. const packageJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + '/package.json'));
  1606. // They don't have a package.json for some reason? Eject button.
  1607. if (!packageJson) {
  1608. return { packages, packagesNoVersions };
  1609. }
  1610. const rawPackages = Object.entries({
  1611. ...packageJson.devDependencies,
  1612. ...packageJson.dependencies,
  1613. });
  1614. // Collect packages only in the stencil, ionic, or capacitor org's:
  1615. // https://www.npmjs.com/org/stencil
  1616. const ionicPackages = rawPackages.filter(([k]) => k.startsWith('@stencil/') || k.startsWith('@ionic/') || k.startsWith('@capacitor/'));
  1617. try {
  1618. packages = yarn ? await yarnPackages(sys, ionicPackages) : await npmPackages(sys, ionicPackages);
  1619. }
  1620. catch (e) {
  1621. packages = ionicPackages.map(([k, v]) => `${k}@${v.replace('^', '')}`);
  1622. }
  1623. packagesNoVersions = ionicPackages.map(([k]) => `${k}`);
  1624. return { packages, packagesNoVersions };
  1625. }
  1626. catch (err) {
  1627. hasDebug(config.flags) && console.error(err);
  1628. return { packages, packagesNoVersions };
  1629. }
  1630. }
  1631. /**
  1632. * Visits the npm lock file to find the exact versions that are installed
  1633. * @param sys The system where the command is invoked
  1634. * @param ionicPackages a list of the found packages matching `@stencil`, `@capacitor`, or `@ionic` from the package.json file.
  1635. * @returns an array of strings of all the packages and their versions.
  1636. */
  1637. async function npmPackages(sys, ionicPackages) {
  1638. const appRootDir = sys.getCurrentDirectory();
  1639. const packageLockJson = await tryFn(readJson, sys, sys.resolvePath(appRootDir + '/package-lock.json'));
  1640. return ionicPackages.map(([k, v]) => {
  1641. var _a, _b, _c, _d;
  1642. let version = (_d = (_b = (_a = packageLockJson === null || packageLockJson === void 0 ? void 0 : packageLockJson.dependencies[k]) === null || _a === void 0 ? void 0 : _a.version) !== null && _b !== void 0 ? _b : (_c = packageLockJson === null || packageLockJson === void 0 ? void 0 : packageLockJson.devDependencies[k]) === null || _c === void 0 ? void 0 : _c.version) !== null && _d !== void 0 ? _d : v;
  1643. version = version.includes('file:') ? sanitizeDeclaredVersion(v) : version;
  1644. return `${k}@${version}`;
  1645. });
  1646. }
  1647. /**
  1648. * Visits the yarn lock file to find the exact versions that are installed
  1649. * @param sys The system where the command is invoked
  1650. * @param ionicPackages a list of the found packages matching `@stencil`, `@capacitor`, or `@ionic` from the package.json file.
  1651. * @returns an array of strings of all the packages and their versions.
  1652. */
  1653. async function yarnPackages(sys, ionicPackages) {
  1654. const appRootDir = sys.getCurrentDirectory();
  1655. const yarnLock = sys.readFileSync(sys.resolvePath(appRootDir + '/yarn.lock'));
  1656. const yarnLockYml = sys.parseYarnLockFile(yarnLock);
  1657. return ionicPackages.map(([k, v]) => {
  1658. var _a;
  1659. const identifiedVersion = `${k}@${v}`;
  1660. let version = (_a = yarnLockYml.object[identifiedVersion]) === null || _a === void 0 ? void 0 : _a.version;
  1661. version = version.includes('undefined') ? sanitizeDeclaredVersion(identifiedVersion) : version;
  1662. return `${k}@${version}`;
  1663. });
  1664. }
  1665. /**
  1666. * This function is used for fallback purposes, where an npm or yarn lock file doesn't exist in the consumers directory.
  1667. * This will strip away '*', '^' and '~' from the declared package versions in a package.json.
  1668. * @param version the raw semver pattern identifier version string
  1669. * @returns a cleaned up representation without any qualifiers
  1670. */
  1671. function sanitizeDeclaredVersion(version) {
  1672. return version.replace(/[*^~]/g, '');
  1673. }
  1674. /**
  1675. * If telemetry is enabled, send a metric to an external data store
  1676. *
  1677. * @param sys the system instance where telemetry is invoked
  1678. * @param config the Stencil configuration associated with the current task that triggered telemetry
  1679. * @param name the name of a trackable metric. Note this name is not necessarily a scalar value to track, like
  1680. * "Stencil Version". For example, "stencil_cli_command" is a name that is used to track all CLI command information.
  1681. * @param value the data to send to the external data store under the provided name argument
  1682. */
  1683. async function sendMetric(sys, config, name, value) {
  1684. const session_id = await getTelemetryToken(sys);
  1685. const message = {
  1686. name,
  1687. timestamp: new Date().toISOString(),
  1688. source: 'stencil_cli',
  1689. value,
  1690. session_id,
  1691. };
  1692. await sendTelemetry(sys, config, message);
  1693. }
  1694. /**
  1695. * Used to read the config file's tokens.telemetry property.
  1696. *
  1697. * @param sys The system where the command is invoked
  1698. * @returns string
  1699. */
  1700. async function getTelemetryToken(sys) {
  1701. const config = await readConfig(sys);
  1702. if (config['tokens.telemetry'] === undefined) {
  1703. config['tokens.telemetry'] = uuidv4();
  1704. await writeConfig(sys, config);
  1705. }
  1706. return config['tokens.telemetry'];
  1707. }
  1708. /**
  1709. * Issues a request to the telemetry server.
  1710. * @param sys The system where the command is invoked
  1711. * @param config The config passed into the Stencil command
  1712. * @param data Data to be tracked
  1713. */
  1714. async function sendTelemetry(sys, config, data) {
  1715. try {
  1716. const now = new Date().toISOString();
  1717. const body = {
  1718. metrics: [data],
  1719. sent_at: now,
  1720. };
  1721. // This request is only made if telemetry is on.
  1722. const response = await sys.fetch('https://api.ionicjs.com/events/metrics', {
  1723. method: 'POST',
  1724. headers: {
  1725. 'Content-Type': 'application/json',
  1726. },
  1727. body: JSON.stringify(body),
  1728. });
  1729. hasVerbose(config.flags) &&
  1730. console.debug('\nSent %O metric to events service (status: %O)', data.name, response.status, '\n');
  1731. if (response.status !== 204) {
  1732. hasVerbose(config.flags) &&
  1733. console.debug('\nBad response from events service. Request body: %O', response.body.toString(), '\n');
  1734. }
  1735. }
  1736. catch (e) {
  1737. hasVerbose(config.flags) && console.debug('Telemetry request failed:', e);
  1738. }
  1739. }
  1740. /**
  1741. * Checks if telemetry is enabled on this machine
  1742. * @param sys The system where the command is invoked
  1743. * @returns true if telemetry is enabled, false otherwise
  1744. */
  1745. async function checkTelemetry(sys) {
  1746. const config = await readConfig(sys);
  1747. if (config['telemetry.stencil'] === undefined) {
  1748. config['telemetry.stencil'] = true;
  1749. await writeConfig(sys, config);
  1750. }
  1751. return config['telemetry.stencil'];
  1752. }
  1753. /**
  1754. * Writes to the config file, enabling telemetry for this machine.
  1755. * @param sys The system where the command is invoked
  1756. * @returns true if writing the file was successful, false otherwise
  1757. */
  1758. async function enableTelemetry(sys) {
  1759. return await updateConfig(sys, { 'telemetry.stencil': true });
  1760. }
  1761. /**
  1762. * Writes to the config file, disabling telemetry for this machine.
  1763. * @param sys The system where the command is invoked
  1764. * @returns true if writing the file was successful, false otherwise
  1765. */
  1766. async function disableTelemetry(sys) {
  1767. return await updateConfig(sys, { 'telemetry.stencil': false });
  1768. }
  1769. /**
  1770. * Takes in a semver string in order to return the major version.
  1771. * @param version The fully qualified semver version
  1772. * @returns a string of the major version
  1773. */
  1774. function getMajorVersion(version) {
  1775. const parts = version.split('.');
  1776. return parts[0];
  1777. }
  1778. const taskBuild = async (coreCompiler, config) => {
  1779. if (config.flags.watch) {
  1780. // watch build
  1781. await taskWatch(coreCompiler, config);
  1782. return;
  1783. }
  1784. // one-time build
  1785. let exitCode = 0;
  1786. try {
  1787. startupCompilerLog(coreCompiler, config);
  1788. const versionChecker = startCheckVersion(config, coreCompiler.version);
  1789. const compiler = await coreCompiler.createCompiler(config);
  1790. const results = await compiler.build();
  1791. await telemetryBuildFinishedAction(config.sys, config, coreCompiler, results);
  1792. await compiler.destroy();
  1793. if (results.hasError) {
  1794. exitCode = 1;
  1795. }
  1796. else if (config.flags.prerender) {
  1797. const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.hydrateAppFilePath, results.componentGraph, null);
  1798. config.logger.printDiagnostics(prerenderDiagnostics);
  1799. if (prerenderDiagnostics.some((d) => d.level === 'error')) {
  1800. exitCode = 1;
  1801. }
  1802. }
  1803. await printCheckVersionResults(versionChecker);
  1804. }
  1805. catch (e) {
  1806. exitCode = 1;
  1807. config.logger.error(e);
  1808. }
  1809. if (exitCode > 0) {
  1810. return config.sys.exit(exitCode);
  1811. }
  1812. };
  1813. const taskDocs = async (coreCompiler, config) => {
  1814. config.devServer = null;
  1815. config.outputTargets = config.outputTargets.filter(isOutputTargetDocs);
  1816. config.devMode = true;
  1817. startupCompilerLog(coreCompiler, config);
  1818. const compiler = await coreCompiler.createCompiler(config);
  1819. await compiler.build();
  1820. await compiler.destroy();
  1821. };
  1822. /**
  1823. * Task to generate component boilerplate and write it to disk. This task can
  1824. * cause the program to exit with an error under various circumstances, such as
  1825. * being called in an inappropriate place, being asked to overwrite files that
  1826. * already exist, etc.
  1827. *
  1828. * @param coreCompiler the CoreCompiler we're using currently, here we're
  1829. * mainly accessing the `path` module
  1830. * @param config the user-supplied config, which we need here to access `.sys`.
  1831. */
  1832. const taskGenerate = async (coreCompiler, config) => {
  1833. if (!IS_NODE_ENV) {
  1834. config.logger.error(`"generate" command is currently only implemented for a NodeJS environment`);
  1835. return config.sys.exit(1);
  1836. }
  1837. const path = coreCompiler.path;
  1838. if (!config.configPath) {
  1839. config.logger.error('Please run this command in your root directory (i. e. the one containing stencil.config.ts).');
  1840. return config.sys.exit(1);
  1841. }
  1842. const absoluteSrcDir = config.srcDir;
  1843. if (!absoluteSrcDir) {
  1844. config.logger.error(`Stencil's srcDir was not specified.`);
  1845. return config.sys.exit(1);
  1846. }
  1847. const { prompt } = await import('../sys/node/prompts.js');
  1848. const input = config.flags.unknownArgs.find((arg) => !arg.startsWith('-')) ||
  1849. (await prompt({ name: 'tagName', type: 'text', message: 'Component tag name (dash-case):' })).tagName;
  1850. const { dir, base: componentName } = path.parse(input);
  1851. const tagError = validateComponentTag(componentName);
  1852. if (tagError) {
  1853. config.logger.error(tagError);
  1854. return config.sys.exit(1);
  1855. }
  1856. const extensionsToGenerate = ['tsx', ...(await chooseFilesToGenerate())];
  1857. const testFolder = extensionsToGenerate.some(isTest) ? 'test' : '';
  1858. const outDir = path.join(absoluteSrcDir, 'components', dir, componentName);
  1859. await config.sys.createDir(path.join(outDir, testFolder), { recursive: true });
  1860. const filesToGenerate = extensionsToGenerate.map((extension) => ({
  1861. extension,
  1862. path: getFilepathForFile(coreCompiler, outDir, componentName, extension),
  1863. }));
  1864. await checkForOverwrite(filesToGenerate, config);
  1865. const writtenFiles = await Promise.all(filesToGenerate.map((file) => getBoilerplateAndWriteFile(config, componentName, extensionsToGenerate.includes('css'), file))).catch((error) => config.logger.error(error));
  1866. if (!writtenFiles) {
  1867. return config.sys.exit(1);
  1868. }
  1869. // We use `console.log` here rather than our `config.logger` because we don't want
  1870. // our TUI messages to be prefixed with timestamps and so on.
  1871. //
  1872. // See STENCIL-424 for details.
  1873. console.log();
  1874. console.log(`${config.logger.gray('$')} stencil generate ${input}`);
  1875. console.log();
  1876. console.log(config.logger.bold('The following files have been generated:'));
  1877. const absoluteRootDir = config.rootDir;
  1878. writtenFiles.map((file) => console.log(` - ${path.relative(absoluteRootDir, file)}`));
  1879. };
  1880. /**
  1881. * Show a checkbox prompt to select the files to be generated.
  1882. *
  1883. * @returns a read-only array of `GenerableExtension`, the extensions that the user has decided
  1884. * to generate
  1885. */
  1886. const chooseFilesToGenerate = async () => {
  1887. const { prompt } = await import('../sys/node/prompts.js');
  1888. return (await prompt({
  1889. name: 'filesToGenerate',
  1890. type: 'multiselect',
  1891. message: 'Which additional files do you want to generate?',
  1892. choices: [
  1893. { value: 'css', title: 'Stylesheet (.css)', selected: true },
  1894. { value: 'spec.tsx', title: 'Spec Test (.spec.tsx)', selected: true },
  1895. { value: 'e2e.ts', title: 'E2E Test (.e2e.ts)', selected: true },
  1896. ],
  1897. })).filesToGenerate;
  1898. };
  1899. /**
  1900. * Get a filepath for a file we want to generate!
  1901. *
  1902. * The filepath for a given file depends on the path, the user-supplied
  1903. * component name, the extension, and whether we're inside of a test directory.
  1904. *
  1905. * @param coreCompiler the compiler we're using, here to acces the `.path` module
  1906. * @param path path to where we're going to generate the component
  1907. * @param componentName the user-supplied name for the generated component
  1908. * @param extension the file extension
  1909. * @returns the full filepath to the component (with a possible `test` directory
  1910. * added)
  1911. */
  1912. const getFilepathForFile = (coreCompiler, path, componentName, extension) => isTest(extension)
  1913. ? coreCompiler.path.join(path, 'test', `${componentName}.${extension}`)
  1914. : coreCompiler.path.join(path, `${componentName}.${extension}`);
  1915. /**
  1916. * Get the boilerplate for a file and write it to disk
  1917. *
  1918. * @param config the current config, needed for file operations
  1919. * @param componentName the component name (user-supplied)
  1920. * @param withCss are we generating CSS?
  1921. * @param file the file we want to write
  1922. * @returns a `Promise<string>` which holds the full filepath we've written to,
  1923. * used to print out a little summary of our activity to the user.
  1924. */
  1925. const getBoilerplateAndWriteFile = async (config, componentName, withCss, file) => {
  1926. const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss);
  1927. await config.sys.writeFile(file.path, boilerplate);
  1928. return file.path;
  1929. };
  1930. /**
  1931. * Check to see if any of the files we plan to write already exist and would
  1932. * therefore be overwritten if we proceed, because we'd like to not overwrite
  1933. * people's code!
  1934. *
  1935. * This function will check all the filepaths and if it finds any files log an
  1936. * error and exit with an error code. If it doesn't find anything it will just
  1937. * peacefully return `Promise<void>`.
  1938. *
  1939. * @param files the files we want to check
  1940. * @param config the Config object, used here to get access to `sys.readFile`
  1941. */
  1942. const checkForOverwrite = async (files, config) => {
  1943. const alreadyPresent = [];
  1944. await Promise.all(files.map(async ({ path }) => {
  1945. if ((await config.sys.readFile(path)) !== undefined) {
  1946. alreadyPresent.push(path);
  1947. }
  1948. }));
  1949. if (alreadyPresent.length > 0) {
  1950. config.logger.error('Generating code would overwrite the following files:', ...alreadyPresent.map((path) => '\t' + path));
  1951. await config.sys.exit(1);
  1952. }
  1953. };
  1954. /**
  1955. * Check if an extension is for a test
  1956. *
  1957. * @param extension the extension we want to check
  1958. * @returns a boolean indicating whether or not its a test
  1959. */
  1960. const isTest = (extension) => {
  1961. return extension === 'e2e.ts' || extension === 'spec.tsx';
  1962. };
  1963. /**
  1964. * Get the boilerplate for a file by its extension.
  1965. *
  1966. * @param tagName the name of the component we're generating
  1967. * @param extension the file extension we want boilerplate for (.css, tsx, etc)
  1968. * @param withCss a boolean indicating whether we're generating a CSS file
  1969. * @returns a string container the file boilerplate for the supplied extension
  1970. */
  1971. const getBoilerplateByExtension = (tagName, extension, withCss) => {
  1972. switch (extension) {
  1973. case 'tsx':
  1974. return getComponentBoilerplate(tagName, withCss);
  1975. case 'css':
  1976. return getStyleUrlBoilerplate();
  1977. case 'spec.tsx':
  1978. return getSpecTestBoilerplate(tagName);
  1979. case 'e2e.ts':
  1980. return getE2eTestBoilerplate(tagName);
  1981. default:
  1982. throw new Error(`Unkown extension "${extension}".`);
  1983. }
  1984. };
  1985. /**
  1986. * Get the boilerplate for a file containing the definition of a component
  1987. * @param tagName the name of the tag to give the component
  1988. * @param hasStyle designates if the component has an external stylesheet or not
  1989. * @returns the contents of a file that defines a component
  1990. */
  1991. const getComponentBoilerplate = (tagName, hasStyle) => {
  1992. const decorator = [`{`];
  1993. decorator.push(` tag: '${tagName}',`);
  1994. if (hasStyle) {
  1995. decorator.push(` styleUrl: '${tagName}.css',`);
  1996. }
  1997. decorator.push(` shadow: true,`);
  1998. decorator.push(`}`);
  1999. return `import { Component, Host, h } from '@stencil/core';
  2000. @Component(${decorator.join('\n')})
  2001. export class ${toPascalCase(tagName)} {
  2002. render() {
  2003. return (
  2004. <Host>
  2005. <slot></slot>
  2006. </Host>
  2007. );
  2008. }
  2009. }
  2010. `;
  2011. };
  2012. /**
  2013. * Get the boilerplate for style for a generated component
  2014. * @returns a boilerplate CSS block
  2015. */
  2016. const getStyleUrlBoilerplate = () => `:host {
  2017. display: block;
  2018. }
  2019. `;
  2020. /**
  2021. * Get the boilerplate for a file containing a spec (unit) test for a component
  2022. * @param tagName the name of the tag associated with the component under test
  2023. * @returns the contents of a file that unit tests a component
  2024. */
  2025. const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@stencil/core/testing';
  2026. import { ${toPascalCase(tagName)} } from '../${tagName}';
  2027. describe('${tagName}', () => {
  2028. it('renders', async () => {
  2029. const page = await newSpecPage({
  2030. components: [${toPascalCase(tagName)}],
  2031. html: \`<${tagName}></${tagName}>\`,
  2032. });
  2033. expect(page.root).toEqualHtml(\`
  2034. <${tagName}>
  2035. <mock:shadow-root>
  2036. <slot></slot>
  2037. </mock:shadow-root>
  2038. </${tagName}>
  2039. \`);
  2040. });
  2041. });
  2042. `;
  2043. /**
  2044. * Get the boilerplate for a file containing an end-to-end (E2E) test for a component
  2045. * @param tagName the name of the tag associated with the component under test
  2046. * @returns the contents of a file that E2E tests a component
  2047. */
  2048. const getE2eTestBoilerplate = (tagName) => `import { newE2EPage } from '@stencil/core/testing';
  2049. describe('${tagName}', () => {
  2050. it('renders', async () => {
  2051. const page = await newE2EPage();
  2052. await page.setContent('<${tagName}></${tagName}>');
  2053. const element = await page.find('${tagName}');
  2054. expect(element).toHaveClass('hydrated');
  2055. });
  2056. });
  2057. `;
  2058. /**
  2059. * Convert a dash case string to pascal case.
  2060. * @param str the string to convert
  2061. * @returns the converted input as pascal case
  2062. */
  2063. const toPascalCase = (str) => str.split('-').reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), '');
  2064. /**
  2065. * Entrypoint for the Telemetry task
  2066. * @param flags configuration flags provided to Stencil when a task was called (either this task or a task that invokes
  2067. * telemetry)
  2068. * @param sys the abstraction for interfacing with the operating system
  2069. * @param logger a logging implementation to log the results out to the user
  2070. */
  2071. const taskTelemetry = async (flags, sys, logger) => {
  2072. const prompt = logger.dim(sys.details.platform === 'windows' ? '>' : '$');
  2073. const isEnabling = flags.args.includes('on');
  2074. const isDisabling = flags.args.includes('off');
  2075. const INFORMATION = `Opt in or out of telemetry. Information about the data we collect is available on our website: ${logger.bold('https://stenciljs.com/telemetry')}`;
  2076. const THANK_YOU = `Thank you for helping to make Stencil better! 💖`;
  2077. const ENABLED_MESSAGE = `${logger.green('Enabled')}. ${THANK_YOU}\n\n`;
  2078. const DISABLED_MESSAGE = `${logger.red('Disabled')}\n\n`;
  2079. const hasTelemetry = await checkTelemetry(sys);
  2080. if (isEnabling) {
  2081. const result = await enableTelemetry(sys);
  2082. result
  2083. ? console.log(`\n ${logger.bold('Telemetry is now ') + ENABLED_MESSAGE}`)
  2084. : console.log(`Something went wrong when enabling Telemetry.`);
  2085. return;
  2086. }
  2087. if (isDisabling) {
  2088. const result = await disableTelemetry(sys);
  2089. result
  2090. ? console.log(`\n ${logger.bold('Telemetry is now ') + DISABLED_MESSAGE}`)
  2091. : console.log(`Something went wrong when disabling Telemetry.`);
  2092. return;
  2093. }
  2094. console.log(` ${logger.bold('Telemetry:')} ${logger.dim(INFORMATION)}`);
  2095. console.log(`\n ${logger.bold('Status')}: ${hasTelemetry ? ENABLED_MESSAGE : DISABLED_MESSAGE}`);
  2096. console.log(` ${prompt} ${logger.green('stencil telemetry [off|on]')}
  2097. ${logger.cyan('off')} ${logger.dim('.............')} Disable sharing anonymous usage data
  2098. ${logger.cyan('on')} ${logger.dim('..............')} Enable sharing anonymous usage data
  2099. `);
  2100. };
  2101. /**
  2102. * Entrypoint for the Help task, providing Stencil usage context to the user
  2103. * @param flags configuration flags provided to Stencil when a task was call (either this task or a task that invokes
  2104. * telemetry)
  2105. * @param logger a logging implementation to log the results out to the user
  2106. * @param sys the abstraction for interfacing with the operating system
  2107. */
  2108. const taskHelp = async (flags, logger, sys) => {
  2109. const prompt = logger.dim(sys.details.platform === 'windows' ? '>' : '$');
  2110. console.log(`
  2111. ${logger.bold('Build:')} ${logger.dim('Build components for development or production.')}
  2112. ${prompt} ${logger.green('stencil build [--dev] [--watch] [--prerender] [--debug]')}
  2113. ${logger.cyan('--dev')} ${logger.dim('.............')} Development build
  2114. ${logger.cyan('--watch')} ${logger.dim('...........')} Rebuild when files update
  2115. ${logger.cyan('--serve')} ${logger.dim('...........')} Start the dev-server
  2116. ${logger.cyan('--prerender')} ${logger.dim('.......')} Prerender the application
  2117. ${logger.cyan('--docs')} ${logger.dim('............')} Generate component readme.md docs
  2118. ${logger.cyan('--config')} ${logger.dim('..........')} Set stencil config file
  2119. ${logger.cyan('--stats')} ${logger.dim('...........')} Write stencil-stats.json file
  2120. ${logger.cyan('--log')} ${logger.dim('.............')} Write stencil-build.log file
  2121. ${logger.cyan('--debug')} ${logger.dim('...........')} Set the log level to debug
  2122. ${logger.bold('Test:')} ${logger.dim('Run unit and end-to-end tests.')}
  2123. ${prompt} ${logger.green('stencil test [--spec] [--e2e]')}
  2124. ${logger.cyan('--spec')} ${logger.dim('............')} Run unit tests with Jest
  2125. ${logger.cyan('--e2e')} ${logger.dim('.............')} Run e2e tests with Puppeteer
  2126. ${logger.bold('Generate:')} ${logger.dim('Bootstrap components.')}
  2127. ${prompt} ${logger.green('stencil generate')} or ${logger.green('stencil g')}
  2128. `);
  2129. await taskTelemetry(flags, sys, logger);
  2130. console.log(`
  2131. ${logger.bold('Examples:')}
  2132. ${prompt} ${logger.green('stencil build --dev --watch --serve')}
  2133. ${prompt} ${logger.green('stencil build --prerender')}
  2134. ${prompt} ${logger.green('stencil test --spec --e2e')}
  2135. ${prompt} ${logger.green('stencil telemetry on')}
  2136. ${prompt} ${logger.green('stencil generate')}
  2137. ${prompt} ${logger.green('stencil g my-component')}
  2138. `);
  2139. };
  2140. const taskInfo = (coreCompiler, sys, logger) => {
  2141. const details = sys.details;
  2142. const versions = coreCompiler.versions;
  2143. console.log(``);
  2144. console.log(`${logger.cyan(' System:')} ${sys.name} ${sys.version}`);
  2145. console.log(`${logger.cyan(' Plaform:')} ${details.platform} (${details.release})`);
  2146. console.log(`${logger.cyan(' CPU Model:')} ${details.cpuModel} (${sys.hardwareConcurrency} cpu${sys.hardwareConcurrency !== 1 ? 's' : ''})`);
  2147. console.log(`${logger.cyan(' Compiler:')} ${sys.getCompilerExecutingPath()}`);
  2148. console.log(`${logger.cyan(' Build:')} ${coreCompiler.buildId}`);
  2149. console.log(`${logger.cyan(' Stencil:')} ${coreCompiler.version}${logger.emoji(' ' + coreCompiler.vermoji)}`);
  2150. console.log(`${logger.cyan(' TypeScript:')} ${versions.typescript}`);
  2151. console.log(`${logger.cyan(' Rollup:')} ${versions.rollup}`);
  2152. console.log(`${logger.cyan(' Parse5:')} ${versions.parse5}`);
  2153. console.log(`${logger.cyan(' Sizzle:')} ${versions.sizzle}`);
  2154. console.log(`${logger.cyan(' Terser:')} ${versions.terser}`);
  2155. console.log(``);
  2156. };
  2157. const taskServe = async (config) => {
  2158. config.suppressLogs = true;
  2159. config.flags.serve = true;
  2160. config.devServer.openBrowser = config.flags.open;
  2161. config.devServer.reloadStrategy = null;
  2162. config.devServer.initialLoadUrl = '/';
  2163. config.devServer.websocket = false;
  2164. config.maxConcurrentWorkers = 1;
  2165. config.devServer.root = isString(config.flags.root) ? config.flags.root : config.sys.getCurrentDirectory();
  2166. const devServerPath = config.sys.getDevServerExecutingPath();
  2167. const { start } = await config.sys.dynamicImport(devServerPath);
  2168. const devServer = await start(config.devServer, config.logger);
  2169. console.log(`${config.logger.cyan(' Root:')} ${devServer.root}`);
  2170. console.log(`${config.logger.cyan(' Address:')} ${devServer.address}`);
  2171. console.log(`${config.logger.cyan(' Port:')} ${devServer.port}`);
  2172. console.log(`${config.logger.cyan(' Server:')} ${devServer.browserUrl}`);
  2173. console.log(``);
  2174. config.sys.onProcessInterrupt(() => {
  2175. if (devServer) {
  2176. config.logger.debug(`dev server close: ${devServer.browserUrl}`);
  2177. devServer.close();
  2178. }
  2179. });
  2180. };
  2181. /**
  2182. * Entrypoint for any Stencil tests
  2183. * @param config a validated Stencil configuration entity
  2184. */
  2185. const taskTest = async (config) => {
  2186. if (!IS_NODE_ENV) {
  2187. config.logger.error(`"test" command is currently only implemented for a NodeJS environment`);
  2188. return config.sys.exit(1);
  2189. }
  2190. config.buildDocs = false;
  2191. const testingRunOpts = {
  2192. e2e: !!config.flags.e2e,
  2193. screenshot: !!config.flags.screenshot,
  2194. spec: !!config.flags.spec,
  2195. updateScreenshot: !!config.flags.updateScreenshot,
  2196. };
  2197. // always ensure we have jest modules installed
  2198. const ensureModuleIds = ['@types/jest', 'jest', 'jest-cli'];
  2199. if (testingRunOpts.e2e) {
  2200. // if it's an e2e test, also make sure we're got
  2201. // puppeteer modules installed and if browserExecutablePath is provided don't download Chromium use only puppeteer-core instead
  2202. const puppeteer = config.testing.browserExecutablePath ? 'puppeteer-core' : 'puppeteer';
  2203. ensureModuleIds.push(puppeteer);
  2204. if (testingRunOpts.screenshot) {
  2205. // ensure we've got pixelmatch for screenshots
  2206. config.logger.warn(config.logger.yellow(`EXPERIMENTAL: screenshot visual diff testing is currently under heavy development and has not reached a stable status. However, any assistance testing would be appreciated.`));
  2207. }
  2208. }
  2209. // ensure we've got the required modules installed
  2210. const diagnostics = await config.sys.lazyRequire.ensure(config.rootDir, ensureModuleIds);
  2211. if (diagnostics.length > 0) {
  2212. config.logger.printDiagnostics(diagnostics);
  2213. return config.sys.exit(1);
  2214. }
  2215. try {
  2216. // let's test!
  2217. const { createTesting } = await import('../testing/index.js');
  2218. const testing = await createTesting(config);
  2219. const passed = await testing.run(testingRunOpts);
  2220. await testing.destroy();
  2221. if (!passed) {
  2222. return config.sys.exit(1);
  2223. }
  2224. }
  2225. catch (e) {
  2226. config.logger.error(e);
  2227. return config.sys.exit(1);
  2228. }
  2229. };
  2230. const run = async (init) => {
  2231. const { args, logger, sys } = init;
  2232. try {
  2233. const flags = parseFlags(args);
  2234. const task = flags.task;
  2235. if (flags.debug || flags.verbose) {
  2236. logger.setLevel('debug');
  2237. }
  2238. if (flags.ci) {
  2239. logger.enableColors(false);
  2240. }
  2241. if (isFunction(sys.applyGlobalPatch)) {
  2242. sys.applyGlobalPatch(sys.getCurrentDirectory());
  2243. }
  2244. if (!task || task === 'help' || flags.help) {
  2245. await taskHelp(createConfigFlags({ task: 'help', args }), logger, sys);
  2246. return;
  2247. }
  2248. startupLog(logger, task);
  2249. const findConfigResults = await findConfig({ sys, configPath: flags.config });
  2250. if (hasError(findConfigResults.diagnostics)) {
  2251. logger.printDiagnostics(findConfigResults.diagnostics);
  2252. return sys.exit(1);
  2253. }
  2254. const ensureDepsResults = await sys.ensureDependencies({
  2255. rootDir: findConfigResults.rootDir,
  2256. logger,
  2257. dependencies: dependencies,
  2258. });
  2259. if (hasError(ensureDepsResults.diagnostics)) {
  2260. logger.printDiagnostics(ensureDepsResults.diagnostics);
  2261. return sys.exit(1);
  2262. }
  2263. const coreCompiler = await loadCoreCompiler(sys);
  2264. if (task === 'version' || flags.version) {
  2265. console.log(coreCompiler.version);
  2266. return;
  2267. }
  2268. startupLogVersion(logger, task, coreCompiler);
  2269. loadedCompilerLog(sys, logger, flags, coreCompiler);
  2270. if (task === 'info') {
  2271. taskInfo(coreCompiler, sys, logger);
  2272. return;
  2273. }
  2274. const validated = await coreCompiler.loadConfig({
  2275. config: {
  2276. flags,
  2277. },
  2278. configPath: findConfigResults.configPath,
  2279. logger,
  2280. sys,
  2281. });
  2282. if (validated.diagnostics.length > 0) {
  2283. logger.printDiagnostics(validated.diagnostics);
  2284. if (hasError(validated.diagnostics)) {
  2285. return sys.exit(1);
  2286. }
  2287. }
  2288. if (isFunction(sys.applyGlobalPatch)) {
  2289. sys.applyGlobalPatch(validated.config.rootDir);
  2290. }
  2291. await sys.ensureResources({ rootDir: validated.config.rootDir, logger, dependencies: dependencies });
  2292. await telemetryAction(sys, validated.config, coreCompiler, async () => {
  2293. await runTask(coreCompiler, validated.config, task, sys);
  2294. });
  2295. }
  2296. catch (e) {
  2297. if (!shouldIgnoreError(e)) {
  2298. const details = `${logger.getLevel() === 'debug' && e instanceof Error ? e.stack : ''}`;
  2299. logger.error(`uncaught cli error: ${e}${details}`);
  2300. return sys.exit(1);
  2301. }
  2302. }
  2303. };
  2304. /**
  2305. * Run a specified task
  2306. * @param coreCompiler an instance of a minimal, bootstrap compiler for running the specified task
  2307. * @param config a configuration for the Stencil project to apply to the task run
  2308. * @param task the task to run
  2309. * @param sys the {@link CompilerSystem} for interacting with the operating system
  2310. * @public
  2311. */
  2312. const runTask = async (coreCompiler, config, task, sys) => {
  2313. var _a, _b, _c, _d, _e, _f;
  2314. const logger = (_a = config.logger) !== null && _a !== void 0 ? _a : createLogger();
  2315. const strictConfig = {
  2316. ...config,
  2317. flags: createConfigFlags((_b = config.flags) !== null && _b !== void 0 ? _b : { task }),
  2318. logger,
  2319. outputTargets: (_c = config.outputTargets) !== null && _c !== void 0 ? _c : [],
  2320. rootDir: (_d = config.rootDir) !== null && _d !== void 0 ? _d : '/',
  2321. sys: (_e = sys !== null && sys !== void 0 ? sys : config.sys) !== null && _e !== void 0 ? _e : coreCompiler.createSystem({ logger }),
  2322. testing: (_f = config.testing) !== null && _f !== void 0 ? _f : {},
  2323. };
  2324. switch (task) {
  2325. case 'build':
  2326. await taskBuild(coreCompiler, strictConfig);
  2327. break;
  2328. case 'docs':
  2329. await taskDocs(coreCompiler, strictConfig);
  2330. break;
  2331. case 'generate':
  2332. case 'g':
  2333. await taskGenerate(coreCompiler, strictConfig);
  2334. break;
  2335. case 'help':
  2336. await taskHelp(strictConfig.flags, strictConfig.logger, sys);
  2337. break;
  2338. case 'prerender':
  2339. await taskPrerender(coreCompiler, strictConfig);
  2340. break;
  2341. case 'serve':
  2342. await taskServe(strictConfig);
  2343. break;
  2344. case 'telemetry':
  2345. await taskTelemetry(strictConfig.flags, sys, strictConfig.logger);
  2346. break;
  2347. case 'test':
  2348. await taskTest(strictConfig);
  2349. break;
  2350. case 'version':
  2351. console.log(coreCompiler.version);
  2352. break;
  2353. default:
  2354. strictConfig.logger.error(`${strictConfig.logger.emoji('❌ ')}Invalid stencil command, please see the options below:`);
  2355. await taskHelp(strictConfig.flags, strictConfig.logger, sys);
  2356. return config.sys.exit(1);
  2357. }
  2358. };
  2359. export { parseFlags, run, runTask };
  2360. //# sourceMappingURL=index.js.map