[ci] yarn format

This commit is contained in:
matthewp 2021-10-29 19:31:54 +00:00 committed by GitHub Actions
parent d84bfe719a
commit 93489946cc
41 changed files with 1470 additions and 1674 deletions

View file

@ -13,4 +13,4 @@ description: Just a Hello World Post!
This is so cool! This is so cool!
Do variables work {frontmatter.value * 2}? Do variables work {frontmatter.value \* 2}?

View file

@ -1,6 +1,6 @@
import { KNOWN_LANGUAGES } from './config'; import { KNOWN_LANGUAGES } from './config';
export { KNOWN_LANGUAGES } export { KNOWN_LANGUAGES };
export const KNOWN_LANGUAGE_CODES = Object.values(KNOWN_LANGUAGES); export const KNOWN_LANGUAGE_CODES = Object.values(KNOWN_LANGUAGES);
export const langPathRegex = /\/([a-z]{2}-?[A-Z]{0,2})\//; export const langPathRegex = /\/([a-z]{2}-?[A-Z]{0,2})\//;

View file

@ -11,13 +11,16 @@ import astroRemark from '@astrojs/markdown-remark';
export default /** @type {import('astro').AstroUserConfig} */ ({ export default /** @type {import('astro').AstroUserConfig} */ ({
// Enable Custom Markdown options, plugins, etc. // Enable Custom Markdown options, plugins, etc.
markdownOptions: { markdownOptions: {
render: [astroRemark, { render: [
remarkPlugins: ['remark-code-titles', 'remark-slug'], astroRemark,
rehypePlugins: [ {
['rehype-autolink-headings', { behavior: 'prepend' }], remarkPlugins: ['remark-code-titles', 'remark-slug'],
['rehype-toc', { headings: ['h2', 'h3'] }], rehypePlugins: [
['rehype-add-classes', { 'h1,h2,h3': 'title' }], ['rehype-autolink-headings', { behavior: 'prepend' }],
] ['rehype-toc', { headings: ['h2', 'h3'] }],
}] ['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
},
],
}, },
}); });

View file

@ -1 +1 @@
export function addAstro(Prism: any): void; export function addAstro(Prism: any): void;

View file

@ -66,7 +66,7 @@ export function codeFrame(src: string, loc: ErrorPayload['err']['loc']): string
export function resolveDependency(dep: string, astroConfig: AstroConfig) { export function resolveDependency(dep: string, astroConfig: AstroConfig) {
const resolved = resolve.sync(dep, { const resolved = resolve.sync(dep, {
basedir: fileURLToPath(astroConfig.projectRoot) basedir: fileURLToPath(astroConfig.projectRoot),
}); });
// For Windows compat, we need a fully resolved `file://` URL string // For Windows compat, we need a fully resolved `file://` URL string
return pathToFileURL(resolved).toString(); return pathToFileURL(resolved).toString();

View file

@ -1,2 +1,2 @@
export * from '../../vendor/vite/dist/node/index.js'; export * from '../../vendor/vite/dist/node/index.js';
export { default } from '../../vendor/vite/dist/node/index.js'; export { default } from '../../vendor/vite/dist/node/index.js';

View file

@ -365,13 +365,17 @@ export async function renderToString(result: SSRResult, componentFactory: AstroC
const uniqueElements = (item: any, index: number, all: any[]) => { const uniqueElements = (item: any, index: number, all: any[]) => {
const props = JSON.stringify(item.props); const props = JSON.stringify(item.props);
const children = item.children; const children = item.children;
return index === all.findIndex(i => JSON.stringify(i.props) === props && i.children == children) return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
} };
export async function renderPage(result: SSRResult, Component: AstroComponentFactory, props: any, children: any) { export async function renderPage(result: SSRResult, Component: AstroComponentFactory, props: any, children: any) {
const template = await renderToString(result, Component, props, children); const template = await renderToString(result, Component, props, children);
const styles = Array.from(result.styles).filter(uniqueElements).map((style) => renderElement('style', style)); const styles = Array.from(result.styles)
const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => renderElement('script', script)); .filter(uniqueElements)
.map((style) => renderElement('style', style));
const scripts = Array.from(result.scripts)
.filter(uniqueElements)
.map((script) => renderElement('script', script));
return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>'); return template.replace('</head>', styles.join('\n') + scripts.join('\n') + '</head>');
} }

View file

@ -60,7 +60,7 @@ class Metadata {
} }
interface CreateMetadataOptions { interface CreateMetadataOptions {
modules: ModuleInfo[]; modules: ModuleInfo[];
hydratedComponents: any[]; hydratedComponents: any[];
hoisted: any[]; hoisted: any[];
} }

View file

@ -11,7 +11,7 @@ interface AstroPluginOptions {
devServer?: AstroDevServer; devServer?: AstroDevServer;
} }
// esbuild transforms the component-scoped Astro into Astro2, so need to check both. // esbuild transforms the component-scoped Astro into Astro2, so need to check both.
const validAstroGlobalNames = new Set(['Astro', 'Astro2']); const validAstroGlobalNames = new Set(['Astro', 'Astro2']);
export default function astro({ config, devServer }: AstroPluginOptions): Plugin { export default function astro({ config, devServer }: AstroPluginOptions): Plugin {

View file

@ -94,4 +94,4 @@ describe('Astro basics', () => {
expect(result.status).to.equal(404); expect(result.status).to.equal(404);
}); });
}); });
}); });

View file

@ -13,8 +13,8 @@ describe('Dynamic components', () => {
it('Loads packages that only run code in client', async () => { it('Loads packages that only run code in client', async () => {
const html = await fixture.readFile('/index.html'); const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html) const $ = cheerio.load(html);
expect($('script').length).to.eq(2) expect($('script').length).to.eq(2);
}); });
it('Loads pages using client:media hydrator', async () => { it('Loads pages using client:media hydrator', async () => {

View file

@ -3,7 +3,6 @@ import cheerio from 'cheerio';
import { loadFixture } from './test-utils.js'; import { loadFixture } from './test-utils.js';
import markdownRemark from '@astrojs/markdown-remark'; import markdownRemark from '@astrojs/markdown-remark';
describe('Astro Markdown plugins', () => { describe('Astro Markdown plugins', () => {
let fixture; let fixture;
@ -12,13 +11,16 @@ describe('Astro Markdown plugins', () => {
projectRoot: './fixtures/astro-markdown-plugins/', projectRoot: './fixtures/astro-markdown-plugins/',
renderers: ['@astrojs/renderer-preact'], renderers: ['@astrojs/renderer-preact'],
markdownOptions: { markdownOptions: {
render: [markdownRemark, { render: [
remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]], markdownRemark,
rehypePlugins: [ {
['rehype-toc', { headings: ['h2', 'h3'] }], remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]],
['rehype-add-classes', { 'h1,h2,h3': 'title' }], rehypePlugins: [
], ['rehype-toc', { headings: ['h2', 'h3'] }],
}], ['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
},
],
}, },
buildOptions: { buildOptions: {
sitemap: false, sitemap: false,
@ -48,4 +50,4 @@ describe('Astro Markdown plugins', () => {
// teste 2: Added .title to h1 // teste 2: Added .title to h1
expect($('#hello-world').hasClass('title')).to.equal(true); expect($('#hello-world').hasClass('title')).to.equal(true);
}); });
}); });

View file

@ -59,7 +59,7 @@ describe('Astro Markdown', () => {
// test 1: <pre> tag has scopedStyle class passed down // test 1: <pre> tag has scopedStyle class passed down
expect($('pre').is('[class]')).to.equal(true); expect($('pre').is('[class]')).to.equal(true);
expect($('pre').attr('class').split(' ').length).to.equal(2) expect($('pre').attr('class').split(' ').length).to.equal(2);
// test 2: <pre> tag has correct language // test 2: <pre> tag has correct language
expect($('pre').hasClass('language-js')).to.equal(true); expect($('pre').hasClass('language-js')).to.equal(true);
@ -117,7 +117,7 @@ describe('Astro Markdown', () => {
expect($('code:nth-child(2)').text()).to.equal('{...props}'); expect($('code:nth-child(2)').text()).to.equal('{...props}');
// test 4: Rendered curly braces markdown content // test 4: Rendered curly braces markdown content
expect($('code:last-child').text()).to.equal('{/* JavaScript *\/}'); expect($('code:last-child').text()).to.equal('{/* JavaScript */}');
}); });
it('Does not close parent early when using content attribute (#494)', async () => { it('Does not close parent early when using content attribute (#494)', async () => {
@ -140,4 +140,4 @@ describe('Astro Markdown', () => {
// test Markdown rendered correctly via content prop // test Markdown rendered correctly via content prop
expect($('h1').text()).to.equal('Foo'); expect($('h1').text()).to.equal('Foo');
}); });
}); });

View file

@ -24,7 +24,7 @@ describe('Sitemaps', () => {
); );
}); });
}); });
describe('Sitemap Generation', () => { describe('Sitemap Generation', () => {
it('Generates Sitemap correctly', async () => { it('Generates Sitemap correctly', async () => {
let sitemap = await fixture.readFile('/sitemap.xml'); let sitemap = await fixture.readFile('/sitemap.xml');
@ -33,4 +33,4 @@ describe('Sitemaps', () => {
); );
}); });
}); });
}); });

View file

@ -112,4 +112,4 @@ describe('Slots', () => {
expect($('#default')).to.have.lengthOf(1); // the default slot is filled expect($('#default')).to.have.lengthOf(1); // the default slot is filled
} }
}); });
}); });

View file

