diff --git a/packages/labs/better-errors/ambient.d.ts b/packages/labs/better-errors/ambient.d.ts deleted file mode 100644 index e69de29..0000000 diff --git a/packages/labs/better-errors/package.json b/packages/labs/better-errors/package.json index 81c3904..9cabede 100644 --- a/packages/labs/better-errors/package.json +++ b/packages/labs/better-errors/package.json @@ -47,10 +47,9 @@ "@gracile/internal-utils": "workspace:^", "@lit-labs/ssr": "^3.2.2", "@lit-labs/ssr-client": "^1.1.7", - "launch-editor-middleware": "^2.8.1", "lit": "^3.1.3", "picocolors": "^1.0.1", - "vite": "^5.3.5" + "vite": "^5.4.10" }, "devDependencies": { "@gracile/internal-tsconfigs": "workspace:^", diff --git a/packages/labs/better-errors/src/dev/custom-overlay/assets.ts b/packages/labs/better-errors/src/dev/custom-overlay/assets.ts index 81991df..a090f30 100644 --- a/packages/labs/better-errors/src/dev/custom-overlay/assets.ts +++ b/packages/labs/better-errors/src/dev/custom-overlay/assets.ts @@ -1,4 +1,4 @@ -import { html } from 'lit'; +import { html } from 'lit/static-html.js'; // const houstonLogo = ``; diff --git a/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.styles.ts b/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.styles.ts index 25acb0a..8357df7 100644 --- a/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.styles.ts +++ b/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.styles.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines */ import { css } from 'lit'; export const style = css` diff --git a/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.ts b/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.ts index 7ad8e43..37fcf4e 100644 --- a/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.ts +++ b/packages/labs/better-errors/src/dev/custom-overlay/vite-custom-overlay.ts @@ -1,245 +1,258 @@ -// TODO: Convert remaining imperative code - -import { css, html, LitElement } from 'lit'; -import { customElement, property } from 'lit/decorators.js'; - -import * as assets from './assets.js'; -import { style } from './vite-custom-overlay.styles.js'; -import type { BetterErrorPayload } from '../vite.js'; -import { unsafeHTML } from 'lit/directives/unsafe-html.js'; - -@customElement('vite-custom-overlay') -export class ViteCustomOverlay extends LitElement { - static styles = [ - style, - css` - :host { - display: contents; - } - `, - ]; - - @property({ type: Object }) accessor errorPayload: - | BetterErrorPayload['err'] - | null = null; - - root = this.shadowRoot!; - - protected firstUpdated(): void { - this?.classList.add('betterr-dark'); - - this.root = this.shadowRoot!; - this.appendCode(); - this.initTheme(); - } - - initTheme() { - const themeToggle = this.root.querySelector( - '.theme-toggle-checkbox', - ); - if ( - localStorage['betterrErrorOverlayTheme'] === 'dark' || - (!('betterrErrorOverlayTheme' in localStorage) && - window.matchMedia('(prefers-color-scheme: dark)').matches) - ) { - this?.classList.add('betterr-dark'); - localStorage['betterrErrorOverlayTheme'] = 'dark'; - themeToggle!.checked = true; - } else { - this?.classList.remove('betterr-dark'); - themeToggle!.checked = false; - } - themeToggle?.addEventListener('click', () => { - const isDark = - localStorage['betterrErrorOverlayTheme'] === 'dark' || - this?.classList.contains('betterr-dark'); - this?.classList.toggle('betterr-dark', !isDark); - localStorage['betterrErrorOverlayTheme'] = isDark ? 'light' : 'dark'; - }); - } - - static createLink(text: string, href: string | undefined): HTMLDivElement { - const linkContainer = document.createElement('div'); - const linkElement = href - ? document.createElement('a') - : document.createElement('button'); - linkElement.innerHTML = text; - - if (href && linkElement instanceof HTMLAnchorElement) { - linkElement.href = href; - linkElement.target = '_blank'; - } - - linkContainer.appendChild(linkElement); - linkContainer.className = 'link'; - - return linkContainer; - } - - appendCode() { - const err = this.errorPayload; - if (!err) throw new ReferenceError(); - - const code = this.root.querySelector('#code'); - if (code && err.loc?.file) { - code.style.display = 'block'; - const codeHeader = code.querySelector('#code header'); - const codeContent = code.querySelector('#code-content'); - - if (codeHeader) { - const separator = err.loc.file.includes('/') ? '/' : '\\'; - const cleanFile = err.loc.file.split(separator).slice(-2).join('/'); - const fileLocation = [cleanFile, err.loc.line, err.loc.column] - .filter(Boolean) - .join(':'); - const absoluteFileLocation = [ - err.loc.file, - err.loc.line, - err.loc.column, - ] - .filter(Boolean) - .join(':'); - - const codeFile = codeHeader.getElementsByTagName('h2')[0]; - if (codeFile) { - codeFile.textContent = fileLocation; - codeFile.title = absoluteFileLocation; - } - - const editorLink = ViteCustomOverlay.createLink( - `Open in editor${assets.openNewWindowIcon}`, - undefined, - ); - editorLink.onclick = () => { - fetch( - `/__open-in-editor?file=${encodeURIComponent( - absoluteFileLocation, - )}`, - ).catch(console.error); - }; - - codeHeader.appendChild(editorLink); - } - - const hint = this.root.querySelector('#hint'); - if (hint && err.hint) { - hint.style.display = 'flex'; - } - - const docslink = this.root.querySelector('#message'); - if (docslink && err.docslink) { - docslink.appendChild( - ViteCustomOverlay.createLink( - `See Docs Reference${assets.openNewWindowIcon}`, - err.docslink, - ), - ); - } - - if (codeContent && err.highlightedCode) { - codeContent.innerHTML = err.highlightedCode; - - window.requestAnimationFrame(() => { - // NOTE: This cannot be `codeContent.querySelector` because `codeContent` still contain the old HTML - const errorLine = - this.root.querySelector('.error-line'); - - if (errorLine) { - if (errorLine.parentElement?.parentElement) { - errorLine.parentElement.parentElement.scrollTop = - errorLine.offsetTop - - errorLine.parentElement.parentElement.offsetTop - - 8; - } - - // Add an empty line below the error line so we can show a caret under the error - if (err.loc?.column) { - errorLine.insertAdjacentHTML( - 'afterend', - `\n^`, - ); - } - } - }); - } - } - } - - render() { - if (!this.errorPayload) throw new ReferenceError('Missing payload!'); - - return html` -
-
-
-
- - -
-
- - - -
-
- ${assets.messageIcon} - -
${unsafeHTML( - this.errorPayload['message'], - )}
-
- -
- ${assets.hintIcon} -
${this.errorPayload.hint}
-
-
- -
-
-

-
- -
-
- -
-

Stack Trace

-
${this.errorPayload['stack']}
-
- - ${this.errorPayload.cause - ? html` -
-

Cause

-
${this.errorPayload.cause}
-
` - : null} -
-
- `; - } -} - -declare global { - interface HTMLElementTagNameMap { - 'vite-custom-overlay': ViteCustomOverlay; - } -} +// // TODO: Convert remaining imperative code + +// // import { customElement, property } from 'lit/decorators.js'; + +// import type { BetterErrorPayload } from '../vite.js'; + +// import * as assets from './assets.js'; +// import { style } from './vite-custom-overlay.styles.js'; +// // import { unsafeHTML } from 'lit/directives/unsafe-html.js'; +// // import { render } from 'lit/html.js'; +// // import { html } from 'lit/static-html.js'; + +// export class ViteCustomOverlay extends HTMLElement { +// // static styles = [ +// // style, +// // css` +// // :host { +// // display: contents; +// // } +// // `, +// // ]; + +// errorPayload: BetterErrorPayload['err'] | null = null; + +// root = this.shadowRoot!; + +// // protected firstUpdated(): void { + +// // } + +// initTheme() { +// const themeToggle = this.root.querySelector( +// '.theme-toggle-checkbox', +// ); +// if ( +// localStorage['betterrErrorOverlayTheme'] === 'dark' || +// (!('betterrErrorOverlayTheme' in localStorage) && +// globalThis.matchMedia('(prefers-color-scheme: dark)').matches) +// ) { +// this?.classList.add('betterr-dark'); +// localStorage['betterrErrorOverlayTheme'] = 'dark'; +// themeToggle!.checked = true; +// } else { +// this?.classList.remove('betterr-dark'); +// themeToggle!.checked = false; +// } +// themeToggle?.addEventListener('click', () => { +// const isDark = +// localStorage['betterrErrorOverlayTheme'] === 'dark' || +// this?.classList.contains('betterr-dark'); +// this?.classList.toggle('betterr-dark', !isDark); +// localStorage['betterrErrorOverlayTheme'] = isDark ? 'light' : 'dark'; +// }); +// } + +// static createLink(text: string, href: string | undefined): HTMLDivElement { +// const linkContainer = document.createElement('div'); +// const linkElement = href +// ? document.createElement('a') +// : document.createElement('button'); +// linkElement.innerHTML = text; + +// if (href && linkElement instanceof HTMLAnchorElement) { +// linkElement.href = href; +// linkElement.target = '_blank'; +// } + +// linkContainer.append(linkElement); +// linkContainer.className = 'link'; + +// return linkContainer; +// } + +// appendCode() { +// const error = this.errorPayload; +// if (!error) throw new ReferenceError('No error.'); + +// const code = this.root.querySelector('#code'); +// if (code && error.loc?.file) { +// const codeHeader = code.querySelector('#code header'); + +// if (codeHeader) { +// const separator = error.loc.file.includes('/') ? '/' : '\\'; +// const cleanFile = error.loc.file.split(separator).slice(-2).join('/'); +// const fileLocation = [cleanFile, error.loc.line, error.loc.column] +// .filter(Boolean) +// .join(':'); +// const absoluteFileLocation = [ +// error.loc.file, +// error.loc.line, +// error.loc.column, +// ] +// .filter(Boolean) +// .join(':'); + +// const codeFile = codeHeader.querySelectorAll('h2')[0]; +// if (codeFile) { +// codeFile.textContent = fileLocation; +// codeFile.title = absoluteFileLocation; +// } + +// const editorLink = ViteCustomOverlay.createLink( +// `Open in editor${assets.openNewWindowIcon}`, +// ); +// editorLink.addEventListener('click', () => { +// fetch( +// `/__open-in-editor?file=${encodeURIComponent( +// absoluteFileLocation, +// )}`, +// ).catch(console.error); +// }); + +// codeHeader.append(editorLink); +// } + +// const hint = this.root.querySelector('#hint'); +// if (hint && error.hint) { +// hint.style.display = 'flex'; +// } + +// const docslink = this.root.querySelector('#message'); +// if (docslink && error.docslink) { +// docslink.append( +// ViteCustomOverlay.createLink( +// `See Docs Reference${assets.openNewWindowIcon}`, +// error.docslink, +// ), +// ); +// } + +// if (error.highlightedCode) { +// globalThis.requestAnimationFrame(() => { +// // NOTE: This cannot be `codeContent.querySelector` because `codeContent` still contain the old HTML +// const errorLine = +// this.root.querySelector('.error-line'); + +// if (errorLine) { +// if (errorLine.parentElement?.parentElement) { +// errorLine.parentElement.parentElement.scrollTop = +// errorLine.offsetTop - +// errorLine.parentElement.parentElement.offsetTop - +// 8; +// } + +// // Add an empty line below the error line so we can show a caret under the error +// if (error.loc?.column) { +// errorLine.insertAdjacentHTML( +// 'afterend', +// `\n^`, +// ); +// } +// } +// }); +// } +// } +// } + +// connectedCallback() { +// if (!this.errorPayload) throw new ReferenceError('Missing payload!'); + +// this.root = this.attachShadow({ mode: 'open' }); +// // this.classList.add('betterr-dark'); +// // // this.root = this.shadowRoot!; + +// // const s = new CSSStyleSheet() +// // s.replaceSync(style.styleSheet) +// this.shadowRoot?.adoptedStyleSheets.push(style.styleSheet!); + +// // const tpl = html` +// //
+// //
+// //
+// //
+// // +// // +// //
+// //
+ +// // + +// //
+// //
+// // ${assets.messageIcon} +// // +// //
${unsafeHTML( +// // this.errorPayload['message'], +// // )}
+// //
+ +// //
+// // ${assets.hintIcon} +// //
${this.errorPayload.hint}
+// //
+// //
+ +// //
+// //
+// //

+// //
+ +// // ${this.errorPayload.highlightedCode +// // ? html`
+// // ${unsafeHTML(this.errorPayload.highlightedCode)} +// //
` +// // : null} +// //
+ +// //
+// //

Stack Trace

+// //
${this.errorPayload['stack']}
+// //
+ +// // ${this.errorPayload.cause +// // ? html` +// //
+// //

Cause

+// //
${this.errorPayload.cause}
+// //
` +// // : null} +// //
+// //
+// // `; + +// // render(tpl, this.root); + +// // this.appendCode(); +// // this.initTheme(); + +// this.root.innerHTML = 'TEST'; +// } +// } + +// customElements.define('vite-custom-overlay', ViteCustomOverlay); + +// declare global { +// interface HTMLElementTagNameMap { +// 'vite-custom-overlay': ViteCustomOverlay; +// } +// } + +throw new Error('Empty'); diff --git a/packages/labs/better-errors/src/dev/logger.ts b/packages/labs/better-errors/src/dev/logger.ts index 22762e2..d0553d6 100644 --- a/packages/labs/better-errors/src/dev/logger.ts +++ b/packages/labs/better-errors/src/dev/logger.ts @@ -1,8 +1,12 @@ -import { getDocsForError, renderErrorMarkdown } from './utils.js'; - +// TODO: Refactor with Gracile code-base style. +/* eslint-disable unicorn/no-abusive-eslint-disable */ +/* eslint-disable */ import picocolors from 'picocolors'; + import { BetterError, type ErrorWithMetadata } from '../errors.js'; import type { BetterErrorData } from '../errors-data.js'; + +import { getDocsForError, renderErrorMarkdown } from './utils.js'; const { yellow, bold, cyan, dim, underline, red } = picocolors; // a regex to match the first line of a stack trace @@ -10,10 +14,10 @@ const STACK_LINE_REGEXP = /^\s+at /g; const IRRELEVANT_STACK_REGEXP = /node_modules|astro[/\\]dist/g; function formatErrorStackTrace( - err: Error | ErrorWithMetadata, + error: Error | ErrorWithMetadata, showFullStacktrace: boolean, ): string { - const stackLines = (err.stack || '') + const stackLines = (error.stack || '') .split('\n') .filter((line) => STACK_LINE_REGEXP.test(line)); // If full details are required, just return the entire stack trace. @@ -25,8 +29,8 @@ function formatErrorStackTrace( IRRELEVANT_STACK_REGEXP.test(line), ); if (irrelevantStackIndex <= 0) { - const errorId = (err as ErrorWithMetadata).id; - const errorLoc = (err as ErrorWithMetadata).loc; + const errorId = (error as ErrorWithMetadata).id; + const errorLoc = (error as ErrorWithMetadata).loc; if (errorId || errorLoc?.file) { const prettyLocation = ` at ${errorId ?? errorLoc?.file}${ errorLoc?.line && errorLoc.column @@ -55,55 +59,50 @@ export function padMultilineString(source: string, n = 2) { } export function formatErrorMessage( - err: ErrorWithMetadata, + error: ErrorWithMetadata, showFullStacktrace: boolean, errorsData: Record, docsBaseUrl?: string, ): string { const isOurError = BetterError.is( - err, + error, ); /* || CompilerError.is(err) || AstroUserError.is(err) */ let message = ''; - if (isOurError) { - message += - red(`[${err.name}]`) + ' ' + renderErrorMarkdown(err.message, 'cli'); - } else { - message += err.message; - } + message += isOurError + ? red(`[${error.name}]`) + ' ' + renderErrorMarkdown(error.message, 'cli') + : error.message; const output = [message]; - if (err.hint) { + if (error.hint) { output.push(` ${bold('Hint:')}`); output.push( - yellow(padMultilineString(renderErrorMarkdown(err.hint, 'cli'), 4)), + yellow(padMultilineString(renderErrorMarkdown(error.hint, 'cli'), 4)), ); } if (docsBaseUrl) { - const docsLink = getDocsForError(err, errorsData, docsBaseUrl); + const docsLink = getDocsForError(error, errorsData, docsBaseUrl); if (docsLink) { output.push(` ${bold('Error reference:')}`); output.push(` ${cyan(underline(docsLink))}`); } } - if (err.stack) { + if (error.stack) { output.push(` ${bold('Stack trace:')}`); - output.push(dim(formatErrorStackTrace(err, showFullStacktrace))); + output.push(dim(formatErrorStackTrace(error, showFullStacktrace))); } - if (err.cause) { + if (error.cause) { output.push(` ${bold('Caused by:')}`); let causeMessage = ' '; - if (err.cause instanceof Error) { - causeMessage += - err.cause.message + - '\n' + - formatErrorStackTrace(err.cause, showFullStacktrace); - } else { - causeMessage += JSON.stringify(err.cause); - } + causeMessage += + error.cause instanceof Error + ? error.cause.message + + '\n' + + formatErrorStackTrace(error.cause, showFullStacktrace) + : JSON.stringify(error.cause); output.push(dim(causeMessage)); } diff --git a/packages/labs/better-errors/src/dev/printer.ts b/packages/labs/better-errors/src/dev/printer.ts index 8663665..67e8deb 100644 --- a/packages/labs/better-errors/src/dev/printer.ts +++ b/packages/labs/better-errors/src/dev/printer.ts @@ -1,19 +1,17 @@ -/* eslint-disable no-restricted-syntax */ - import type { ErrorLocation } from '../errors.js'; export function normalizeLF(code: string) { - return code.replace(/\r\n|\r(?!\n)|\n/g, '\n'); + return code.replaceAll(/\r\n|\r(?!\n)|\n/g, '\n'); } /** Generate a code frame from string and an error location */ -export function codeFrame(src: string, loc: ErrorLocation): string { +export function codeFrame(source: string, loc: ErrorLocation): string { if (!loc || loc.line === undefined || loc.column === undefined) { return ''; } - const lines = normalizeLF(src) + const lines = normalizeLF(source) .split('\n') - .map((ln) => ln.replace(/\t/g, ' ')); + .map((ln) => ln.replaceAll('\t', ' ')); // grab 2 lines before, and 3 lines after focused line const visibleLines = []; for (let n = -2; n <= 2; n += 1) { diff --git a/packages/labs/better-errors/src/dev/utils.ts b/packages/labs/better-errors/src/dev/utils.ts index 3f6243d..764d7f0 100644 --- a/packages/labs/better-errors/src/dev/utils.ts +++ b/packages/labs/better-errors/src/dev/utils.ts @@ -1,3 +1,5 @@ +// TODO: Refactor with Gracile code-base style. +/* eslint-disable unicorn/no-abusive-eslint-disable */ /* eslint-disable */ import c from 'picocolors'; diff --git a/packages/labs/better-errors/src/dev/vite.ts b/packages/labs/better-errors/src/dev/vite.ts index 00c0a93..bbb8b81 100644 --- a/packages/labs/better-errors/src/dev/vite.ts +++ b/packages/labs/better-errors/src/dev/vite.ts @@ -1,3 +1,5 @@ +// TODO: Refactor with Gracile code-base style. +/* eslint-disable unicorn/no-abusive-eslint-disable */ /* eslint-disable */ import * as fs from 'node:fs'; import { fileURLToPath } from 'node:url'; diff --git a/packages/labs/better-errors/src/errors-data.ts b/packages/labs/better-errors/src/errors-data.ts index f0b8e96..83c9fdd 100644 --- a/packages/labs/better-errors/src/errors-data.ts +++ b/packages/labs/better-errors/src/errors-data.ts @@ -5,8 +5,8 @@ export interface BetterErrorData { name: string; title: string; - message?: string | ((...params: any) => string) | undefined; - hint?: string | ((...params: any) => string) | undefined; + message?: string | ((...parameters: any) => string) | undefined; + hint?: string | ((...parameters: any) => string) | undefined; } /** diff --git a/packages/labs/better-errors/src/errors.ts b/packages/labs/better-errors/src/errors.ts index 1ef4162..3d20620 100644 --- a/packages/labs/better-errors/src/errors.ts +++ b/packages/labs/better-errors/src/errors.ts @@ -1,4 +1,5 @@ import type { ErrorPayload } from 'vite'; + import { codeFrame } from './dev/printer.js'; export type BuiltinErrorTypes = @@ -58,11 +59,12 @@ export class BetterError< type: BuiltinErrorTypes | ConsumerErrorTypes = 'BetterError'; - constructor(props: ErrorProperties, options?: ErrorOptions) { - const { name, title, message, stack, location, hint, frame } = props; + constructor(properties: ErrorProperties, options?: ErrorOptions) { + const { name, title, message, stack, location, hint, frame } = properties; super(message, options); this.title = title; + // eslint-disable-next-line unicorn/custom-error-definition this.name = name; if (message) this.message = message; @@ -93,8 +95,8 @@ export class BetterError< this.frame = codeFrame(source, location); } - static is(err: unknown): err is BetterError { - return (err as BetterError).type === 'BetterError'; + static is(error: unknown): error is BetterError { + return (error as BetterError).type === 'BetterError'; } } @@ -105,21 +107,22 @@ export class AggregateError extends BetterError { // Despite being a collection of errors, AggregateError still needs to have a main error attached to it // This is because Vite expects every thrown errors handled during HMR to be, well, Error and have a message constructor( - props: ErrorProperties & { errors: BetterError[] }, + properties: ErrorProperties & { errors: BetterError[] }, options?: ErrorOptions, + // eslint-disable-next-line unicorn/custom-error-definition ) { - super(props, options); + super(properties, options); - this.errors = props.errors; + this.errors = properties.errors; } - static is(err: unknown): err is AggregateError { - return (err as AggregateError).type === 'AggregateError'; + static is(error: unknown): error is AggregateError { + return (error as AggregateError).type === 'AggregateError'; } } -export function isBetterError(e: unknown): e is BetterError { - return e instanceof BetterError; +export function isBetterError(error: unknown): error is BetterError { + return error instanceof BetterError; } export type SSRError = Error & ErrorPayload['err']; diff --git a/packages/labs/better-errors/src/plugin.ts b/packages/labs/better-errors/src/plugin.ts index cb223c3..0e6d308 100755 --- a/packages/labs/better-errors/src/plugin.ts +++ b/packages/labs/better-errors/src/plugin.ts @@ -1,117 +1,136 @@ -import { createLogger as createViteLogger, type PluginOption } from 'vite'; -// @ts-expect-error No typings at all -import launchMiddleware from 'launch-editor-middleware'; - -import type { BetterErrorPayload } from './dev/vite.js'; -import { getLogger } from '@gracile/internal-utils/logger/helpers'; - -const VITE_PLUGIN_NAME = 'vite-plugin-better-errors'; - -// const virtualModuleId = 'better-errors:overlay'; -// const resolvedVirtualModuleId = `\0${virtualModuleId}`; - -const GRACILE_OVERLAY_PATH = - '@gracile-labs/better-errors/dev/custom-overlay/vite-custom-overlay'; - -export function patchOverlay(code: string, importPath?: string) { - // NOTE: Make HTMLElement available in non-browser environments - const { HTMLElement = class {} as typeof globalThis.HTMLElement } = - globalThis; - class ErrorOverlay extends HTMLElement { - root: ShadowRoot; - - constructor(err: BetterErrorPayload['err']) { - super(); - this.root = this.attachShadow({ mode: 'open' }); - this.dir = 'ltr'; - - const customOverlay = document.createElement('vite-custom-overlay'); - customOverlay.errorPayload = err; - - this.root.append(customOverlay); - } - } - - const overlayCode = ` -import('${importPath ?? GRACILE_OVERLAY_PATH}'); - -${ErrorOverlay.toString()}; -`; - - return code.replace( - 'class ErrorOverlay', - overlayCode + '\nclass ViteErrorOverlay', - ); -} - -export function betterErrors(options?: { - overlayImportPath: string; - // MarkdownRenderer: typeof MarkdownDocumentRendererEmpty; - // NOTE: for Vite versions mismatches with `exactOptionalPropertyTypes`? - // This `any[]` AND with a plugin -array- makes ESLint and TS shut up. - // eslint-disable-next-line @typescript-eslint/no-explicit-any -}): any[] { - // const logger = getLogger(); - - // NOTE: Used to filter out redundant Vite errors, which are - // noisy and less detailed than ours. - // This should be refined on a case-by-case-basis. - // Also, keep in mind that the user could use their own Vite - // logger. Which is fine, but maybe the Gracile one should be - // disabled in that case. - const viteLogger = createViteLogger(); - const customLogger = createViteLogger(); - customLogger.error = (msg /* options */) => { - if (msg.startsWith('\x1B[31mError when evaluating SSR module ')) return; - viteLogger.error(msg); - }; - - return [ - { - name: VITE_PLUGIN_NAME, - enforce: 'pre', - - apply: 'serve', - - config() { - return { - customLogger, - }; - }, - - configureServer(server) { - server.middlewares.use( - '/__open-in-editor', - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call - launchMiddleware(), - ); - }, - - transform(code, id, opts = {}) { - if (opts.ssr) return null; - if (!id.includes('vite/dist/client/client.mjs')) return null; - - // Replace the Vite overlay with ours - return patchOverlay(code, options?.overlayImportPath); - }, - - // resolveId(id) { - // if (id === virtualModuleId) { - // return resolvedVirtualModuleId; - // } - // return null; - // }, - - // load(id) { - // if (id === resolvedVirtualModuleId) { - // return ` - // const routeImports = new Map( - - // ); - - // `; - // } - // }, - } satisfies PluginOption, - ]; -} +// import { createLogger as createViteLogger, type PluginOption } from 'vite'; +// // @\ts-expect-error No typings at all +// // import launchMiddleware from 'launch-editor-middleware'; + +// // import { getLogger } from '@gracile/internal-utils/logger/helpers'; + +// import type { BetterErrorPayload } from './dev/vite.js'; + +// const VITE_PLUGIN_NAME = 'vite-plugin-better-errors'; + +// // const virtualModuleId = 'better-errors:overlay'; +// // const resolvedVirtualModuleId = `\0${virtualModuleId}`; + +// // static GRACILE_OVERLAY_PATH = +// // '@gracile-labs/better-errors/dev/custom-overlay/vite-custom-overlay'; + +// export function patchOverlay(code: string, importPath?: string) { +// // NOTE: Make HTMLElement available in non-browser environments +// // eslint-disable-next-line @typescript-eslint/no-extraneous-class +// const { HTMLElement = class {} as typeof globalThis.HTMLElement } = +// globalThis; +// class ErrorOverlay extends HTMLElement { +// root: ShadowRoot; + +// constructor(error: BetterErrorPayload['err']) { +// super(); +// this.root = this.attachShadow({ mode: 'open' }); +// this.dir = 'ltr'; + +// const customOverlay = document.createElement('vite-custom-overlay'); +// customOverlay.errorPayload = error; + +// // ; + +// // // @ts-expect-error . +// // setTimeout(() => { +// // // __gracile_importOverlay(); +// // }, 100); +// this.root.append(customOverlay); +// } +// } + +// const overlayCode = ` +// const BETTERR_OVERLAY_PATH = +// '@gracile-labs/better-errors/dev/custom-overlay/vite-custom-overlay'; + +// const BETTERR_CUSTOM_IMPORT_PATH = '${importPath}'; + +// // const __gracile_importOverlay = () => import(BETTERR_CUSTOM_IMPORT_PATH ?? BETTERR_OVERLAY_PATH); + +// import('${importPath}') + +// ${ErrorOverlay.toString()}; +// `; + +// return code.replace( +// 'class ErrorOverlay', +// overlayCode + '\nclass ViteErrorOverlay', +// ); +// } + +// export function betterErrors(options?: { +// overlayImportPath: string; +// // MarkdownRenderer: typeof MarkdownDocumentRendererEmpty; +// // NOTE: for Vite versions mismatches with `exactOptionalPropertyTypes`? +// // This `any[]` AND with a plugin -array- makes ESLint and TS shut up. +// // eslint-disable-next-line @typescript-eslint/no-explicit-any +// }): any[] { +// // const logger = getLogger(); + +// // NOTE: Used to filter out redundant Vite errors, which are +// // noisy and less detailed than ours. +// // This should be refined on a case-by-case-basis. +// // Also, keep in mind that the user could use their own Vite +// // logger. Which is fine, but maybe the Gracile one should be +// // disabled in that case. +// const viteLogger = createViteLogger(); +// const customLogger = createViteLogger(); +// customLogger.error = (message /* options */) => { +// if (message.startsWith('\u001B[31mError when evaluating SSR module ')) +// return; +// viteLogger.error(message); +// }; + +// return [ +// { +// name: VITE_PLUGIN_NAME, +// enforce: 'pre', + +// apply: 'serve', + +// config() { +// return { +// customLogger, +// }; +// }, + +// // NOTE: VITE ALREADY PROVIDE THIS! +// // configureServer(server) { +// // server.middlewares.use( +// // '/__open-in-editor', +// // // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call +// // launchMiddleware(), +// // ); +// // }, + +// transform(code, id, options_ = {}) { +// if (options_.ssr) return null; +// if (!id.includes('vite/dist/client/client.mjs')) return null; + +// // Replace the Vite overlay with ours +// return patchOverlay(code, options?.overlayImportPath); +// }, + +// // resolveId(id) { +// // if (id === virtualModuleId) { +// // return resolvedVirtualModuleId; +// // } +// // return null; +// // }, + +// // load(id) { +// // if (id === resolvedVirtualModuleId) { +// // return ` +// // const routeImports = new Map( + +// // ); + +// // `; +// // } +// // }, +// } satisfies PluginOption, +// ]; +// } + +throw new Error('Empty'); diff --git a/packages/labs/better-errors/vite.config.ts b/packages/labs/better-errors/vite.config.ts deleted file mode 100644 index 48a7356..0000000 --- a/packages/labs/better-errors/vite.config.ts +++ /dev/null @@ -1,40 +0,0 @@ -// NOTE: UNUSED, maybe never? - -// import { defineConfig } from 'vite'; -// import terser from '@rollup/plugin-terser'; -// import { literalsHtmlCssMinifier } from '@literals/rollup-plugin-html-css-minifier'; - -// export default defineConfig({ -// esbuild: { legalComments: 'none' }, -// build: { -// lib: { -// // Could also be a dictionary or array of multiple entry points -// entry: './src/dev/custom-overlay/vite-custom-overlay.ts', -// name: 'BetterErrors', -// // the proper extensions will be added -// fileName: 'better-errors', -// formats: ['es'], -// }, - -// minify: false, -// target: 'esnext', -// rollupOptions: { -// // make sure to externalize deps that shouldn't be bundled -// // into your library -// external: [], -// output: { -// dir: 'bundle', -// }, -// }, -// }, - -// plugins: [ -// terser({ -// format: { -// comments: false, -// }, -// }), - -// literalsHtmlCssMinifier(), -// ], -// });