index.cjs 90 KB

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