@ -4,7 +4,7 @@ import { devCLI, loadFixture } from './test-utils.js';
describe('config', () => { describe('config', () => {
let hostnameFixture; let hostnameFixture;
let portFixture; let portFixture;
before(async () => { before(async () => {
[hostnameFixture, portFixture] = await Promise.all([loadFixture({ projectRoot: './fixtures/config-hostname/' }), loadFixture({ projectRoot: './fixtures/config-port/' })]); [hostnameFixture, portFixture] = await Promise.all([loadFixture({ projectRoot: './fixtures/config-hostname/' }), loadFixture({ projectRoot: './fixtures/config-port/' })]);
}); });

File diff suppressed because it is too large Load diff

View file

@ -2,65 +2,65 @@
/// <reference path="./types/importMeta.d.ts" /> /// <reference path="./types/importMeta.d.ts" />
// CSS modules // CSS modules
type CSSModuleClasses = { readonly [key: string]: string } type CSSModuleClasses = { readonly [key: string]: string };
declare module '*.module.css' { declare module '*.module.css' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.scss' { declare module '*.module.scss' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.sass' { declare module '*.module.sass' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.less' { declare module '*.module.less' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.styl' { declare module '*.module.styl' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.stylus' { declare module '*.module.stylus' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
declare module '*.module.pcss' { declare module '*.module.pcss' {
const classes: CSSModuleClasses const classes: CSSModuleClasses;
export default classes export default classes;
} }
// CSS // CSS
declare module '*.css' { declare module '*.css' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.scss' { declare module '*.scss' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.sass' { declare module '*.sass' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.less' { declare module '*.less' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.styl' { declare module '*.styl' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.stylus' { declare module '*.stylus' {
const css: string const css: string;
export default css export default css;
} }
declare module '*.pcss' { declare module '*.pcss' {
const css: string const css: string;
export default css export default css;
} }
// Built-in asset types // Built-in asset types
@ -68,137 +68,137 @@ declare module '*.pcss' {
// images // images
declare module '*.jpg' { declare module '*.jpg' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.jpeg' { declare module '*.jpeg' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.png' { declare module '*.png' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.gif' { declare module '*.gif' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.svg' { declare module '*.svg' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.ico' { declare module '*.ico' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.webp' { declare module '*.webp' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.avif' { declare module '*.avif' {
const src: string const src: string;
export default src export default src;
} }
// media // media
declare module '*.mp4' { declare module '*.mp4' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.webm' { declare module '*.webm' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.ogg' { declare module '*.ogg' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.mp3' { declare module '*.mp3' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.wav' { declare module '*.wav' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.flac' { declare module '*.flac' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.aac' { declare module '*.aac' {
const src: string const src: string;
export default src export default src;
} }
// fonts // fonts
declare module '*.woff' { declare module '*.woff' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.woff2' { declare module '*.woff2' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.eot' { declare module '*.eot' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.ttf' { declare module '*.ttf' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.otf' { declare module '*.otf' {
const src: string const src: string;
export default src export default src;
} }
// other // other
declare module '*.wasm' { declare module '*.wasm' {
const initWasm: (options: WebAssembly.Imports) => Promise<WebAssembly.Exports> const initWasm: (options: WebAssembly.Imports) => Promise<WebAssembly.Exports>;
export default initWasm export default initWasm;
} }
declare module '*.webmanifest' { declare module '*.webmanifest' {
const src: string const src: string;
export default src export default src;
} }
declare module '*.pdf' { declare module '*.pdf' {
const src: string const src: string;
export default src export default src;
} }
// web worker // web worker
declare module '*?worker' { declare module '*?worker' {
const workerConstructor: { const workerConstructor: {
new (): Worker new (): Worker;
} };
export default workerConstructor export default workerConstructor;
} }
declare module '*?worker&inline' { declare module '*?worker&inline' {
const workerConstructor: { const workerConstructor: {
new (): Worker new (): Worker;
} };
export default workerConstructor export default workerConstructor;
} }
declare module '*?sharedworker' { declare module '*?sharedworker' {
const sharedWorkerConstructor: { const sharedWorkerConstructor: {
new (): SharedWorker new (): SharedWorker;
} };
export default sharedWorkerConstructor export default sharedWorkerConstructor;
} }
declare module '*?raw' { declare module '*?raw' {
const src: string const src: string;
export default src export default src;
} }
declare module '*?url' { declare module '*?url' {
const src: string const src: string;
export default src export default src;
} }
declare module '*?inline' { declare module '*?inline' {
const src: string const src: string;
export default src export default src;
} }

View file

@ -27,24 +27,24 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*/ */
import { PluginHooks } from 'rollup' import { PluginHooks } from 'rollup';
export interface Alias { export interface Alias {
find: string | RegExp find: string | RegExp;
replacement: string replacement: string;
/** /**
* Instructs the plugin to use an alternative resolving algorithm, * Instructs the plugin to use an alternative resolving algorithm,
* rather than the Rollup's resolver. * rather than the Rollup's resolver.
* @default null * @default null
*/ */
customResolver?: ResolverFunction | ResolverObject | null customResolver?: ResolverFunction | ResolverObject | null;
} }
export type ResolverFunction = PluginHooks['resolveId'] export type ResolverFunction = PluginHooks['resolveId'];
export interface ResolverObject { export interface ResolverObject {
buildStart?: PluginHooks['buildStart'] buildStart?: PluginHooks['buildStart'];
resolveId: ResolverFunction resolveId: ResolverFunction;
} }
/** /**
@ -56,4 +56,4 @@ export interface ResolverObject {
* This is passed to \@rollup/plugin-alias as the "entries" field * This is passed to \@rollup/plugin-alias as the "entries" field
* https://github.com/rollup/plugins/tree/master/packages/alias#entries * https://github.com/rollup/plugins/tree/master/packages/alias#entries
*/ */
export type AliasOptions = readonly Alias[] | { [find: string]: string } export type AliasOptions = readonly Alias[] | { [find: string]: string };

View file

@ -1,5 +1,5 @@
export type AnymatchFn = (testString: string) => boolean export type AnymatchFn = (testString: string) => boolean;
export type AnymatchPattern = string | RegExp | AnymatchFn export type AnymatchPattern = string | RegExp | AnymatchFn;
type AnymatchMatcher = AnymatchPattern | AnymatchPattern[] type AnymatchMatcher = AnymatchPattern | AnymatchPattern[];
export { AnymatchMatcher as Matcher } export { AnymatchMatcher as Matcher };

View file

@ -28,28 +28,28 @@ THE SOFTWARE.
*/ */
/// <reference types="node" /> /// <reference types="node" />
import * as fs from 'fs' import * as fs from 'fs';
import { Matcher } from './anymatch' import { Matcher } from './anymatch';
export interface FSWatcher extends fs.FSWatcher { export interface FSWatcher extends fs.FSWatcher {
options: WatchOptions options: WatchOptions;
/** /**
* Constructs a new FSWatcher instance with optional WatchOptions parameter. * Constructs a new FSWatcher instance with optional WatchOptions parameter.
*/ */
(options?: WatchOptions): void (options?: WatchOptions): void;
/** /**
* Add files, directories, or glob patterns for tracking. Takes an array of strings or just one * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one
* string. * string.
*/ */
add(paths: string | ReadonlyArray<string>): void add(paths: string | ReadonlyArray<string>): void;
/** /**
* Stop watching files, directories, or glob patterns. Takes an array of strings or just one * Stop watching files, directories, or glob patterns. Takes an array of strings or just one
* string. * string.
*/ */
unwatch(paths: string | ReadonlyArray<string>): void unwatch(paths: string | ReadonlyArray<string>): void;
/** /**
* Returns an object representing all the paths on the file system being watched by this * Returns an object representing all the paths on the file system being watched by this
@ -58,49 +58,36 @@ export interface FSWatcher extends fs.FSWatcher {
* each directory. * each directory.
*/ */
getWatched(): { getWatched(): {
[directory: string]: string[] [directory: string]: string[];
} };
/** /**
* Removes all listeners from watched files. * Removes all listeners from watched files.
*/ */
close(): Promise<void> close(): Promise<void>;
on( on(event: 'add' | 'addDir' | 'change', listener: (path: string, stats?: fs.Stats) => void): this;
event: 'add' | 'addDir' | 'change',
listener: (path: string, stats?: fs.Stats) => void
): this
on( on(event: 'all', listener: (eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string, stats?: fs.Stats) => void): this;
event: 'all',
listener: (
eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
path: string,
stats?: fs.Stats
) => void
): this
/** /**
* Error occurred * Error occurred
*/ */
on(event: 'error', listener: (error: Error) => void): this on(event: 'error', listener: (error: Error) => void): this;
/** /**
* Exposes the native Node `fs.FSWatcher events` * Exposes the native Node `fs.FSWatcher events`
*/ */
on( on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this;
event: 'raw',
listener: (eventName: string, path: string, details: any) => void
): this
/** /**
* Fires when the initial scan is complete * Fires when the initial scan is complete
*/ */
on(event: 'ready', listener: () => void): this on(event: 'ready', listener: () => void): this;
on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this;
on(event: string, listener: (...args: any[]) => void): this on(event: string, listener: (...args: any[]) => void): this;
} }
export interface WatchOptions { export interface WatchOptions {
@ -109,7 +96,7 @@ export interface WatchOptions {
* set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
* even if the process continues to run. * even if the process continues to run.
*/ */
persistent?: boolean persistent?: boolean;
/** /**
* ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to
@ -118,31 +105,31 @@ export interface WatchOptions {
* (the path), second time with two arguments (the path and the * (the path), second time with two arguments (the path and the
* [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path).
*/ */
ignored?: Matcher ignored?: Matcher;
/** /**
* If set to `false` then `add`/`addDir` events are also emitted for matching paths while * If set to `false` then `add`/`addDir` events are also emitted for matching paths while
* instantiating the watching as chokidar discovers these file paths (before the `ready` event). * instantiating the watching as chokidar discovers these file paths (before the `ready` event).
*/ */
ignoreInitial?: boolean ignoreInitial?: boolean;
/** /**
* When `false`, only the symlinks themselves will be watched for changes instead of following * When `false`, only the symlinks themselves will be watched for changes instead of following
* the link references and bubbling events through the link's path. * the link references and bubbling events through the link's path.
*/ */
followSymlinks?: boolean followSymlinks?: boolean;
/** /**
* The base directory from which watch `paths` are to be derived. Paths emitted with events will * The base directory from which watch `paths` are to be derived. Paths emitted with events will
* be relative to this. * be relative to this.
*/ */
cwd?: string cwd?: string;
/** /**
* If set to true then the strings passed to .watch() and .add() are treated as literal path * If set to true then the strings passed to .watch() and .add() are treated as literal path
* names, even if they look like globs. Default: false. * names, even if they look like globs. Default: false.
*/ */
disableGlobbing?: boolean disableGlobbing?: boolean;
/** /**
* Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU
@ -151,44 +138,44 @@ export interface WatchOptions {
* watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
* the `useFsEvents` default. * the `useFsEvents` default.
*/ */
usePolling?: boolean usePolling?: boolean;
/** /**
* Whether to use the `fsevents` watching interface if available. When set to `true` explicitly * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly
* and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on
* OS X, `usePolling: true` becomes the default. * OS X, `usePolling: true` becomes the default.
*/ */
useFsEvents?: boolean useFsEvents?: boolean;
/** /**
* If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that
* may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is
* provided even in cases where it wasn't already available from the underlying watch events. * provided even in cases where it wasn't already available from the underlying watch events.
*/ */
alwaysStat?: boolean alwaysStat?: boolean;
/** /**
* If set, limits how many levels of subdirectories will be traversed. * If set, limits how many levels of subdirectories will be traversed.
*/ */
depth?: number depth?: number;
/** /**
* Interval of file system polling. * Interval of file system polling.
*/ */
interval?: number interval?: number;
/** /**
* Interval of file system polling for binary files. ([see list of binary extensions](https://gi * Interval of file system polling for binary files. ([see list of binary extensions](https://gi
* thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
*/ */
binaryInterval?: number binaryInterval?: number;
/** /**
* Indicates whether to watch files that don't have read permissions if possible. If watching * Indicates whether to watch files that don't have read permissions if possible. If watching
* fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed
* silently. * silently.
*/ */
ignorePermissionErrors?: boolean ignorePermissionErrors?: boolean;
/** /**
* `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts
@ -197,7 +184,7 @@ export interface WatchOptions {
* event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you,
* you can override it by setting `atomic` to a custom value, in milliseconds. * you can override it by setting `atomic` to a custom value, in milliseconds.
*/ */
atomic?: boolean | number atomic?: boolean | number;
/** /**
* can be set to an object in order to adjust timing params: * can be set to an object in order to adjust timing params:
@ -207,12 +194,12 @@ export interface WatchOptions {
/** /**
* Amount of time in milliseconds for a file size to remain constant before emitting its event. * Amount of time in milliseconds for a file size to remain constant before emitting its event.
*/ */
stabilityThreshold?: number stabilityThreshold?: number;
/** /**
* File size polling interval. * File size polling interval.
*/ */
pollInterval?: number pollInterval?: number;
} }
| boolean | boolean;
} }

View file

@ -15,7 +15,7 @@ export interface RollupCommonJSOptions {
* statements or `transformMixedEsModules` is `true`. * statements or `transformMixedEsModules` is `true`.
* @default undefined * @default undefined
*/ */
include?: string | RegExp | readonly (string | RegExp)[] include?: string | RegExp | readonly (string | RegExp)[];
/** /**
* A minimatch pattern, or array of patterns, which specifies the files in * A minimatch pattern, or array of patterns, which specifies the files in
* the build the plugin should _ignore_. By default, all files with * the build the plugin should _ignore_. By default, all files with
@ -23,24 +23,24 @@ export interface RollupCommonJSOptions {
* can exclude additional files. See also the `include` option. * can exclude additional files. See also the `include` option.
* @default undefined * @default undefined
*/ */
exclude?: string | RegExp | readonly (string | RegExp)[] exclude?: string | RegExp | readonly (string | RegExp)[];
/** /**
* For extensionless imports, search for extensions other than .js in the * For extensionless imports, search for extensions other than .js in the
* order specified. Note that you need to make sure that non-JavaScript files * order specified. Note that you need to make sure that non-JavaScript files
* are transpiled by another plugin first. * are transpiled by another plugin first.
* @default [ '.js' ] * @default [ '.js' ]
*/ */
extensions?: ReadonlyArray<string> extensions?: ReadonlyArray<string>;
/** /**
* If true then uses of `global` won't be dealt with by this plugin * If true then uses of `global` won't be dealt with by this plugin
* @default false * @default false
*/ */
ignoreGlobal?: boolean ignoreGlobal?: boolean;
/** /**
* If false, skips source map generation for CommonJS modules. This will improve performance. * If false, skips source map generation for CommonJS modules. This will improve performance.
* @default true * @default true
*/ */
sourceMap?: boolean sourceMap?: boolean;
/** /**
* Some `require` calls cannot be resolved statically to be translated to * Some `require` calls cannot be resolved statically to be translated to
* imports. * imports.
@ -52,7 +52,7 @@ export interface RollupCommonJSOptions {
* code or use it as a fallback for `dynamicRequireTargets`. * code or use it as a fallback for `dynamicRequireTargets`.
* @default false * @default false
*/ */
ignoreDynamicRequires?: boolean ignoreDynamicRequires?: boolean;
/** /**
* Instructs the plugin whether to enable mixed module transformations. This * Instructs the plugin whether to enable mixed module transformations. This
* is useful in scenarios with modules that contain a mix of ES `import` * is useful in scenarios with modules that contain a mix of ES `import`
@ -64,13 +64,13 @@ export interface RollupCommonJSOptions {
* ElectronJS. See also the `ignore` option. * ElectronJS. See also the `ignore` option.
* @default false * @default false
*/ */
transformMixedEsModules?: boolean transformMixedEsModules?: boolean;
/** /**
* Sometimes you have to leave require statements unconverted. Pass an array * Sometimes you have to leave require statements unconverted. Pass an array
* containing the IDs or a `id => boolean` function. * containing the IDs or a `id => boolean` function.
* @default [] * @default []
*/ */
ignore?: ReadonlyArray<string> | ((id: string) => boolean) ignore?: ReadonlyArray<string> | ((id: string) => boolean);
/** /**
* Controls how to render imports from external dependencies. By default, * Controls how to render imports from external dependencies. By default,
* this plugin assumes that all external dependencies are CommonJS. This * this plugin assumes that all external dependencies are CommonJS. This
@ -88,7 +88,7 @@ export interface RollupCommonJSOptions {
* module. * module.
* @default false * @default false
*/ */
esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean) esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean);
/** /**
* Controls what is returned when requiring an ES module from a CommonJS file. * Controls what is returned when requiring an ES module from a CommonJS file.
* When using the `esmExternals` option, this will also apply to external * When using the `esmExternals` option, this will also apply to external
@ -139,12 +139,7 @@ export interface RollupCommonJSOptions {
* and allows you to return different values for different modules. * and allows you to return different values for different modules.
* @default false * @default false
*/ */
requireReturnsDefault?: requireReturnsDefault?: boolean | 'auto' | 'preferred' | 'namespace' | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace');
| boolean
| 'auto'
| 'preferred'
| 'namespace'
| ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
/** /**
* Some modules contain dynamic `require` calls, or require modules that * Some modules contain dynamic `require` calls, or require modules that
* contain circular dependencies, which are not handled well by static * contain circular dependencies, which are not handled well by static
@ -158,5 +153,5 @@ export interface RollupCommonJSOptions {
* with paths that are far away from your project's folder, that may require * with paths that are far away from your project's folder, that may require
* replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`. * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`.
*/ */
dynamicRequireTargets?: string | ReadonlyArray<string> dynamicRequireTargets?: string | ReadonlyArray<string>;
} }

View file

@ -8,47 +8,32 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" /> /// <reference types="node" />
import * as http from 'http' import * as http from 'http';
export namespace Connect { export namespace Connect {
export type ServerHandle = HandleFunction | http.Server export type ServerHandle = HandleFunction | http.Server;
export class IncomingMessage extends http.IncomingMessage { export class IncomingMessage extends http.IncomingMessage {
originalUrl?: http.IncomingMessage['url'] originalUrl?: http.IncomingMessage['url'];
} }
export type NextFunction = (err?: any) => void export type NextFunction = (err?: any) => void;
export type SimpleHandleFunction = ( export type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void;
req: IncomingMessage, export type NextHandleFunction = (req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
res: http.ServerResponse export type ErrorHandleFunction = (err: any, req: IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
) => void export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction;
export type NextHandleFunction = (
req: IncomingMessage,
res: http.ServerResponse,
next: NextFunction
) => void
export type ErrorHandleFunction = (
err: any,
req: IncomingMessage,
res: http.ServerResponse,
next: NextFunction
) => void
export type HandleFunction =
| SimpleHandleFunction
| NextHandleFunction
| ErrorHandleFunction
export interface ServerStackItem { export interface ServerStackItem {
route: string route: string;
handle: ServerHandle handle: ServerHandle;
} }
export interface Server extends NodeJS.EventEmitter { export interface Server extends NodeJS.EventEmitter {
(req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void;
route: string route: string;
stack: ServerStackItem[] stack: ServerStackItem[];
/** /**
* Utilize the given middleware `handle` to the given `route`, * Utilize the given middleware `handle` to the given `route`,
@ -61,20 +46,16 @@ export namespace Connect {
* be invoked on _/admin_, and _/admin/settings_, however it would * be invoked on _/admin_, and _/admin/settings_, however it would
* not be invoked for _/_, or _/posts_. * not be invoked for _/_, or _/posts_.
*/ */
use(fn: NextHandleFunction): Server use(fn: NextHandleFunction): Server;
use(fn: HandleFunction): Server use(fn: HandleFunction): Server;
use(route: string, fn: NextHandleFunction): Server use(route: string, fn: NextHandleFunction): Server;
use(route: string, fn: HandleFunction): Server use(route: string, fn: HandleFunction): Server;
/** /**
* Handle server requests, punting them down * Handle server requests, punting them down
* the middleware stack. * the middleware stack.
*/ */
handle( handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void;
req: http.IncomingMessage,
res: http.ServerResponse,
next: Function
): void
/** /**
* Listen for connections. * Listen for connections.
@ -98,14 +79,9 @@ export namespace Connect {
* http.createServer(app).listen(80); * http.createServer(app).listen(80);
* https.createServer(options, app).listen(443); * https.createServer(options, app).listen(443);
*/ */
listen( listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server;
port: number, listen(port: number, hostname?: string, callback?: Function): http.Server;
hostname?: string, listen(path: string, callback?: Function): http.Server;
backlog?: number, listen(handle: any, listeningListener?: Function): http.Server;
callback?: Function
): http.Server
listen(port: number, hostname?: string, callback?: Function): http.Server
listen(path: string, callback?: Function): http.Server
listen(handle: any, listeningListener?: Function): http.Server
} }
} }

View file

@ -1,5 +1,2 @@
// See https://stackoverflow.com/a/63549561. // See https://stackoverflow.com/a/63549561.
export type CustomEventName<T extends string> = (T extends `vite:${T}` export type CustomEventName<T extends string> = (T extends `vite:${T}` ? never : T) & (`vite:${T}` extends T ? never : T);
? never
: T) &
(`vite:${T}` extends T ? never : T)

View file

@ -3,15 +3,15 @@ export interface RollupDynamicImportVarsOptions {
* Files to include in this plugin (default all). * Files to include in this plugin (default all).
* @default [] * @default []
*/ */
include?: string | RegExp | (string | RegExp)[] include?: string | RegExp | (string | RegExp)[];
/** /**
* Files to exclude in this plugin (default none). * Files to exclude in this plugin (default none).
* @default [] * @default []
*/ */
exclude?: string | RegExp | (string | RegExp)[] exclude?: string | RegExp | (string | RegExp)[];
/** /**
* By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched. * By default, the plugin quits the build process when it encounters an error. If you set this option to true, it will throw a warning instead and leave the code untouched.
* @default false * @default false
*/ */
warnOnError?: boolean warnOnError?: boolean;
} }

View file

@ -1,57 +1,51 @@
export type HMRPayload = export type HMRPayload = ConnectedPayload | UpdatePayload | FullReloadPayload | CustomPayload | ErrorPayload | PrunePayload;
| ConnectedPayload
| UpdatePayload
| FullReloadPayload
| CustomPayload
| ErrorPayload
| PrunePayload
export interface ConnectedPayload { export interface ConnectedPayload {
type: 'connected' type: 'connected';
} }
export interface UpdatePayload { export interface UpdatePayload {
type: 'update' type: 'update';
updates: Update[] updates: Update[];
} }
export interface Update { export interface Update {
type: 'js-update' | 'css-update' type: 'js-update' | 'css-update';
path: string path: string;
acceptedPath: string acceptedPath: string;
timestamp: number timestamp: number;
} }
export interface PrunePayload { export interface PrunePayload {
type: 'prune' type: 'prune';
paths: string[] paths: string[];
} }
export interface FullReloadPayload { export interface FullReloadPayload {
type: 'full-reload' type: 'full-reload';
path?: string path?: string;
} }
export interface CustomPayload { export interface CustomPayload {
type: 'custom' type: 'custom';
event: string event: string;
data?: any data?: any;
} }
export interface ErrorPayload { export interface ErrorPayload {
type: 'error' type: 'error';
err: { err: {
[name: string]: any [name: string]: any;
message: string message: string;
stack: string stack: string;
id?: string id?: string;
frame?: string frame?: string;
plugin?: string plugin?: string;
pluginCode?: string pluginCode?: string;
loc?: { loc?: {
file?: string file?: string;
line: number line: number;
column: number column: number;
} };
} };
} }

View file

@ -13,45 +13,40 @@
/// <reference types="node" /> /// <reference types="node" />
import * as net from 'net' import * as net from 'net';
import * as http from 'http' import * as http from 'http';
import * as events from 'events' import * as events from 'events';
import * as url from 'url' import * as url from 'url';
import * as stream from 'stream' import * as stream from 'stream';
export namespace HttpProxy { export namespace HttpProxy {
export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed;
export type ProxyTargetUrl = string | Partial<url.Url> export type ProxyTargetUrl = string | Partial<url.Url>;
export interface ProxyTargetDetailed { export interface ProxyTargetDetailed {
host: string host: string;
port: number port: number;
protocol?: string protocol?: string;
hostname?: string hostname?: string;
socketPath?: string socketPath?: string;
key?: string key?: string;
passphrase?: string passphrase?: string;
pfx?: Buffer | string pfx?: Buffer | string;
cert?: string cert?: string;
ca?: string ca?: string;
ciphers?: string ciphers?: string;
secureProtocol?: string secureProtocol?: string;
} }
export type ErrorCallback = ( export type ErrorCallback = (err: Error, req: http.IncomingMessage, res: http.ServerResponse, target?: ProxyTargetUrl) => void;
err: Error,
req: http.IncomingMessage,
res: http.ServerResponse,
target?: ProxyTargetUrl
) => void
export class Server extends events.EventEmitter { export class Server extends events.EventEmitter {
/** /**
* Creates the proxy server with specified options. * Creates the proxy server with specified options.
* @param options - Config object passed to the proxy * @param options - Config object passed to the proxy
*/ */
constructor(options?: ServerOptions) constructor(options?: ServerOptions);
/** /**
* Used for proxying regular HTTP(S) requests * Used for proxying regular HTTP(S) requests
@ -59,12 +54,7 @@ export namespace HttpProxy {
* @param res - Client response. * @param res - Client response.
* @param options - Additionnal options. * @param options - Additionnal options.
*/ */
web( web(req: http.IncomingMessage, res: http.ServerResponse, options?: ServerOptions, callback?: ErrorCallback): void;
req: http.IncomingMessage,
res: http.ServerResponse,
options?: ServerOptions,
callback?: ErrorCallback
): void
/** /**
* Used for proxying regular HTTP(S) requests * Used for proxying regular HTTP(S) requests
@ -73,170 +63,111 @@ export namespace HttpProxy {
* @param head - Client head. * @param head - Client head.
* @param options - Additional options. * @param options - Additional options.
*/ */
ws( ws(req: http.IncomingMessage, socket: unknown, head: unknown, options?: ServerOptions, callback?: ErrorCallback): void;
req: http.IncomingMessage,
socket: unknown,
head: unknown,
options?: ServerOptions,
callback?: ErrorCallback
): void
/** /**
* A function that wraps the object in a webserver, for your convenience * A function that wraps the object in a webserver, for your convenience
* @param port - Port to listen on * @param port - Port to listen on
*/ */
listen(port: number): Server listen(port: number): Server;
/** /**
* A function that closes the inner webserver and stops listening on given port * A function that closes the inner webserver and stops listening on given port
*/ */
close(callback?: () => void): void close(callback?: () => void): void;
/** /**
* Creates the proxy server with specified options. * Creates the proxy server with specified options.
* @param options - Config object passed to the proxy * @param options - Config object passed to the proxy
* @returns Proxy object with handlers for `ws` and `web` requests * @returns Proxy object with handlers for `ws` and `web` requests
*/ */
static createProxyServer(options?: ServerOptions): Server static createProxyServer(options?: ServerOptions): Server;
/** /**
* Creates the proxy server with specified options. * Creates the proxy server with specified options.
* @param options - Config object passed to the proxy * @param options - Config object passed to the proxy
* @returns Proxy object with handlers for `ws` and `web` requests * @returns Proxy object with handlers for `ws` and `web` requests
*/ */
static createServer(options?: ServerOptions): Server static createServer(options?: ServerOptions): Server;
/** /**
* Creates the proxy server with specified options. * Creates the proxy server with specified options.
* @param options - Config object passed to the proxy * @param options - Config object passed to the proxy
* @returns Proxy object with handlers for `ws` and `web` requests * @returns Proxy object with handlers for `ws` and `web` requests
*/ */
static createProxy(options?: ServerOptions): Server static createProxy(options?: ServerOptions): Server;
addListener(event: string, listener: () => void): this addListener(event: string, listener: () => void): this;
on(event: string, listener: () => void): this on(event: string, listener: () => void): this;
on(event: 'error', listener: ErrorCallback): this on(event: 'error', listener: ErrorCallback): this;
on( on(event: 'start', listener: (req: http.IncomingMessage, res: http.ServerResponse, target: ProxyTargetUrl) => void): this;
event: 'start', on(event: 'proxyReq', listener: (proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse, options: ServerOptions) => void): this;
listener: ( on(event: 'proxyRes', listener: (proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse) => void): this;
req: http.IncomingMessage, on(event: 'proxyReqWs', listener: (proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: net.Socket, options: ServerOptions, head: any) => void): this;
res: http.ServerResponse, on(event: 'econnreset', listener: (err: Error, req: http.IncomingMessage, res: http.ServerResponse, target: ProxyTargetUrl) => void): this;
target: ProxyTargetUrl on(event: 'end', listener: (req: http.IncomingMessage, res: http.ServerResponse, proxyRes: http.IncomingMessage) => void): this;
) => void on(event: 'close', listener: (proxyRes: http.IncomingMessage, proxySocket: net.Socket, proxyHead: any) => void): this;
): this
on(
event: 'proxyReq',
listener: (
proxyReq: http.ClientRequest,
req: http.IncomingMessage,
res: http.ServerResponse,
options: ServerOptions
) => void
): this
on(
event: 'proxyRes',
listener: (
proxyRes: http.IncomingMessage,
req: http.IncomingMessage,
res: http.ServerResponse
) => void
): this
on(
event: 'proxyReqWs',
listener: (
proxyReq: http.ClientRequest,
req: http.IncomingMessage,
socket: net.Socket,
options: ServerOptions,
head: any
) => void
): this
on(
event: 'econnreset',
listener: (
err: Error,
req: http.IncomingMessage,
res: http.ServerResponse,
target: ProxyTargetUrl
) => void
): this
on(
event: 'end',
listener: (
req: http.IncomingMessage,
res: http.ServerResponse,
proxyRes: http.IncomingMessage
) => void
): this
on(
event: 'close',
listener: (
proxyRes: http.IncomingMessage,
proxySocket: net.Socket,
proxyHead: any
) => void
): this
once(event: string, listener: () => void): this once(event: string, listener: () => void): this;
removeListener(event: string, listener: () => void): this removeListener(event: string, listener: () => void): this;
removeAllListeners(event?: string): this removeAllListeners(event?: string): this;
getMaxListeners(): number getMaxListeners(): number;
setMaxListeners(n: number): this setMaxListeners(n: number): this;
listeners(event: string): Array<() => void> listeners(event: string): Array<() => void>;
emit(event: string, ...args: any[]): boolean emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number listenerCount(type: string): number;
} }
export interface ServerOptions { export interface ServerOptions {
/** URL string to be parsed with the url module. */ /** URL string to be parsed with the url module. */
target?: ProxyTarget target?: ProxyTarget;
/** URL string to be parsed with the url module. */ /** URL string to be parsed with the url module. */
forward?: ProxyTargetUrl forward?: ProxyTargetUrl;
/** Object to be passed to http(s).request. */ /** Object to be passed to http(s).request. */
agent?: any agent?: any;
/** Object to be passed to https.createServer(). */ /** Object to be passed to https.createServer(). */
ssl?: any ssl?: any;
/** If you want to proxy websockets. */ /** If you want to proxy websockets. */
ws?: boolean ws?: boolean;
/** Adds x- forward headers. */ /** Adds x- forward headers. */
xfwd?: boolean xfwd?: boolean;
/** Verify SSL certificate. */ /** Verify SSL certificate. */
secure?: boolean secure?: boolean;
/** Explicitly specify if we are proxying to another proxy. */ /** Explicitly specify if we are proxying to another proxy. */
toProxy?: boolean toProxy?: boolean;
/** Specify whether you want to prepend the target's path to the proxy path. */ /** Specify whether you want to prepend the target's path to the proxy path. */
prependPath?: boolean prependPath?: boolean;
/** Specify whether you want to ignore the proxy path of the incoming request. */ /** Specify whether you want to ignore the proxy path of the incoming request. */
ignorePath?: boolean ignorePath?: boolean;
/** Local interface string to bind for outgoing connections. */ /** Local interface string to bind for outgoing connections. */
localAddress?: string localAddress?: string;
/** Changes the origin of the host header to the target URL. */ /** Changes the origin of the host header to the target URL. */
changeOrigin?: boolean changeOrigin?: boolean;
/** specify whether you want to keep letter case of response header key */ /** specify whether you want to keep letter case of response header key */
preserveHeaderKeyCase?: boolean preserveHeaderKeyCase?: boolean;
/** Basic authentication i.e. 'user:password' to compute an Authorization header. */ /** Basic authentication i.e. 'user:password' to compute an Authorization header. */
auth?: string auth?: string;
/** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */
hostRewrite?: string hostRewrite?: string;
/** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */
autoRewrite?: boolean autoRewrite?: boolean;
/** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */
protocolRewrite?: string protocolRewrite?: string;
/** rewrites domain of set-cookie headers. */ /** rewrites domain of set-cookie headers. */
cookieDomainRewrite?: false | string | { [oldDomain: string]: string } cookieDomainRewrite?: false | string | { [oldDomain: string]: string };
/** rewrites path of set-cookie headers. Default: false */ /** rewrites path of set-cookie headers. Default: false */
cookiePathRewrite?: false | string | { [oldPath: string]: string } cookiePathRewrite?: false | string | { [oldPath: string]: string };
/** object with extra headers to be added to target requests. */ /** object with extra headers to be added to target requests. */
headers?: { [header: string]: string } headers?: { [header: string]: string };
/** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */
proxyTimeout?: number proxyTimeout?: number;
/** Timeout (in milliseconds) for incoming requests */ /** Timeout (in milliseconds) for incoming requests */
timeout?: number timeout?: number;
/** Specify whether you want to follow redirects. Default: false */ /** Specify whether you want to follow redirects. Default: false */
followRedirects?: boolean followRedirects?: boolean;
/** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */ /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */
selfHandleResponse?: boolean selfHandleResponse?: boolean;
/** Buffer */ /** Buffer */
buffer?: stream.Stream buffer?: stream.Stream;
} }
} }

View file

@ -1,69 +1,54 @@
interface ImportMeta { interface ImportMeta {
url: string url: string;
readonly hot?: { readonly hot?: {
readonly data: any readonly data: any;
accept(): void accept(): void;
accept(cb: (mod: any) => void): void accept(cb: (mod: any) => void): void;
accept(dep: string, cb: (mod: any) => void): void accept(dep: string, cb: (mod: any) => void): void;
accept(deps: readonly string[], cb: (mods: any[]) => void): void accept(deps: readonly string[], cb: (mods: any[]) => void): void;
/** /**
* @deprecated * @deprecated
*/ */
acceptDeps(): never acceptDeps(): never;
dispose(cb: (data: any) => void): void dispose(cb: (data: any) => void): void;
decline(): void decline(): void;
invalidate(): void invalidate(): void;
on: { on: {
( (event: 'vite:beforeUpdate', cb: (payload: import('./hmrPayload').UpdatePayload) => void): void;
event: 'vite:beforeUpdate', (event: 'vite:beforePrune', cb: (payload: import('./hmrPayload').PrunePayload) => void): void;
cb: (payload: import('./hmrPayload').UpdatePayload) => void (event: 'vite:beforeFullReload', cb: (payload: import('./hmrPayload').FullReloadPayload) => void): void;
): void (event: 'vite:error', cb: (payload: import('./hmrPayload').ErrorPayload) => void): void;
( <T extends string>(event: import('./customEvent').CustomEventName<T>, cb: (data: any) => void): void;
event: 'vite:beforePrune', };
cb: (payload: import('./hmrPayload').PrunePayload) => void };
): void
(
event: 'vite:beforeFullReload',
cb: (payload: import('./hmrPayload').FullReloadPayload) => void
): void
(
event: 'vite:error',
cb: (payload: import('./hmrPayload').ErrorPayload) => void
): void
<T extends string>(
event: import('./customEvent').CustomEventName<T>,
cb: (data: any) => void
): void
}
}
readonly env: ImportMetaEnv readonly env: ImportMetaEnv;
glob(pattern: string): Record< glob(pattern: string): Record<
string, string,
() => Promise<{ () => Promise<{
[key: string]: any [key: string]: any;
}> }>
> >;
globEager(pattern: string): Record< globEager(pattern: string): Record<
string, string,
{ {
[key: string]: any [key: string]: any;
} }
> >;
} }
interface ImportMetaEnv { interface ImportMetaEnv {
[key: string]: string | boolean | undefined [key: string]: string | boolean | undefined;
BASE_URL: string BASE_URL: string;
MODE: string MODE: string;
DEV: boolean DEV: boolean;
PROD: boolean PROD: boolean;
SSR: boolean SSR: boolean;
} }

View file

@ -1,108 +1,102 @@
declare module 'connect' { declare module 'connect' {
const connect: () => any const connect: () => any;
export = connect export = connect;
} }
declare module 'cors' { declare module 'cors' {
function cors(options: any): any function cors(options: any): any;
export = cors export = cors;
} }
declare module 'selfsigned' { declare module 'selfsigned' {
export function generate(attrs: any, options: any, done?: any): any export function generate(attrs: any, options: any, done?: any): any;
} }
declare module 'http-proxy' { declare module 'http-proxy' {
const proxy: any const proxy: any;
export = proxy export = proxy;
} }
declare module 'acorn-class-fields' { declare module 'acorn-class-fields' {
const plugin: any const plugin: any;
export = plugin export = plugin;
} }
declare module 'acorn-static-class-features' { declare module 'acorn-static-class-features' {
const plugin: any const plugin: any;
export default plugin export default plugin;
} }
declare module 'connect-history-api-fallback' { declare module 'connect-history-api-fallback' {
const plugin: any const plugin: any;
export = plugin export = plugin;
} }
declare module 'launch-editor-middleware' { declare module 'launch-editor-middleware' {
const plugin: any const plugin: any;
export = plugin export = plugin;
} }
declare module 'postcss-load-config' { declare module 'postcss-load-config' {
import { ProcessOptions, Plugin } from 'postcss' import { ProcessOptions, Plugin } from 'postcss';
function load( function load(
inline: any, inline: any,
root: string root: string
): Promise<{ ): Promise<{
options: ProcessOptions options: ProcessOptions;
plugins: Plugin[] plugins: Plugin[];
}> }>;
export = load export = load;
} }
declare module 'postcss-import' { declare module 'postcss-import' {
import { Plugin } from 'postcss' import { Plugin } from 'postcss';
const plugin: (options: { const plugin: (options: { resolve: (id: string, basedir: string, importOptions: any) => string | string[] | Promise<string | string[]> }) => Plugin;
resolve: ( export = plugin;
id: string,
basedir: string,
importOptions: any
) => string | string[] | Promise<string | string[]>
}) => Plugin
export = plugin
} }
declare module 'postcss-modules' { declare module 'postcss-modules' {
import { Plugin } from 'postcss' import { Plugin } from 'postcss';
const plugin: (options: any) => Plugin const plugin: (options: any) => Plugin;
export = plugin export = plugin;
} }
declare module '@rollup/plugin-dynamic-import-vars' { declare module '@rollup/plugin-dynamic-import-vars' {
import { Plugin } from 'rollup' import { Plugin } from 'rollup';
interface Options { interface Options {
include?: string | RegExp | (string | RegExp)[] include?: string | RegExp | (string | RegExp)[];
exclude?: string | RegExp | (string | RegExp)[] exclude?: string | RegExp | (string | RegExp)[];
warnOnError?: boolean warnOnError?: boolean;
} }
const p: (o?: Options) => Plugin const p: (o?: Options) => Plugin;
export default p export default p;
} }
declare module 'rollup-plugin-web-worker-loader' { declare module 'rollup-plugin-web-worker-loader' {
import { Plugin } from 'rollup' import { Plugin } from 'rollup';
interface Options { interface Options {
targetPlatform?: string targetPlatform?: string;
pattern?: RegExp pattern?: RegExp;
extensions?: string[] extensions?: string[];
sourcemap?: boolean sourcemap?: boolean;
inline?: boolean inline?: boolean;
} }
const p: (o?: Options) => Plugin const p: (o?: Options) => Plugin;
export default p export default p;
} }
declare module 'minimatch' { declare module 'minimatch' {
function match(path: string, pattern: string): boolean function match(path: string, pattern: string): boolean;
export default match export default match;
} }
declare module 'compression' { declare module 'compression' {
function compression(): any function compression(): any;
export default compression export default compression;
} }
// LESS' types somewhat references this which doesn't make sense in Node, // LESS' types somewhat references this which doesn't make sense in Node,

View file

@ -35,102 +35,102 @@ SUCH DAMAGE.
*/ */
export namespace Terser { export namespace Terser {
export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020;
export interface ParseOptions { export interface ParseOptions {
bare_returns?: boolean bare_returns?: boolean;
ecma?: ECMA ecma?: ECMA;
html5_comments?: boolean html5_comments?: boolean;
shebang?: boolean shebang?: boolean;
} }
export interface CompressOptions { export interface CompressOptions {
arguments?: boolean arguments?: boolean;
arrows?: boolean arrows?: boolean;
booleans_as_integers?: boolean booleans_as_integers?: boolean;
booleans?: boolean booleans?: boolean;
collapse_vars?: boolean collapse_vars?: boolean;
comparisons?: boolean comparisons?: boolean;
computed_props?: boolean computed_props?: boolean;
conditionals?: boolean conditionals?: boolean;
dead_code?: boolean dead_code?: boolean;
defaults?: boolean defaults?: boolean;
directives?: boolean directives?: boolean;
drop_console?: boolean drop_console?: boolean;
drop_debugger?: boolean drop_debugger?: boolean;
ecma?: ECMA ecma?: ECMA;
evaluate?: boolean evaluate?: boolean;
expression?: boolean expression?: boolean;
global_defs?: object global_defs?: object;
hoist_funs?: boolean hoist_funs?: boolean;
hoist_props?: boolean hoist_props?: boolean;
hoist_vars?: boolean hoist_vars?: boolean;
ie8?: boolean ie8?: boolean;
if_return?: boolean if_return?: boolean;
inline?: boolean | InlineFunctions inline?: boolean | InlineFunctions;
join_vars?: boolean join_vars?: boolean;
keep_classnames?: boolean | RegExp keep_classnames?: boolean | RegExp;
keep_fargs?: boolean keep_fargs?: boolean;
keep_fnames?: boolean | RegExp keep_fnames?: boolean | RegExp;
keep_infinity?: boolean keep_infinity?: boolean;
loops?: boolean loops?: boolean;
module?: boolean module?: boolean;
negate_iife?: boolean negate_iife?: boolean;
passes?: number passes?: number;
properties?: boolean properties?: boolean;
pure_funcs?: string[] pure_funcs?: string[];
pure_getters?: boolean | 'strict' pure_getters?: boolean | 'strict';
reduce_funcs?: boolean reduce_funcs?: boolean;
reduce_vars?: boolean reduce_vars?: boolean;
sequences?: boolean | number sequences?: boolean | number;
side_effects?: boolean side_effects?: boolean;
switches?: boolean switches?: boolean;
toplevel?: boolean toplevel?: boolean;
top_retain?: null | string | string[] | RegExp top_retain?: null | string | string[] | RegExp;
typeofs?: boolean typeofs?: boolean;
unsafe_arrows?: boolean unsafe_arrows?: boolean;
unsafe?: boolean unsafe?: boolean;
unsafe_comps?: boolean unsafe_comps?: boolean;
unsafe_Function?: boolean unsafe_Function?: boolean;
unsafe_math?: boolean unsafe_math?: boolean;
unsafe_symbols?: boolean unsafe_symbols?: boolean;
unsafe_methods?: boolean unsafe_methods?: boolean;
unsafe_proto?: boolean unsafe_proto?: boolean;
unsafe_regexp?: boolean unsafe_regexp?: boolean;
unsafe_undefined?: boolean unsafe_undefined?: boolean;
unused?: boolean unused?: boolean;
} }
export enum InlineFunctions { export enum InlineFunctions {
Disabled = 0, Disabled = 0,
SimpleFunctions = 1, SimpleFunctions = 1,
WithArguments = 2, WithArguments = 2,
WithArgumentsAndVariables = 3 WithArgumentsAndVariables = 3,
} }
export interface MangleOptions { export interface MangleOptions {
eval?: boolean eval?: boolean;
keep_classnames?: boolean | RegExp keep_classnames?: boolean | RegExp;
keep_fnames?: boolean | RegExp keep_fnames?: boolean | RegExp;
module?: boolean module?: boolean;
properties?: boolean | ManglePropertiesOptions properties?: boolean | ManglePropertiesOptions;
reserved?: string[] reserved?: string[];
safari10?: boolean safari10?: boolean;
toplevel?: boolean toplevel?: boolean;
} }
export interface ManglePropertiesOptions { export interface ManglePropertiesOptions {
builtins?: boolean builtins?: boolean;
debug?: boolean debug?: boolean;
keep_quoted?: boolean | 'strict' keep_quoted?: boolean | 'strict';
regex?: RegExp | string regex?: RegExp | string;
reserved?: string[] reserved?: string[];
} }
export interface FormatOptions { export interface FormatOptions {
ascii_only?: boolean ascii_only?: boolean;
beautify?: boolean beautify?: boolean;
braces?: boolean braces?: boolean;
comments?: comments?:
| boolean | boolean
| 'all' | 'all'
@ -139,71 +139,71 @@ export namespace Terser {
| (( | ((
node: any, node: any,
comment: { comment: {
value: string value: string;
type: 'comment1' | 'comment2' | 'comment3' | 'comment4' type: 'comment1' | 'comment2' | 'comment3' | 'comment4';
pos: number pos: number;
line: number line: number;
col: number col: number;
} }
) => boolean) ) => boolean);
ecma?: ECMA ecma?: ECMA;
ie8?: boolean ie8?: boolean;
indent_level?: number indent_level?: number;
indent_start?: number indent_start?: number;
inline_script?: boolean inline_script?: boolean;
keep_quoted_props?: boolean keep_quoted_props?: boolean;
max_line_len?: number | false max_line_len?: number | false;
preamble?: string preamble?: string;
preserve_annotations?: boolean preserve_annotations?: boolean;
quote_keys?: boolean quote_keys?: boolean;
quote_style?: OutputQuoteStyle quote_style?: OutputQuoteStyle;
safari10?: boolean safari10?: boolean;
semicolons?: boolean semicolons?: boolean;
shebang?: boolean shebang?: boolean;
shorthand?: boolean shorthand?: boolean;
source_map?: SourceMapOptions source_map?: SourceMapOptions;
webkit?: boolean webkit?: boolean;
width?: number width?: number;
wrap_iife?: boolean wrap_iife?: boolean;
wrap_func_args?: boolean wrap_func_args?: boolean;
} }
export enum OutputQuoteStyle { export enum OutputQuoteStyle {
PreferDouble = 0, PreferDouble = 0,
AlwaysSingle = 1, AlwaysSingle = 1,
AlwaysDouble = 2, AlwaysDouble = 2,
AlwaysOriginal = 3 AlwaysOriginal = 3,
} }
export interface MinifyOptions { export interface MinifyOptions {
compress?: boolean | CompressOptions compress?: boolean | CompressOptions;
ecma?: ECMA ecma?: ECMA;
ie8?: boolean ie8?: boolean;
keep_classnames?: boolean | RegExp keep_classnames?: boolean | RegExp;
keep_fnames?: boolean | RegExp keep_fnames?: boolean | RegExp;
mangle?: boolean | MangleOptions mangle?: boolean | MangleOptions;
module?: boolean module?: boolean;
nameCache?: object nameCache?: object;
format?: FormatOptions format?: FormatOptions;
/** @deprecated use format instead */ /** @deprecated use format instead */
output?: FormatOptions output?: FormatOptions;
parse?: ParseOptions parse?: ParseOptions;
safari10?: boolean safari10?: boolean;
sourceMap?: boolean | SourceMapOptions sourceMap?: boolean | SourceMapOptions;
toplevel?: boolean toplevel?: boolean;
} }
export interface MinifyOutput { export interface MinifyOutput {
code?: string code?: string;
map?: object | string map?: object | string;
} }
export interface SourceMapOptions { export interface SourceMapOptions {
/** Source map object, 'inline' or source map file content */ /** Source map object, 'inline' or source map file content */
content?: object | string content?: object | string;
includeSources?: boolean includeSources?: boolean;
filename?: string filename?: string;
root?: string root?: string;
url?: string | 'inline' url?: string | 'inline';
} }
} }

View file

@ -14,317 +14,144 @@
/// <reference types="node" /> /// <reference types="node" />
import { EventEmitter } from 'events' import { EventEmitter } from 'events';
import { import { Agent, ClientRequest, ClientRequestArgs, IncomingMessage, OutgoingHttpHeaders, Server as HTTPServer } from 'http';
Agent, import { Server as HTTPSServer } from 'https';
ClientRequest, import { Socket } from 'net';
ClientRequestArgs, import { Duplex, DuplexOptions } from 'stream';
IncomingMessage, import { SecureContextOptions } from 'tls';
OutgoingHttpHeaders, import { URL } from 'url';
Server as HTTPServer import { ZlibOptions } from 'zlib';
} from 'http'
import { Server as HTTPSServer } from 'https'
import { Socket } from 'net'
import { Duplex, DuplexOptions } from 'stream'
import { SecureContextOptions } from 'tls'
import { URL } from 'url'
import { ZlibOptions } from 'zlib'
export declare namespace WebSocket { export declare namespace WebSocket {
// WebSocket socket. // WebSocket socket.
export class WebSocket extends EventEmitter { export class WebSocket extends EventEmitter {
/** The connection is not yet open. */ /** The connection is not yet open. */
static readonly CONNECTING: 0 static readonly CONNECTING: 0;
/** The connection is open and ready to communicate. */ /** The connection is open and ready to communicate. */
static readonly OPEN: 1 static readonly OPEN: 1;
/** The connection is in the process of closing. */ /** The connection is in the process of closing. */
static readonly CLOSING: 2 static readonly CLOSING: 2;
/** The connection is closed. */ /** The connection is closed. */
static readonly CLOSED: 3 static readonly CLOSED: 3;
binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments' binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments';
readonly bufferedAmount: number readonly bufferedAmount: number;
readonly extensions: string readonly extensions: string;
readonly protocol: string readonly protocol: string;
/** The current state of the connection */ /** The current state of the connection */
readonly readyState: readonly readyState: typeof WebSocket.CONNECTING | typeof WebSocket.OPEN | typeof WebSocket.CLOSING | typeof WebSocket.CLOSED;
| typeof WebSocket.CONNECTING readonly url: string;
| typeof WebSocket.OPEN
| typeof WebSocket.CLOSING
| typeof WebSocket.CLOSED
readonly url: string
/** The connection is not yet open. */ /** The connection is not yet open. */
readonly CONNECTING: 0 readonly CONNECTING: 0;
/** The connection is open and ready to communicate. */ /** The connection is open and ready to communicate. */
readonly OPEN: 1 readonly OPEN: 1;
/** The connection is in the process of closing. */ /** The connection is in the process of closing. */
readonly CLOSING: 2 readonly CLOSING: 2;
/** The connection is closed. */ /** The connection is closed. */
readonly CLOSED: 3 readonly CLOSED: 3;
onopen: (event: WebSocket.OpenEvent) => void onopen: (event: WebSocket.OpenEvent) => void;
onerror: (event: WebSocket.ErrorEvent) => void onerror: (event: WebSocket.ErrorEvent) => void;
onclose: (event: WebSocket.CloseEvent) => void onclose: (event: WebSocket.CloseEvent) => void;
onmessage: (event: WebSocket.MessageEvent) => void onmessage: (event: WebSocket.MessageEvent) => void;
constructor( constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
address: string | URL, constructor(address: string | URL, protocols?: string | string[], options?: WebSocket.ClientOptions | ClientRequestArgs);
options?: WebSocket.ClientOptions | ClientRequestArgs
)
constructor(
address: string | URL,
protocols?: string | string[],
options?: WebSocket.ClientOptions | ClientRequestArgs
)
close(code?: number, data?: string): void close(code?: number, data?: string): void;
ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void ping(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void pong(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
send(data: any, cb?: (err?: Error) => void): void send(data: any, cb?: (err?: Error) => void): void;
send( send(
data: any, data: any,
options: { options: {
mask?: boolean | undefined mask?: boolean | undefined;
binary?: boolean | undefined binary?: boolean | undefined;
compress?: boolean | undefined compress?: boolean | undefined;
fin?: boolean | undefined fin?: boolean | undefined;
}, },
cb?: (err?: Error) => void cb?: (err?: Error) => void
): void ): void;
terminate(): void terminate(): void;
// HTML5 WebSocket events // HTML5 WebSocket events
addEventListener( addEventListener(method: 'message', cb: (event: { data: any; type: string; target: WebSocket }) => void, options?: WebSocket.EventListenerOptions): void;
method: 'message', addEventListener(method: 'close', cb: (event: { wasClean: boolean; code: number; reason: string; target: WebSocket }) => void, options?: WebSocket.EventListenerOptions): void;
cb: (event: { data: any; type: string; target: WebSocket }) => void, addEventListener(method: 'error', cb: (event: { error: any; message: any; type: string; target: WebSocket }) => void, options?: WebSocket.EventListenerOptions): void;
options?: WebSocket.EventListenerOptions addEventListener(method: 'open', cb: (event: { target: WebSocket }) => void, options?: WebSocket.EventListenerOptions): void;
): void addEventListener(method: string, listener: () => void, options?: WebSocket.EventListenerOptions): void;
addEventListener(
method: 'close',
cb: (event: {
wasClean: boolean
code: number
reason: string
target: WebSocket
}) => void,
options?: WebSocket.EventListenerOptions
): void
addEventListener(
method: 'error',
cb: (event: {
error: any
message: any
type: string
target: WebSocket
}) => void,
options?: WebSocket.EventListenerOptions
): void
addEventListener(
method: 'open',
cb: (event: { target: WebSocket }) => void,
options?: WebSocket.EventListenerOptions
): void
addEventListener(
method: string,
listener: () => void,
options?: WebSocket.EventListenerOptions
): void
removeEventListener( removeEventListener(method: 'message', cb?: (event: { data: any; type: string; target: WebSocket }) => void): void;
method: 'message', removeEventListener(method: 'close', cb?: (event: { wasClean: boolean; code: number; reason: string; target: WebSocket }) => void): void;
cb?: (event: { data: any; type: string; target: WebSocket }) => void removeEventListener(method: 'error', cb?: (event: { error: any; message: any; type: string; target: WebSocket }) => void): void;
): void removeEventListener(method: 'open', cb?: (event: { target: WebSocket }) => void): void;
removeEventListener( removeEventListener(method: string, listener?: () => void): void;
method: 'close',
cb?: (event: {
wasClean: boolean
code: number
reason: string
target: WebSocket
}) => void
): void
removeEventListener(
method: 'error',
cb?: (event: {
error: any
message: any
type: string
target: WebSocket
}) => void
): void
removeEventListener(
method: 'open',
cb?: (event: { target: WebSocket }) => void
): void
removeEventListener(method: string, listener?: () => void): void
// Events // Events
on( on(event: 'close', listener: (this: WebSocket, code: number, reason: string) => void): this;
event: 'close', on(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
listener: (this: WebSocket, code: number, reason: string) => void on(event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void): this;
): this on(event: 'message', listener: (this: WebSocket, data: WebSocket.Data) => void): this;
on(event: 'error', listener: (this: WebSocket, err: Error) => void): this on(event: 'open', listener: (this: WebSocket) => void): this;
on( on(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
event: 'upgrade', on(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void): this;
listener: (this: WebSocket, request: IncomingMessage) => void on(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
): this
on(
event: 'message',
listener: (this: WebSocket, data: WebSocket.Data) => void
): this
on(event: 'open', listener: (this: WebSocket) => void): this
on(
event: 'ping' | 'pong',
listener: (this: WebSocket, data: Buffer) => void
): this
on(
event: 'unexpected-response',
listener: (
this: WebSocket,
request: ClientRequest,
response: IncomingMessage
) => void
): this
on(
event: string | symbol,
listener: (this: WebSocket, ...args: any[]) => void
): this
once( once(event: 'close', listener: (this: WebSocket, code: number, reason: string) => void): this;
event: 'close', once(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
listener: (this: WebSocket, code: number, reason: string) => void once(event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void): this;
): this once(event: 'message', listener: (this: WebSocket, data: WebSocket.Data) => void): this;
once(event: 'error', listener: (this: WebSocket, err: Error) => void): this once(event: 'open', listener: (this: WebSocket) => void): this;
once( once(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
event: 'upgrade', once(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void): this;
listener: (this: WebSocket, request: IncomingMessage) => void once(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
): this
once(
event: 'message',
listener: (this: WebSocket, data: WebSocket.Data) => void
): this
once(event: 'open', listener: (this: WebSocket) => void): this
once(
event: 'ping' | 'pong',
listener: (this: WebSocket, data: Buffer) => void
): this
once(
event: 'unexpected-response',
listener: (
this: WebSocket,
request: ClientRequest,
response: IncomingMessage
) => void
): this
once(
event: string | symbol,
listener: (this: WebSocket, ...args: any[]) => void
): this
off( off(event: 'close', listener: (this: WebSocket, code: number, reason: string) => void): this;
event: 'close', off(event: 'error', listener: (this: WebSocket, err: Error) => void): this;
listener: (this: WebSocket, code: number, reason: string) => void off(event: 'upgrade', listener: (this: WebSocket, request: IncomingMessage) => void): this;
): this off(event: 'message', listener: (this: WebSocket, data: WebSocket.Data) => void): this;
off(event: 'error', listener: (this: WebSocket, err: Error) => void): this off(event: 'open', listener: (this: WebSocket) => void): this;
off( off(event: 'ping' | 'pong', listener: (this: WebSocket, data: Buffer) => void): this;
event: 'upgrade', off(event: 'unexpected-response', listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void): this;
listener: (this: WebSocket, request: IncomingMessage) => void off(event: string | symbol, listener: (this: WebSocket, ...args: any[]) => void): this;
): this
off(
event: 'message',
listener: (this: WebSocket, data: WebSocket.Data) => void
): this
off(event: 'open', listener: (this: WebSocket) => void): this
off(
event: 'ping' | 'pong',
listener: (this: WebSocket, data: Buffer) => void
): this
off(
event: 'unexpected-response',
listener: (
this: WebSocket,
request: ClientRequest,
response: IncomingMessage
) => void
): this
off(
event: string | symbol,
listener: (this: WebSocket, ...args: any[]) => void
): this
addListener( addListener(event: 'close', listener: (code: number, message: string) => void): this;
event: 'close', addListener(event: 'error', listener: (err: Error) => void): this;
listener: (code: number, message: string) => void addListener(event: 'upgrade', listener: (request: IncomingMessage) => void): this;
): this addListener(event: 'message', listener: (data: WebSocket.Data) => void): this;
addListener(event: 'error', listener: (err: Error) => void): this addListener(event: 'open', listener: () => void): this;
addListener( addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
event: 'upgrade', addListener(event: 'unexpected-response', listener: (request: ClientRequest, response: IncomingMessage) => void): this;
listener: (request: IncomingMessage) => void addListener(event: string | symbol, listener: (...args: any[]) => void): this;
): this
addListener(
event: 'message',
listener: (data: WebSocket.Data) => void
): this
addListener(event: 'open', listener: () => void): this
addListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this
addListener(
event: 'unexpected-response',
listener: (request: ClientRequest, response: IncomingMessage) => void
): this
addListener(
event: string | symbol,
listener: (...args: any[]) => void
): this
removeListener( removeListener(event: 'close', listener: (code: number, message: string) => void): this;
event: 'close', removeListener(event: 'error', listener: (err: Error) => void): this;
listener: (code: number, message: string) => void removeListener(event: 'upgrade', listener: (request: IncomingMessage) => void): this;
): this removeListener(event: 'message', listener: (data: WebSocket.Data) => void): this;
removeListener(event: 'error', listener: (err: Error) => void): this removeListener(event: 'open', listener: () => void): this;
removeListener( removeListener(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
event: 'upgrade', removeListener(event: 'unexpected-response', listener: (request: ClientRequest, response: IncomingMessage) => void): this;
listener: (request: IncomingMessage) => void removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
): this
removeListener(
event: 'message',
listener: (data: WebSocket.Data) => void
): this
removeListener(event: 'open', listener: () => void): this
removeListener(
event: 'ping' | 'pong',
listener: (data: Buffer) => void
): this
removeListener(
event: 'unexpected-response',
listener: (request: ClientRequest, response: IncomingMessage) => void
): this
removeListener(
event: string | symbol,
listener: (...args: any[]) => void
): this
} }
/** /**
* Data represents the message payload received over the WebSocket. * Data represents the message payload received over the WebSocket.
*/ */
type Data = string | Buffer | ArrayBuffer | Buffer[] type Data = string | Buffer | ArrayBuffer | Buffer[];
/** /**
* CertMeta represents the accepted types for certificate & key data. * CertMeta represents the accepted types for certificate & key data.
*/ */
type CertMeta = string | string[] | Buffer | Buffer[] type CertMeta = string | string[] | Buffer | Buffer[];
/** /**
* VerifyClientCallbackSync is a synchronous callback used to inspect the * VerifyClientCallbackSync is a synchronous callback used to inspect the
* incoming message. The return value (boolean) of the function determines * incoming message. The return value (boolean) of the function determines
* whether or not to accept the handshake. * whether or not to accept the handshake.
*/ */
type VerifyClientCallbackSync = (info: { type VerifyClientCallbackSync = (info: { origin: string; secure: boolean; req: IncomingMessage }) => boolean;
origin: string
secure: boolean
req: IncomingMessage
}) => boolean
/** /**
* VerifyClientCallbackAsync is an asynchronous callback used to inspect the * VerifyClientCallbackAsync is an asynchronous callback used to inspect the
@ -333,200 +160,145 @@ export declare namespace WebSocket {
*/ */
type VerifyClientCallbackAsync = ( type VerifyClientCallbackAsync = (
info: { origin: string; secure: boolean; req: IncomingMessage }, info: { origin: string; secure: boolean; req: IncomingMessage },
callback: ( callback: (res: boolean, code?: number, message?: string, headers?: OutgoingHttpHeaders) => void
res: boolean, ) => void;
code?: number,
message?: string,
headers?: OutgoingHttpHeaders
) => void
) => void
interface ClientOptions extends SecureContextOptions { interface ClientOptions extends SecureContextOptions {
protocol?: string | undefined protocol?: string | undefined;
followRedirects?: boolean | undefined followRedirects?: boolean | undefined;
handshakeTimeout?: number | undefined handshakeTimeout?: number | undefined;
maxRedirects?: number | undefined maxRedirects?: number | undefined;
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
localAddress?: string | undefined localAddress?: string | undefined;
protocolVersion?: number | undefined protocolVersion?: number | undefined;
headers?: { [key: string]: string } | undefined headers?: { [key: string]: string } | undefined;
origin?: string | undefined origin?: string | undefined;
agent?: Agent | undefined agent?: Agent | undefined;
host?: string | undefined host?: string | undefined;
family?: number | undefined family?: number | undefined;
checkServerIdentity?(servername: string, cert: CertMeta): boolean checkServerIdentity?(servername: string, cert: CertMeta): boolean;
rejectUnauthorized?: boolean | undefined rejectUnauthorized?: boolean | undefined;
maxPayload?: number | undefined maxPayload?: number | undefined;
} }
interface PerMessageDeflateOptions { interface PerMessageDeflateOptions {
serverNoContextTakeover?: boolean | undefined serverNoContextTakeover?: boolean | undefined;
clientNoContextTakeover?: boolean | undefined clientNoContextTakeover?: boolean | undefined;
serverMaxWindowBits?: number | undefined serverMaxWindowBits?: number | undefined;
clientMaxWindowBits?: number | undefined clientMaxWindowBits?: number | undefined;
zlibDeflateOptions?: zlibDeflateOptions?:
| { | {
flush?: number | undefined flush?: number | undefined;
finishFlush?: number | undefined finishFlush?: number | undefined;
chunkSize?: number | undefined chunkSize?: number | undefined;
windowBits?: number | undefined windowBits?: number | undefined;
level?: number | undefined level?: number | undefined;
memLevel?: number | undefined memLevel?: number | undefined;
strategy?: number | undefined strategy?: number | undefined;
dictionary?: Buffer | Buffer[] | DataView | undefined dictionary?: Buffer | Buffer[] | DataView | undefined;
info?: boolean | undefined info?: boolean | undefined;
} }
| undefined | undefined;
zlibInflateOptions?: ZlibOptions | undefined zlibInflateOptions?: ZlibOptions | undefined;
threshold?: number | undefined threshold?: number | undefined;
concurrencyLimit?: number | undefined concurrencyLimit?: number | undefined;
} }
interface OpenEvent { interface OpenEvent {
type: string type: string;
target: WebSocket target: WebSocket;
} }
interface ErrorEvent { interface ErrorEvent {
error: any error: any;
message: string message: string;
type: string type: string;
target: WebSocket target: WebSocket;
} }
interface CloseEvent { interface CloseEvent {
wasClean: boolean wasClean: boolean;
code: number code: number;
reason: string reason: string;
type: string type: string;
target: WebSocket target: WebSocket;
} }
interface MessageEvent { interface MessageEvent {
data: Data data: Data;
type: string type: string;
target: WebSocket target: WebSocket;
} }
interface EventListenerOptions { interface EventListenerOptions {
once?: boolean | undefined once?: boolean | undefined;
} }
interface ServerOptions { interface ServerOptions {
host?: string | undefined host?: string | undefined;
port?: number | undefined port?: number | undefined;
backlog?: number | undefined backlog?: number | undefined;
server?: HTTPServer | HTTPSServer | undefined server?: HTTPServer | HTTPSServer | undefined;
verifyClient?: verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync | undefined;
| VerifyClientCallbackAsync handleProtocols?: any;
| VerifyClientCallbackSync path?: string | undefined;
| undefined noServer?: boolean | undefined;
handleProtocols?: any clientTracking?: boolean | undefined;
path?: string | undefined perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
noServer?: boolean | undefined maxPayload?: number | undefined;
clientTracking?: boolean | undefined
perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined
maxPayload?: number | undefined
} }
interface AddressInfo { interface AddressInfo {
address: string address: string;
family: string family: string;
port: number port: number;
} }
// WebSocket Server // WebSocket Server
export class Server extends EventEmitter { export class Server extends EventEmitter {
options: ServerOptions options: ServerOptions;
path: string path: string;
clients: Set<WebSocket> clients: Set<WebSocket>;
constructor(options?: ServerOptions, callback?: () => void) constructor(options?: ServerOptions, callback?: () => void);
address(): AddressInfo | string address(): AddressInfo | string;
close(cb?: (err?: Error) => void): void close(cb?: (err?: Error) => void): void;
handleUpgrade( handleUpgrade(request: IncomingMessage, socket: Socket, upgradeHead: Buffer, callback: (client: WebSocket, request: IncomingMessage) => void): void;
request: IncomingMessage, shouldHandle(request: IncomingMessage): boolean | Promise<boolean>;
socket: Socket,
upgradeHead: Buffer,
callback: (client: WebSocket, request: IncomingMessage) => void
): void
shouldHandle(request: IncomingMessage): boolean | Promise<boolean>
// Events // Events
on( on(event: 'connection', cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void): this;
event: 'connection', on(event: 'error', cb: (this: Server, error: Error) => void): this;
cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void on(event: 'headers', cb: (this: Server, headers: string[], request: IncomingMessage) => void): this;
): this on(event: 'close' | 'listening', cb: (this: Server) => void): this;
on(event: 'error', cb: (this: Server, error: Error) => void): this on(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this;
on(
event: 'headers',
cb: (this: Server, headers: string[], request: IncomingMessage) => void
): this
on(event: 'close' | 'listening', cb: (this: Server) => void): this
on(
event: string | symbol,
listener: (this: Server, ...args: any[]) => void
): this
once( once(event: 'connection', cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void): this;
event: 'connection', once(event: 'error', cb: (this: Server, error: Error) => void): this;
cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void once(event: 'headers', cb: (this: Server, headers: string[], request: IncomingMessage) => void): this;
): this once(event: 'close' | 'listening', cb: (this: Server) => void): this;
once(event: 'error', cb: (this: Server, error: Error) => void): this once(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: 'headers',
cb: (this: Server, headers: string[], request: IncomingMessage) => void
): this
once(event: 'close' | 'listening', cb: (this: Server) => void): this
once(event: string | symbol, listener: (...args: any[]) => void): this
off( off(event: 'connection', cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void): this;
event: 'connection', off(event: 'error', cb: (this: Server, error: Error) => void): this;
cb: (this: Server, socket: WebSocket, request: IncomingMessage) => void off(event: 'headers', cb: (this: Server, headers: string[], request: IncomingMessage) => void): this;
): this off(event: 'close' | 'listening', cb: (this: Server) => void): this;
off(event: 'error', cb: (this: Server, error: Error) => void): this off(event: string | symbol, listener: (this: Server, ...args: any[]) => void): this;
off(
event: 'headers',
cb: (this: Server, headers: string[], request: IncomingMessage) => void
): this
off(event: 'close' | 'listening', cb: (this: Server) => void): this
off(
event: string | symbol,
listener: (this: Server, ...args: any[]) => void
): this
addListener( addListener(event: 'connection', cb: (client: WebSocket, request: IncomingMessage) => void): this;
event: 'connection', addListener(event: 'error', cb: (err: Error) => void): this;
cb: (client: WebSocket, request: IncomingMessage) => void addListener(event: 'headers', cb: (headers: string[], request: IncomingMessage) => void): this;
): this addListener(event: 'close' | 'listening', cb: () => void): this;
addListener(event: 'error', cb: (err: Error) => void): this addListener(event: string | symbol, listener: (...args: any[]) => void): this;
addListener(
event: 'headers',
cb: (headers: string[], request: IncomingMessage) => void
): this
addListener(event: 'close' | 'listening', cb: () => void): this
addListener(
event: string | symbol,
listener: (...args: any[]) => void
): this
removeListener(event: 'connection', cb: (client: WebSocket) => void): this removeListener(event: 'connection', cb: (client: WebSocket) => void): this;
removeListener(event: 'error', cb: (err: Error) => void): this removeListener(event: 'error', cb: (err: Error) => void): this;
removeListener( removeListener(event: 'headers', cb: (headers: string[], request: IncomingMessage) => void): this;
event: 'headers', removeListener(event: 'close' | 'listening', cb: () => void): this;
cb: (headers: string[], request: IncomingMessage) => void removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
): this
removeListener(event: 'close' | 'listening', cb: () => void): this
removeListener(
event: string | symbol,
listener: (...args: any[]) => void
): this
} }
// WebSocket stream // WebSocket stream
function createWebSocketStream( function createWebSocketStream(websocket: WebSocket, options?: DuplexOptions): Duplex;
websocket: WebSocket,
options?: DuplexOptions
): Duplex
} }

View file

@ -32,17 +32,17 @@ export const DEFAULT_REMARK_PLUGINS = [
'remark-footnotes', 'remark-footnotes',
// TODO: reenable smartypants! // TODO: reenable smartypants!
// '@silvenon/remark-smartypants' // '@silvenon/remark-smartypants'
] ];
export const DEFAULT_REHYPE_PLUGINS = [ export const DEFAULT_REHYPE_PLUGINS = [
// empty // empty
] ];
/** Shared utility for rendering markdown */ /** Shared utility for rendering markdown */
export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) { export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) {
const { remarkPlugins = DEFAULT_REMARK_PLUGINS, rehypePlugins = DEFAULT_REHYPE_PLUGINS } = opts ?? {}; const { remarkPlugins = DEFAULT_REMARK_PLUGINS, rehypePlugins = DEFAULT_REHYPE_PLUGINS } = opts ?? {};
const scopedClassName = opts?.$?.scopedClassName; const scopedClassName = opts?.$?.scopedClassName;
const mode = opts?.mode ?? "mdx"; const mode = opts?.mode ?? 'mdx';
const isMDX = mode === 'mdx'; const isMDX = mode === 'mdx';
const { headers, rehypeCollectHeaders } = createCollectHeaders(); const { headers, rehypeCollectHeaders } = createCollectHeaders();
@ -52,7 +52,7 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
.use(markdown) .use(markdown)
.use(isMDX ? [remarkJsx] : []) .use(isMDX ? [remarkJsx] : [])
.use(isMDX ? [remarkExpressions] : []) .use(isMDX ? [remarkExpressions] : [])
.use([remarkUnwrap]) .use([remarkUnwrap]);
const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins)); const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins)); const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
@ -62,28 +62,25 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
}); });
if (scopedClassName) { if (scopedClassName) {
parser.use([scopedStyles(scopedClassName)]); parser.use([scopedStyles(scopedClassName)]);
} }
parser.use([remarkPrism(scopedClassName)]); parser.use([remarkPrism(scopedClassName)]);
parser.use([[markdownToHtml as any, { allowDangerousHtml: true, passThrough: ['raw', 'mdxTextExpression', 'mdxJsxTextElement', 'mdxJsxFlowElement']}]]); parser.use([[markdownToHtml as any, { allowDangerousHtml: true, passThrough: ['raw', 'mdxTextExpression', 'mdxJsxTextElement', 'mdxJsxFlowElement'] }]]);
loadedRehypePlugins.forEach(([plugin, opts]) => { loadedRehypePlugins.forEach(([plugin, opts]) => {
parser.use([[plugin, opts]]); parser.use([[plugin, opts]]);
}); });
parser parser
.use(isMDX ? [rehypeJsx] : []) .use(isMDX ? [rehypeJsx] : [])
.use(isMDX ? [rehypeExpressions] : []) .use(isMDX ? [rehypeExpressions] : [])
.use(isMDX ? [] : [rehypeRaw]) .use(isMDX ? [] : [rehypeRaw])
.use(rehypeIslands) .use(rehypeIslands);
let result: string; let result: string;
try { try {
const vfile = await parser const vfile = await parser.use([rehypeCollectHeaders]).use(rehypeStringify, { allowDangerousHtml: true }).process(content);
.use([rehypeCollectHeaders])
.use(rehypeStringify, { allowDangerousHtml: true })
.process(content);
result = vfile.toString(); result = vfile.toString();
} catch (err) { } catch (err) {
console.error(err); console.error(err);

View file

@ -1,4 +1,4 @@
import {SKIP, visit} from 'unist-util-visit'; import { SKIP, visit } from 'unist-util-visit';
// This fixes some confusing bugs coming from somewhere inside of our Markdown pipeline. // This fixes some confusing bugs coming from somewhere inside of our Markdown pipeline.
// `unist`/`remark`/`rehype` (not sure) often generate malformed HTML inside of <astro-root> // `unist`/`remark`/`rehype` (not sure) often generate malformed HTML inside of <astro-root>
@ -11,11 +11,11 @@ export default function rehypeIslands(): any {
if (el.tagName == 'astro-root') { if (el.tagName == 'astro-root') {
visit(el, 'text', (child, index, parent) => { visit(el, 'text', (child, index, parent) => {
if (child.type === 'text') { if (child.type === 'text') {
// Sometimes comments can be trapped as text, which causes them to be escaped // Sometimes comments can be trapped as text, which causes them to be escaped
// This casts them back to real HTML comments // This casts them back to real HTML comments
if (parent && child.value.indexOf('<!--') > -1 && index != null) { if (parent && child.value.indexOf('<!--') > -1 && index != null) {
parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim()}); parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim() });
return [SKIP, index] return [SKIP, index];
} }
// For some reason `rehype` likes to inject extra linebreaks, // For some reason `rehype` likes to inject extra linebreaks,
// but React and Vue throw hydration errors when they see these! // but React and Vue throw hydration errors when they see these!
@ -24,7 +24,7 @@ export default function rehypeIslands(): any {
child.value = child.value.replace(/\n+/g, ''); child.value = child.value.replace(/\n+/g, '');
return child; return child;
} }
}) });
} }
}); });
}; };

View file

@ -5,22 +5,22 @@ export default function rehypeJsx(): any {
return function (node: any): any { return function (node: any): any {
return map(node, (child: any) => { return map(node, (child: any) => {
if (child.type === 'element') { if (child.type === 'element') {
return { ...child, tagName: `${child.tagName}` } return { ...child, tagName: `${child.tagName}` };
} }
if (MDX_ELEMENTS.has(child.type)) { if (MDX_ELEMENTS.has(child.type)) {
return { return {
...child, ...child,
type: 'element', type: 'element',
tagName: `${child.name}`, tagName: `${child.name}`,
properties: child.attributes.reduce((acc: any[], entry: any) => { properties: child.attributes.reduce((acc: any[], entry: any) => {
let attr = entry.value; let attr = entry.value;
if (attr && typeof attr === 'object') { if (attr && typeof attr === 'object') {
attr = `{${attr.value}}` attr = `{${attr.value}}`;
} else if (attr === null) { } else if (attr === null) {
attr = `{true}` attr = `{true}`;
} }
return Object.assign(acc, { [entry.name]: attr }); return Object.assign(acc, { [entry.name]: attr });
}, {}) }, {}),
}; };
} }
return child; return child;

View file

@ -4,26 +4,24 @@ import { addAstro } from '@astrojs/prism';
import loadLanguages from 'prismjs/components/index.js'; import loadLanguages from 'prismjs/components/index.js';
const noVisit = new Set(['root', 'html', 'text']); const noVisit = new Set(['root', 'html', 'text']);
const languageMap = new Map([ const languageMap = new Map([['ts', 'typescript']]);
['ts', 'typescript']
]);
function runHighlighter(lang: string, code: string) { function runHighlighter(lang: string, code: string) {
let classLanguage = `language-${lang}` let classLanguage = `language-${lang}`;
if (lang == null) { if (lang == null) {
lang = 'plaintext'; lang = 'plaintext';
} }
const ensureLoaded = (lang: string) => { const ensureLoaded = (lang: string) => {
if(lang && !Prism.languages[lang]) { if (lang && !Prism.languages[lang]) {
loadLanguages([lang]); loadLanguages([lang]);
} }
}; };
if(languageMap.has(lang)) { if (languageMap.has(lang)) {
ensureLoaded(languageMap.get(lang)!); ensureLoaded(languageMap.get(lang)!);
} else if(lang === 'astro') { } else if (lang === 'astro') {
ensureLoaded('typescript'); ensureLoaded('typescript');
addAstro(Prism); addAstro(Prism);
} else { } else {
@ -31,7 +29,7 @@ function runHighlighter(lang: string, code: string) {
ensureLoaded(lang); ensureLoaded(lang);
} }
if(lang && !Prism.languages[lang]) { if (lang && !Prism.languages[lang]) {
console.warn(`Unable to load the language: ${lang}`); console.warn(`Unable to load the language: ${lang}`);
} }
@ -48,26 +46,25 @@ type MaybeString = string | null | undefined;
/** */ /** */
function transformer(className: MaybeString) { function transformer(className: MaybeString) {
return function(tree: any) { return function (tree: any) {
const visitor = (node: any) => { const visitor = (node: any) => {
let {lang, value} = node; let { lang, value } = node;
node.type = 'html'; node.type = 'html';
let { html, classLanguage } = runHighlighter(lang, value); let { html, classLanguage } = runHighlighter(lang, value);
let classes = [classLanguage]; let classes = [classLanguage];
if(className) { if (className) {
classes.push(className); classes.push(className);
} }
node.value = `<pre class="${classes.join(' ')}"><code data-astro-raw class="${classLanguage}">${html}</code></pre>`; node.value = `<pre class="${classes.join(' ')}"><code data-astro-raw class="${classLanguage}">${html}</code></pre>`;
return node; return node;
}; };
return visit(tree, 'code', visitor) return visit(tree, 'code', visitor);
} };
} }
function plugin(className: MaybeString) { function plugin(className: MaybeString) {
return transformer.bind(null, className); return transformer.bind(null, className);
} }
export default plugin; export default plugin;

View file

@ -3,11 +3,11 @@
* @typedef {import('hast').Properties} Properties * @typedef {import('hast').Properties} Properties
*/ */
import {toString} from 'mdast-util-to-string' import { toString } from 'mdast-util-to-string';
import {visit} from 'unist-util-visit' import { visit } from 'unist-util-visit';
import BananaSlug from 'github-slugger' import BananaSlug from 'github-slugger';
const slugs = new BananaSlug() const slugs = new BananaSlug();
/** /**
* Plugin to add anchors headings using GitHubs algorithm. * Plugin to add anchors headings using GitHubs algorithm.
@ -16,19 +16,17 @@ const slugs = new BananaSlug()
*/ */
export default function remarkSlug() { export default function remarkSlug() {
return (tree: any) => { return (tree: any) => {
slugs.reset() slugs.reset();
visit(tree, (node) => { visit(tree, (node) => {
console.log(node); console.log(node);
}); });
visit(tree, 'heading', (node) => { visit(tree, 'heading', (node) => {
const data = node.data || (node.data = {}) const data = node.data || (node.data = {});
const props = /** @type {Properties} */ ( const props = /** @type {Properties} */ data.hProperties || (data.hProperties = {});
data.hProperties || (data.hProperties = {}) let id = props.id;
) id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node));
let id = props.id
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node))
data.id = id; data.id = id;
props.id = id; props.id = id;
}) });
} };
} }

View file

@ -1,4 +1,4 @@
import {visit, SKIP} from 'unist-util-visit' import { visit, SKIP } from 'unist-util-visit';
// Remove the wrapping paragraph for <astro-root> islands // Remove the wrapping paragraph for <astro-root> islands
export default function remarkUnwrap() { export default function remarkUnwrap() {
@ -18,21 +18,17 @@ export default function remarkUnwrap() {
insideAstroRoot = false; insideAstroRoot = false;
} }
astroRootNodes.add(node); astroRootNodes.add(node);
}) });
visit(tree, 'paragraph', (node, index, parent) => { visit(tree, 'paragraph', (node, index, parent) => {
if ( if (parent && typeof index === 'number' && containsAstroRootNode(node)) {
parent && parent.children.splice(index, 1, ...node.children);
typeof index === 'number' && return [SKIP, index];
containsAstroRootNode(node)
) {
parent.children.splice(index, 1, ...node.children)
return [SKIP, index]
} }
}) });
} };
function containsAstroRootNode(node: any) { function containsAstroRootNode(node: any) {
return node.children.map((child: any) => astroRootNodes.has(child)).reduce((all: boolean, v: boolean) => all ? all : v, false) return node.children.map((child: any) => astroRootNodes.has(child)).reduce((all: boolean, v: boolean) => (all ? all : v), false);
} }
} }

View file

@ -4,7 +4,7 @@ export type UnifiedPluginImport = Promise<{ default: unified.Plugin }>;
export type Plugin = string | [string, any] | UnifiedPluginImport | [UnifiedPluginImport, any]; export type Plugin = string | [string, any] | UnifiedPluginImport | [UnifiedPluginImport, any];
export interface AstroMarkdownOptions { export interface AstroMarkdownOptions {
mode?: 'md'|'mdx'; mode?: 'md' | 'mdx';
remarkPlugins?: Plugin[]; remarkPlugins?: Plugin[];
rehypePlugins?: Plugin[]; rehypePlugins?: Plugin[];
} }

View file

@ -1 +1 @@
import 'lit/experimental-hydrate-support.js'; import 'lit/experimental-hydrate-support.js';

View file

@ -20,7 +20,7 @@ export default {
'@webcomponents/template-shadowroot/template-shadowroot.js', '@webcomponents/template-shadowroot/template-shadowroot.js',
'lit/experimental-hydrate-support.js', 'lit/experimental-hydrate-support.js',
], ],
exclude: ['@astrojs/renderer-lit/server.js'] exclude: ['@astrojs/renderer-lit/server.js'],
}, },
ssr: { ssr: {
external: [ external: [

View file

@ -15,7 +15,7 @@ export default {
return { return {
alias: { alias: {
react: 'preact/compat', react: 'preact/compat',
'react-dom': 'preact/compat' 'react-dom': 'preact/compat',
}, },
resolve: { resolve: {
dedupe: ['react', 'react-dom'], dedupe: ['react', 'react-dom'],