diff --git a/src/cli/run.ts b/src/cli/run.ts index 39473396f21..bcc60c94a74 100644 --- a/src/cli/run.ts +++ b/src/cli/run.ts @@ -104,7 +104,8 @@ export const run = async (init: d.CliInitOptions) => { }); } catch (e) { if (!shouldIgnoreError(e)) { - logger.error(`uncaught cli error: ${e}${logger.getLevel() === 'debug' ? e.stack : ''}`); + const details = `${logger.getLevel() === 'debug' && e instanceof Error ? e.stack : ''}`; + logger.error(`uncaught cli error: ${e}${details}`); return sys.exit(1); } } diff --git a/src/cli/task-prerender.ts b/src/cli/task-prerender.ts index b1ffe7f6378..a83c0c9b166 100644 --- a/src/cli/task-prerender.ts +++ b/src/cli/task-prerender.ts @@ -41,7 +41,7 @@ export const runPrerenderTask = async ( }); diagnostics.push(...results.diagnostics); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } diff --git a/src/compiler/build/build-stats.ts b/src/compiler/build/build-stats.ts index c364c774dc4..7d0cf60765b 100644 --- a/src/compiler/build/build-stats.ts +++ b/src/compiler/build/build-stats.ts @@ -60,9 +60,14 @@ export function generateBuildStats( jsonData = stats; } - } catch (e) { + } catch (e: unknown) { + const diagnostic: d.Diagnostic = { + messageText: `Generate Build Stats Error: ` + e, + level: `error`, + type: `build`, + }; jsonData = { - diagnostics: [e.message], + diagnostics: [diagnostic], }; } diff --git a/src/compiler/build/build.ts b/src/compiler/build/build.ts index 4213733256b..143d7bd500e 100644 --- a/src/compiler/build/build.ts +++ b/src/compiler/build/build.ts @@ -55,7 +55,7 @@ export const build = async ( // write outputs await buildCtx.stylesPromise; await writeBuild(config, compilerCtx, buildCtx); - } catch (e) { + } catch (e: any) { // ¯\_(ツ)_/¯ catchError(buildCtx.diagnostics, e); } diff --git a/src/compiler/build/write-build.ts b/src/compiler/build/write-build.ts index bdc2ec7f3c0..83f38da3d96 100644 --- a/src/compiler/build/write-build.ts +++ b/src/compiler/build/write-build.ts @@ -26,7 +26,7 @@ export const writeBuild = async (config: d.Config, compilerCtx: d.CompilerCtx, b // buildCtx.debug(`cache: ${compilerCtx.cache.getMemoryStats()}`); await outputServiceWorkers(config, buildCtx), await validateBuildFiles(config, compilerCtx, buildCtx); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } diff --git a/src/compiler/bundle/bundle-output.ts b/src/compiler/bundle/bundle-output.ts index 69c16e7c36a..5b5cdcce1ed 100644 --- a/src/compiler/bundle/bundle-output.ts +++ b/src/compiler/bundle/bundle-output.ts @@ -30,8 +30,10 @@ export const bundleOutput = async ( compilerCtx.rollupCache.set(bundleOpts.id, rollupBuild.cache); return rollupBuild; - } catch (e) { + } catch (e: any) { if (!buildCtx.hasError) { + // TODO(STENCIL-353): Implement a type guard that balances using our own copy of Rollup types (which are + // breakable) and type safety (so that the error variable may be something other than `any`) loadRollupDiagnostics(config, compilerCtx, buildCtx, e); } } diff --git a/src/compiler/bundle/dev-module.ts b/src/compiler/bundle/dev-module.ts index 897626d3892..356cd8b2b40 100644 --- a/src/compiler/bundle/dev-module.ts +++ b/src/compiler/bundle/dev-module.ts @@ -111,9 +111,9 @@ export const compilerRequest = async (config: d.Config, compilerCtx: d.CompilerC results.status = 400; return results; } - } catch (e) { + } catch (e: unknown) { if (e) { - if (e.stack) { + if (e instanceof Error && e.stack) { results.content = `/*\n${e.stack}\n*/`; } else { results.content = `/*\n${e}\n*/`; @@ -165,7 +165,8 @@ const bundleDevModule = async ( } } catch (e) { results.status = 500; - results.content = `console.error(${JSON.stringify((e.stack || e) + '')})`; + const errorMsg = e instanceof Error ? e.stack : e + ''; + results.content = `console.error(${JSON.stringify(errorMsg)})`; } }; diff --git a/src/compiler/config/load-config.ts b/src/compiler/config/load-config.ts index 43f49498feb..e2eef18551d 100644 --- a/src/compiler/config/load-config.ts +++ b/src/compiler/config/load-config.ts @@ -82,7 +82,7 @@ export const loadConfig = async (init: LoadConfigInit = {}) => { results.tsconfig.exclude = tsConfigResults.exclude; results.tsconfig.extends = tsConfigResults.extends; } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } @@ -131,7 +131,7 @@ const evaluateConfigFile = async (sys: CompilerSystem, diagnostics: Diagnostic[] const evalConfig = new Function(`const exports = {}; ${sourceText}; return exports;`); configFileData = evalConfig(); } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } diff --git a/src/compiler/config/outputs/validate-custom-output.ts b/src/compiler/config/outputs/validate-custom-output.ts index b3d82fac7bf..9694df67ec5 100644 --- a/src/compiler/config/outputs/validate-custom-output.ts +++ b/src/compiler/config/outputs/validate-custom-output.ts @@ -8,7 +8,7 @@ export const validateCustomOutput = (config: d.Config, diagnostics: d.Diagnostic const localDiagnostics: d.Diagnostic[] = []; try { o.validate(config, diagnostics); - } catch (e) { + } catch (e: any) { catchError(localDiagnostics, e); } if (o.copy && o.copy.length > 0) { diff --git a/src/compiler/html/remove-unused-styles.ts b/src/compiler/html/remove-unused-styles.ts index 59a5d7df5dc..33b6624ca4e 100644 --- a/src/compiler/html/remove-unused-styles.ts +++ b/src/compiler/html/remove-unused-styles.ts @@ -18,7 +18,7 @@ export const removeUnusedStyles = (doc: Document, diagnostics: d.Diagnostic[]) = removeUnusedStyleText(usedSelectors, diagnostics, styleElms[i]); } } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } }; @@ -43,7 +43,7 @@ const removeUnusedStyleText = ( styleElm.innerHTML = serializeCss(parseResults.stylesheet, { usedSelectors, }); - } catch (e) { + } catch (e: any) { diagnostics.push({ level: 'warn', type: 'css', @@ -51,7 +51,7 @@ const removeUnusedStyleText = ( messageText: e, }); } - } catch (e) { + } catch (e: any) { diagnostics.push({ level: 'warn', type: 'css', diff --git a/src/compiler/optimize/autoprefixer.ts b/src/compiler/optimize/autoprefixer.ts index f1c7ac47320..2f459901480 100644 --- a/src/compiler/optimize/autoprefixer.ts +++ b/src/compiler/optimize/autoprefixer.ts @@ -28,7 +28,7 @@ export const autoprefixCss = async (cssText: string, opts: any) => { }); output.output = result.css; - } catch (e) { + } catch (e: any) { const diagnostic: d.Diagnostic = { header: `Autoprefix CSS`, messageText: `CSS Error` + e, diff --git a/src/compiler/optimize/minify-js.ts b/src/compiler/optimize/minify-js.ts index 2cb7b74fa42..768d6395055 100644 --- a/src/compiler/optimize/minify-js.ts +++ b/src/compiler/optimize/minify-js.ts @@ -45,7 +45,9 @@ export const minifyJs = async (input: string, opts?: MinifyOptions): Promise { result.output = minifyResults.output; result.sourceMap = minifyResults.sourceMap; } - } catch (e) { + } catch (e: any) { catchError(result.diagnostics, e); } diff --git a/src/compiler/output-targets/copy/output-copy.ts b/src/compiler/output-targets/copy/output-copy.ts index 10cc286ac1d..1ade8da7a73 100644 --- a/src/compiler/output-targets/copy/output-copy.ts +++ b/src/compiler/output-targets/copy/output-copy.ts @@ -35,7 +35,9 @@ export const outputCopy = async (config: d.Config, compilerCtx: d.CompilerCtx, b } } catch (e) { const err = buildError(buildCtx.diagnostics); - err.messageText = e.message; + if (e instanceof Error) { + err.messageText = e.message; + } } timespan.finish(`copy finished (${copiedFiles} file${copiedFiles === 1 ? '' : 's'})`); } diff --git a/src/compiler/output-targets/dist-collection/index.ts b/src/compiler/output-targets/dist-collection/index.ts index 7ad6fe06fc6..33c1d0feeb9 100644 --- a/src/compiler/output-targets/dist-collection/index.ts +++ b/src/compiler/output-targets/dist-collection/index.ts @@ -43,7 +43,7 @@ export const outputCollection = async ( ); await writeCollectionManifests(config, compilerCtx, buildCtx, outputTargets); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } diff --git a/src/compiler/output-targets/dist-custom-elements-bundle/index.ts b/src/compiler/output-targets/dist-custom-elements-bundle/index.ts index 6a89c988f5e..ebd966076e9 100644 --- a/src/compiler/output-targets/dist-custom-elements-bundle/index.ts +++ b/src/compiler/output-targets/dist-custom-elements-bundle/index.ts @@ -111,7 +111,7 @@ const bundleCustomElements = async ( }); await Promise.all(files); } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } }; diff --git a/src/compiler/output-targets/dist-custom-elements/index.ts b/src/compiler/output-targets/dist-custom-elements/index.ts index 891cb329194..72f7e13f272 100644 --- a/src/compiler/output-targets/dist-custom-elements/index.ts +++ b/src/compiler/output-targets/dist-custom-elements/index.ts @@ -118,7 +118,7 @@ const bundleCustomElements = async ( }); await Promise.all(files); } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } }; diff --git a/src/compiler/output-targets/dist-hydrate-script/bundle-hydrate-factory.ts b/src/compiler/output-targets/dist-hydrate-script/bundle-hydrate-factory.ts index aa325ae66ea..e9b1ac1390d 100644 --- a/src/compiler/output-targets/dist-hydrate-script/bundle-hydrate-factory.ts +++ b/src/compiler/output-targets/dist-hydrate-script/bundle-hydrate-factory.ts @@ -32,8 +32,10 @@ export const bundleHydrateFactory = async ( const rollupBuild = await bundleOutput(config, compilerCtx, buildCtx, bundleOpts); return rollupBuild; - } catch (e) { + } catch (e: any) { if (!buildCtx.hasError) { + // TODO(STENCIL-353): Implement a type guard that balances using our own copy of Rollup types (which are + // breakable) and type safety (so that the error variable may be something other than `any`) loadRollupDiagnostics(config, compilerCtx, buildCtx, e); } } diff --git a/src/compiler/output-targets/dist-hydrate-script/generate-hydrate-app.ts b/src/compiler/output-targets/dist-hydrate-script/generate-hydrate-app.ts index 8a654885ca6..6928ee7bfba 100644 --- a/src/compiler/output-targets/dist-hydrate-script/generate-hydrate-app.ts +++ b/src/compiler/output-targets/dist-hydrate-script/generate-hydrate-app.ts @@ -63,8 +63,10 @@ export const generateHydrateApp = async ( }); await writeHydrateOutputs(config, compilerCtx, buildCtx, outputTargets, rollupOutput); - } catch (e) { + } catch (e: any) { if (!buildCtx.hasError) { + // TODO(STENCIL-353): Implement a type guard that balances using our own copy of Rollup types (which are + // breakable) and type safety (so that the error variable may be something other than `any`) loadRollupDiagnostics(config, compilerCtx, buildCtx, e); } } @@ -93,7 +95,7 @@ const generateHydrateFactory = async (config: d.Config, compilerCtx: d.CompilerC return rollupOutput.output[0].code; } } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } } diff --git a/src/compiler/output-targets/dist-lazy/lazy-output.ts b/src/compiler/output-targets/dist-lazy/lazy-output.ts index 460f9114c1a..5466af39e90 100644 --- a/src/compiler/output-targets/dist-lazy/lazy-output.ts +++ b/src/compiler/output-targets/dist-lazy/lazy-output.ts @@ -86,7 +86,7 @@ export const outputLazy = async (config: d.Config, compilerCtx: d.CompilerCtx, b buildCtx.componentGraph = generateModuleGraph(buildCtx.components, buildCtx.esmBrowserComponentBundle); } } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } @@ -120,7 +120,7 @@ function generateEntryModules(config: d.Config, buildCtx: d.BuildCtx): void { try { const bundles = generateComponentBundles(config, buildCtx); buildCtx.entryModules = bundles.map(createEntryModule); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } diff --git a/src/compiler/output-targets/output-custom.ts b/src/compiler/output-targets/output-custom.ts index 348e649eb2a..afbdebf6b96 100644 --- a/src/compiler/output-targets/output-custom.ts +++ b/src/compiler/output-targets/output-custom.ts @@ -19,7 +19,7 @@ export const outputCustom = async ( const timespan = buildCtx.createTimeSpan(`generating ${o.name} started`); try { await o.generator(config, compilerCtx, buildCtx, docs); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } timespan.finish(`generate ${o.name} finished`); diff --git a/src/compiler/output-targets/output-www.ts b/src/compiler/output-targets/output-www.ts index 81de73a8567..17ca01a9803 100644 --- a/src/compiler/output-targets/output-www.ts +++ b/src/compiler/output-targets/output-www.ts @@ -134,7 +134,7 @@ const generateIndexHtml = async ( } buildCtx.debug(`generateIndexHtml, write: ${relative(config.rootDir, outputTarget.indexHtml)}`); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } }; diff --git a/src/compiler/plugin/plugin.ts b/src/compiler/plugin/plugin.ts index 4943f3123c3..d4327ffd79d 100644 --- a/src/compiler/plugin/plugin.ts +++ b/src/compiler/plugin/plugin.ts @@ -21,7 +21,7 @@ export const runPluginResolveId = async (pluginCtx: PluginCtx, importee: string) return results; } } - } catch (e) { + } catch (e: any) { catchError(pluginCtx.diagnostics, e); } } @@ -47,7 +47,7 @@ export const runPluginLoad = async (pluginCtx: PluginCtx, id: string) => { return results; } } - } catch (e) { + } catch (e: any) { catchError(pluginCtx.diagnostics, e); } } @@ -139,7 +139,7 @@ export const runPluginTransforms = async ( } } } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } } @@ -249,7 +249,7 @@ export const runPluginTransformsEsmImports = async ( } } } - } catch (e) { + } catch (e: any) { catchError(transformResults.diagnostics, e); } } diff --git a/src/compiler/prerender/crawl-urls.ts b/src/compiler/prerender/crawl-urls.ts index e53afb957e5..c20e432bc57 100644 --- a/src/compiler/prerender/crawl-urls.ts +++ b/src/compiler/prerender/crawl-urls.ts @@ -29,7 +29,7 @@ export const crawlAnchorsForNextUrls = ( if (userFilterAnchor === false) { return false; } - } catch (e) { + } catch (e: any) { // user filterAnchor() error catchError(diagnostics, e); return false; @@ -49,7 +49,7 @@ export const crawlAnchorsForNextUrls = ( // standard normalizeUrl(), after user normalized return standardNormalizeUrl(diagnostics, userNormalizedUrl.href, currentUrl); - } catch (e) { + } catch (e: any) { // user normalizeUrl() error catchError(diagnostics, e); } @@ -68,7 +68,7 @@ export const crawlAnchorsForNextUrls = ( if (userFilterUrl === false) { return false; } - } catch (e) { + } catch (e: any) { // user filterUrl() error catchError(diagnostics, e); return false; @@ -123,7 +123,7 @@ const standardFilterAnchor = (diagnostics: d.Diagnostic[], attrs: { [attrName: s return true; } } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } @@ -146,7 +146,7 @@ const standardNormalizeUrl = (diagnostics: d.Diagnostic[], href: string, current } return outputUrl; - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } @@ -183,7 +183,7 @@ const standardFilterUrl = (diagnostics: d.Diagnostic[], url: URL, currentUrl: UR } return true; - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } return false; @@ -214,7 +214,7 @@ export const standardNormalizeHref = (prerenderConfig: d.PrerenderConfig, diagno return href; } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } diff --git a/src/compiler/prerender/prerender-hydrate-options.ts b/src/compiler/prerender/prerender-hydrate-options.ts index a371b0ca75c..e46eebc169c 100644 --- a/src/compiler/prerender/prerender-hydrate-options.ts +++ b/src/compiler/prerender/prerender-hydrate-options.ts @@ -23,7 +23,7 @@ export const getHydrateOptions = (prerenderConfig: d.PrerenderConfig, url: URL, } else if (typeof prerenderConfig.canonicalUrl === 'function') { try { opts.canonicalUrl = prerenderConfig.canonicalUrl(url); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } else { @@ -39,7 +39,7 @@ export const getHydrateOptions = (prerenderConfig: d.PrerenderConfig, url: URL, } Object.assign(opts, userOpts); } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } diff --git a/src/compiler/prerender/prerender-main.ts b/src/compiler/prerender/prerender-main.ts index a5986f541a5..a2f16464730 100644 --- a/src/compiler/prerender/prerender-main.ts +++ b/src/compiler/prerender/prerender-main.ts @@ -102,7 +102,7 @@ const runPrerender = async ( ); }) ); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } @@ -247,7 +247,7 @@ const runPrerenderOutputTarget = async ( const statusColor = prerenderBuildErrors.length > 0 ? 'red' : 'green'; timeSpan.finish(`prerendering ${statusMessage}`, statusColor, true); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } }; diff --git a/src/compiler/prerender/prerender-optimize.ts b/src/compiler/prerender/prerender-optimize.ts index 55c2ccfe273..a66b45dc186 100644 --- a/src/compiler/prerender/prerender-optimize.ts +++ b/src/compiler/prerender/prerender-optimize.ts @@ -253,7 +253,7 @@ export const hashAssets = async ( }); sys.writeFileSync(filePath, css); } - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } diff --git a/src/compiler/prerender/prerender-queue.ts b/src/compiler/prerender/prerender-queue.ts index ab9e1172db3..dc7e9bb568d 100644 --- a/src/compiler/prerender/prerender-queue.ts +++ b/src/compiler/prerender/prerender-queue.ts @@ -147,7 +147,7 @@ const prerenderUrl = async (results: d.PrerenderResults, manager: d.PrerenderMan addUrlToPendingQueue(manager, anchorUrl, url); } } - } catch (e) { + } catch (e: any) { // darn, idk, bad news catchError(manager.diagnostics, e); } diff --git a/src/compiler/prerender/prerender-template-html.ts b/src/compiler/prerender/prerender-template-html.ts index 70d76626bd3..adfa91d4b9a 100644 --- a/src/compiler/prerender/prerender-template-html.ts +++ b/src/compiler/prerender/prerender-template-html.ts @@ -58,7 +58,7 @@ export const generateTemplateHtml = async ( if (hydrateOpts.inlineExternalStyleSheets && !isDebug) { try { await inlineExternalStyleSheets(config.sys, outputTarget.appDir, doc); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } @@ -66,7 +66,7 @@ export const generateTemplateHtml = async ( if (hydrateOpts.minifyScriptElements && !isDebug) { try { await minifyScriptElements(doc, true); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } @@ -75,7 +75,7 @@ export const generateTemplateHtml = async ( try { const baseUrl = new URL(outputTarget.baseUrl, manager.devServerHostUrl); await minifyStyleElements(config.sys, outputTarget.appDir, doc, baseUrl, true); - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } @@ -104,7 +104,7 @@ export const generateTemplateHtml = async ( html, staticSite, }; - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } return undefined; diff --git a/src/compiler/prerender/prerender-worker.ts b/src/compiler/prerender/prerender-worker.ts index 67d5d9a49b0..1cb44ab1234 100644 --- a/src/compiler/prerender/prerender-worker.ts +++ b/src/compiler/prerender/prerender-worker.ts @@ -74,7 +74,7 @@ export const prerenderWorker = async (sys: d.CompilerSystem, prerenderRequest: d if (isPromise(rtn)) { await rtn; } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } @@ -90,7 +90,7 @@ export const prerenderWorker = async (sys: d.CompilerSystem, prerenderRequest: d if (typeof userWriteToFilePath === 'string') { results.filePath = userWriteToFilePath; } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } @@ -127,7 +127,7 @@ export const prerenderWorker = async (sys: d.CompilerSystem, prerenderRequest: d docPromises.push( hashAssets(sys, prerenderCtx, results.diagnostics, hydrateOpts, prerenderRequest.appDir, doc, url) ); - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } @@ -152,7 +152,7 @@ export const prerenderWorker = async (sys: d.CompilerSystem, prerenderRequest: d if (isPromise(rtn)) { await rtn; } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } @@ -197,7 +197,7 @@ export const prerenderWorker = async (sys: d.CompilerSystem, prerenderRequest: d try { win.close(); } catch (e) {} - } catch (e) { + } catch (e: any) { // ahh man! what happened! catchError(results.diagnostics, e); } diff --git a/src/compiler/prerender/robots-txt.ts b/src/compiler/prerender/robots-txt.ts index f0cbe98c33a..bf5f797c87a 100644 --- a/src/compiler/prerender/robots-txt.ts +++ b/src/compiler/prerender/robots-txt.ts @@ -65,7 +65,7 @@ export const generateRobotsTxt = async (manager: d.PrerenderManager, sitemapResu await manager.config.sys.writeFile(results.filePath, results.content); return results; - } catch (e) { + } catch (e: any) { catchError(manager.diagnostics, e); return null; } diff --git a/src/compiler/prerender/sitemap-xml.ts b/src/compiler/prerender/sitemap-xml.ts index 1089dfb383a..9d939c288d3 100644 --- a/src/compiler/prerender/sitemap-xml.ts +++ b/src/compiler/prerender/sitemap-xml.ts @@ -65,7 +65,7 @@ export const generateSitemapXml = async (manager: d.PrerenderManager) => { await manager.config.sys.writeFile(results.filePath, results.content); return results; - } catch (e) { + } catch (e: any) { catchError(manager.diagnostics, e); return null; } diff --git a/src/compiler/service-worker/generate-sw.ts b/src/compiler/service-worker/generate-sw.ts index 869b74b0b7b..20b450fcf59 100644 --- a/src/compiler/service-worker/generate-sw.ts +++ b/src/compiler/service-worker/generate-sw.ts @@ -38,7 +38,7 @@ const generateSW = async (buildCtx: d.BuildCtx, serviceWorker: d.ServiceWorkerCo try { await workbox.generateSW(serviceWorker); timeSpan.finish(`generate service worker finished`); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } }; @@ -49,7 +49,7 @@ const injectManifest = async (buildCtx: d.BuildCtx, serviceWorker: d.ServiceWork try { await workbox.injectManifest(serviceWorker); timeSpan.finish('inject manifest into service worker finished'); - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } }; diff --git a/src/compiler/style/css-to-esm.ts b/src/compiler/style/css-to-esm.ts index f14721b8d7f..1f78d9f2bfa 100644 --- a/src/compiler/style/css-to-esm.ts +++ b/src/compiler/style/css-to-esm.ts @@ -81,7 +81,7 @@ const transformCssToEsmModule = (input: d.TransformCssToEsmInput) => { importPath, }); }); - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } diff --git a/src/compiler/style/global-styles.ts b/src/compiler/style/global-styles.ts index cb516164c79..cd5370a4f1e 100644 --- a/src/compiler/style/global-styles.ts +++ b/src/compiler/style/global-styles.ts @@ -56,7 +56,7 @@ const buildGlobalStyles = async (config: d.Config, compilerCtx: d.CompilerCtx, b } return optimizedCss; } - } catch (e) { + } catch (e: any) { const d = catchError(buildCtx.diagnostics, e); d.absFilePath = globalStylePath; } diff --git a/src/compiler/sys/node-require.ts b/src/compiler/sys/node-require.ts index 9fd4df8bd00..f0fc5e4d45e 100644 --- a/src/compiler/sys/node-require.ts +++ b/src/compiler/sys/node-require.ts @@ -49,7 +49,7 @@ export const nodeRequire = (id: string) => { try { module._compile(sourceText, fileName); - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } }; @@ -59,7 +59,7 @@ export const nodeRequire = (id: string) => { // all set, let's go ahead and reset the require back to the default require.extensions['.ts'] = undefined; - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } diff --git a/src/compiler/sys/resolve/resolve-module-sync.ts b/src/compiler/sys/resolve/resolve-module-sync.ts index 09aa988c71a..8f0eebacb8f 100644 --- a/src/compiler/sys/resolve/resolve-module-sync.ts +++ b/src/compiler/sys/resolve/resolve-module-sync.ts @@ -139,9 +139,11 @@ export const createCustomResolverSync = ( const fsFilePath = normalizeFsPath(p); try { return sys.realpathSync(fsFilePath); - } catch (realpathErr) { - if (realpathErr.code !== 'ENOENT') { - throw realpathErr; + } catch (realpathErr: unknown) { + if (isErrnoException(realpathErr)) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } } } return fsFilePath; @@ -150,3 +152,15 @@ export const createCustomResolverSync = ( extensions: exts, } as any; }; + +/** + * Type guard to determine if an Error is an instance of `ErrnoException`. For the purposes of this type guard, we + * must ensure that the `code` field is present. This type guard was written with the `ErrnoException` definition from + * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/d121716ed123957f6a86f8985eb013fcaddab345/types/node/globals.d.ts#L183-L188 + * in mind. + * @param err the entity to check the type of + * @return true if the provided value is an instance of `ErrnoException`, `false` otherwise + */ +function isErrnoException(err: unknown): err is NodeJS.ErrnoException { + return err instanceof Error && err.hasOwnProperty('code'); +} diff --git a/src/compiler/sys/typescript/typescript-config.ts b/src/compiler/sys/typescript/typescript-config.ts index fc121bc46fb..cf4f38cdd56 100644 --- a/src/compiler/sys/typescript/typescript-config.ts +++ b/src/compiler/sys/typescript/typescript-config.ts @@ -98,7 +98,7 @@ export const validateTsConfig = async (config: d.Config, sys: d.CompilerSystem, } } } - } catch (e) { + } catch (e: any) { catchError(tsconfig.diagnostics, e); } diff --git a/src/compiler/transformers/component-native/tranform-to-native-component.ts b/src/compiler/transformers/component-native/tranform-to-native-component.ts index 46d5630dada..cb007d57934 100644 --- a/src/compiler/transformers/component-native/tranform-to-native-component.ts +++ b/src/compiler/transformers/component-native/tranform-to-native-component.ts @@ -50,7 +50,7 @@ export const transformToNativeComponentText = ( if (!buildCtx.hasError && typeof transpileOutput.outputText === 'string') { outputText = transpileOutput.outputText; } - } catch (e) { + } catch (e: any) { catchError(buildCtx.diagnostics, e); } diff --git a/src/compiler/transpile.ts b/src/compiler/transpile.ts index 81875c727c8..bdf7845e159 100644 --- a/src/compiler/transpile.ts +++ b/src/compiler/transpile.ts @@ -23,7 +23,7 @@ export const transpile = async (code: string, opts: TranspileOptions = {}) => { } else if (results.inputFileExtension === 'json') { transpileJson(results); } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } @@ -46,7 +46,7 @@ export const transpileSync = (code: string, opts: TranspileOptions = {}) => { } else if (results.inputFileExtension === 'json') { transpileJson(results); } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } diff --git a/src/dev-server/server-process.ts b/src/dev-server/server-process.ts index 24ac9af8dce..f2c1fde354e 100644 --- a/src/dev-server/server-process.ts +++ b/src/dev-server/server-process.ts @@ -116,8 +116,12 @@ export function initServerProcess(sendMsg: d.DevServerSendMessage) { } } } catch (e) { + let stack: string | null = null; + if (e instanceof Error) { + stack = e.stack; + } sendMsg({ - error: { message: e + '', stack: e?.stack ? e.stack : null }, + error: { message: e + '', stack }, }); } }; diff --git a/src/dev-server/ssr-request.ts b/src/dev-server/ssr-request.ts index 3d77cd202b3..ed587f2971e 100644 --- a/src/dev-server/ssr-request.ts +++ b/src/dev-server/ssr-request.ts @@ -26,7 +26,7 @@ export async function ssrPageRequest( diagnostics.push(...ssrResults.diagnostics); status = ssrResults.httpStatus; content = ssrResults.html; - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } @@ -88,7 +88,7 @@ export async function ssrStaticDataRequest( }); data.components = ssrResults.components.map((c) => c.tag).sort(); httpCache = hasQueryString; - } catch (e) { + } catch (e: any) { catchError(diagnostics, e); } } diff --git a/src/sys/node/node-copy-tasks.ts b/src/sys/node/node-copy-tasks.ts index 131f4228587..7d8f21ba7d9 100644 --- a/src/sys/node/node-copy-tasks.ts +++ b/src/sys/node/node-copy-tasks.ts @@ -36,7 +36,7 @@ export async function nodeCopyTasks(copyTasks: Required[], srcDir: s await Promise.all(tasks.map((copyTask) => copyFile(copyTask.src, copyTask.dest))); } - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } @@ -106,7 +106,9 @@ async function processCopyTask(results: d.CopyResults, allCopyTasks: d.CopyTask[ } catch (e) { if (copyTask.warn !== false) { const err = buildError(results.diagnostics); - err.messageText = e.message; + if (e instanceof Error) { + err.messageText = e.message; + } } } } @@ -126,7 +128,7 @@ async function processCopyTaskDirectory(results: d.CopyResults, allCopyTasks: d. await processCopyTask(results, allCopyTasks, subCopyTask); }) ); - } catch (e) { + } catch (e: any) { catchError(results.diagnostics, e); } } diff --git a/src/testing/jest/jest-screenshot.ts b/src/testing/jest/jest-screenshot.ts index a62b3a63ba9..3167d9d423d 100644 --- a/src/testing/jest/jest-screenshot.ts +++ b/src/testing/jest/jest-screenshot.ts @@ -82,7 +82,11 @@ export async function runJestScreenshot(config: d.Config, env: d.E2EProcessEnv) } } } catch (e) { - config.logger.error(e, e.stack); + if (e instanceof Error) { + config.logger.error(e, e.stack); + } else { + config.logger.error(e); + } } return passed; diff --git a/src/utils/message-utils.ts b/src/utils/message-utils.ts index aae708a4332..8c03c0d6a74 100644 --- a/src/utils/message-utils.ts +++ b/src/utils/message-utils.ts @@ -118,7 +118,14 @@ export const buildJsonFileError = ( return err; }; -export const catchError = (diagnostics: d.Diagnostic[], err: Error, msg?: string) => { +/** + * Builds a diagnostic from an `Error`, appends it to the `diagnostics` parameter, and returns the created diagnostic + * @param diagnostics the series of diagnostics the newly created diagnostics should be added to + * @param err the error to derive information from in generating the diagnostic + * @param msg an optional message to use in place of `err` to generate the diagnostic + * @returns the generated diagnostic + */ +export const catchError = (diagnostics: d.Diagnostic[], err: Error | null | undefined, msg?: string): d.Diagnostic => { const diagnostic: d.Diagnostic = { level: 'error', type: 'build', diff --git a/src/utils/util.ts b/src/utils/util.ts index d36f9eafb1b..e8f7b4bdcb8 100644 --- a/src/utils/util.ts +++ b/src/utils/util.ts @@ -175,11 +175,12 @@ export const parseJson = (jsonStr: string, filePath?: string) => { try { rtn.data = JSON.parse(jsonStr); } catch (e) { - const msg = e.message; rtn.diagnostic = buildError(); rtn.diagnostic.absFilePath = filePath; rtn.diagnostic.header = `Error Parsing JSON`; - rtn.diagnostic.messageText = msg; + if (e instanceof Error) { + rtn.diagnostic.messageText = e.message; + } } } else { rtn.diagnostic = buildError(); diff --git a/tsconfig.json b/tsconfig.json index 57f2b4eb2b5..2f4c417f576 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,8 +22,7 @@ "resolveJsonModule": true, "sourceMap": true, "target": "es2018", - // TODO(STENCIL-346): Enable useUnknownInCatchVariables flag for main project - "useUnknownInCatchVariables": false, + "useUnknownInCatchVariables": true, "baseUrl": ".", "paths": { "@app-data": ["src/app-data/index.ts"],