[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!
Do variables work {frontmatter.value * 2}?
Do variables work {frontmatter.value \* 2}?

View file

@ -1,6 +1,6 @@
import { KNOWN_LANGUAGES } from './config';
export { KNOWN_LANGUAGES }
export { KNOWN_LANGUAGES };
export const KNOWN_LANGUAGE_CODES = Object.values(KNOWN_LANGUAGES);
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} */ ({
// Enable Custom Markdown options, plugins, etc.
markdownOptions: {
render: [astroRemark, {
remarkPlugins: ['remark-code-titles', 'remark-slug'],
rehypePlugins: [
['rehype-autolink-headings', { behavior: 'prepend' }],
['rehype-toc', { headings: ['h2', 'h3'] }],
['rehype-add-classes', { 'h1,h2,h3': 'title' }],
]
}]
render: [
astroRemark,
{
remarkPlugins: ['remark-code-titles', 'remark-slug'],
rehypePlugins: [
['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) {
const resolved = resolve.sync(dep, {
basedir: fileURLToPath(astroConfig.projectRoot)
basedir: fileURLToPath(astroConfig.projectRoot),
});
// For Windows compat, we need a fully resolved `file://` URL string
return pathToFileURL(resolved).toString();

View file

@ -1,2 +1,2 @@
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 props = JSON.stringify(item.props);
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) {
const template = await renderToString(result, Component, props, children);
const styles = Array.from(result.styles).filter(uniqueElements).map((style) => renderElement('style', style));
const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => renderElement('script', script));
const styles = Array.from(result.styles)
.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>');
}

View file

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

View file

@ -11,7 +11,7 @@ interface AstroPluginOptions {
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']);
export default function astro({ config, devServer }: AstroPluginOptions): Plugin {

View file

@ -94,4 +94,4 @@ describe('Astro basics', () => {
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 () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html)
expect($('script').length).to.eq(2)
const $ = cheerio.load(html);
expect($('script').length).to.eq(2);
});
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 markdownRemark from '@astrojs/markdown-remark';
describe('Astro Markdown plugins', () => {
let fixture;
@ -12,13 +11,16 @@ describe('Astro Markdown plugins', () => {
projectRoot: './fixtures/astro-markdown-plugins/',
renderers: ['@astrojs/renderer-preact'],
markdownOptions: {
render: [markdownRemark, {
remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]],
rehypePlugins: [
['rehype-toc', { headings: ['h2', 'h3'] }],
['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
}],
render: [
markdownRemark,
{
remarkPlugins: ['remark-code-titles', 'remark-slug', ['rehype-autolink-headings', { behavior: 'prepend' }]],
rehypePlugins: [
['rehype-toc', { headings: ['h2', 'h3'] }],
['rehype-add-classes', { 'h1,h2,h3': 'title' }],
],
},
],
},
buildOptions: {
sitemap: false,
@ -48,4 +50,4 @@ describe('Astro Markdown plugins', () => {
// teste 2: Added .title to h1
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
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
expect($('pre').hasClass('language-js')).to.equal(true);
@ -117,7 +117,7 @@ describe('Astro Markdown', () => {
expect($('code:nth-child(2)').text()).to.equal('{...props}');
// 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 () => {
@ -140,4 +140,4 @@ describe('Astro Markdown', () => {
// test Markdown rendered correctly via content prop
expect($('h1').text()).to.equal('Foo');
});
});
});

View file

@ -24,7 +24,7 @@ describe('Sitemaps', () => {
);
});
});
describe('Sitemap Generation', () => {
it('Generates Sitemap correctly', async () => {
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
}
});
});
});

View file

@ -4,7 +4,7 @@ import { devCLI, loadFixture } from './test-utils.js';
describe('config', () => {
let hostnameFixture;
let portFixture;
before(async () => {
[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" />
// CSS modules
type CSSModuleClasses = { readonly [key: string]: string }
type CSSModuleClasses = { readonly [key: string]: string };
declare module '*.module.css' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.scss' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.sass' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.less' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.styl' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.stylus' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
declare module '*.module.pcss' {
const classes: CSSModuleClasses
export default classes
const classes: CSSModuleClasses;
export default classes;
}
// CSS
declare module '*.css' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.scss' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.sass' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.less' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.styl' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.stylus' {
const css: string
export default css
const css: string;
export default css;
}
declare module '*.pcss' {
const css: string
export default css
const css: string;
export default css;
}
// Built-in asset types
@ -68,137 +68,137 @@ declare module '*.pcss' {
// images
declare module '*.jpg' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.jpeg' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.png' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.gif' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.svg' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.ico' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.webp' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.avif' {
const src: string
export default src
const src: string;
export default src;
}
// media
declare module '*.mp4' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.webm' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.ogg' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.mp3' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.wav' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.flac' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.aac' {
const src: string
export default src
const src: string;
export default src;
}
// fonts
declare module '*.woff' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.woff2' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.eot' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.ttf' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.otf' {
const src: string
export default src
const src: string;
export default src;
}
// other
declare module '*.wasm' {
const initWasm: (options: WebAssembly.Imports) => Promise<WebAssembly.Exports>
export default initWasm
const initWasm: (options: WebAssembly.Imports) => Promise<WebAssembly.Exports>;
export default initWasm;
}
declare module '*.webmanifest' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*.pdf' {
const src: string
export default src
const src: string;
export default src;
}
// web worker
declare module '*?worker' {
const workerConstructor: {
new (): Worker
}
export default workerConstructor
new (): Worker;
};
export default workerConstructor;
}
declare module '*?worker&inline' {
const workerConstructor: {
new (): Worker
}
export default workerConstructor
new (): Worker;
};
export default workerConstructor;
}
declare module '*?sharedworker' {
const sharedWorkerConstructor: {
new (): SharedWorker
}
export default sharedWorkerConstructor
new (): SharedWorker;
};
export default sharedWorkerConstructor;
}
declare module '*?raw' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*?url' {
const src: string
export default src
const src: string;
export default src;
}
declare module '*?inline' {
const src: string
export default src
const src: string;
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.
*/
import { PluginHooks } from 'rollup'
import { PluginHooks } from 'rollup';
export interface Alias {
find: string | RegExp
replacement: string
find: string | RegExp;
replacement: string;
/**
* Instructs the plugin to use an alternative resolving algorithm,
* rather than the Rollup's resolver.
* @default null
*/
customResolver?: ResolverFunction | ResolverObject | null
customResolver?: ResolverFunction | ResolverObject | null;
}
export type ResolverFunction = PluginHooks['resolveId']
export type ResolverFunction = PluginHooks['resolveId'];
export interface ResolverObject {
buildStart?: PluginHooks['buildStart']
resolveId: ResolverFunction
buildStart?: PluginHooks['buildStart'];
resolveId: ResolverFunction;
}
/**
@ -56,4 +56,4 @@ export interface ResolverObject {
* This is passed to \@rollup/plugin-alias as the "entries" field
* 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 AnymatchPattern = string | RegExp | AnymatchFn
type AnymatchMatcher = AnymatchPattern | AnymatchPattern[]
export type AnymatchFn = (testString: string) => boolean;
export type AnymatchPattern = string | RegExp | AnymatchFn;
type AnymatchMatcher = AnymatchPattern | AnymatchPattern[];
export { AnymatchMatcher as Matcher }
export { AnymatchMatcher as Matcher };

View file

@ -28,28 +28,28 @@ THE SOFTWARE.
*/
/// <reference types="node" />
import * as fs from 'fs'
import { Matcher } from './anymatch'
import * as fs from 'fs';
import { Matcher } from './anymatch';
export interface FSWatcher extends fs.FSWatcher {
options: WatchOptions
options: WatchOptions;
/**
* 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
* 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
* 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
@ -58,49 +58,36 @@ export interface FSWatcher extends fs.FSWatcher {
* each directory.
*/
getWatched(): {
[directory: string]: string[]
}
[directory: string]: string[];
};
/**
* Removes all listeners from watched files.
*/
close(): Promise<void>
close(): Promise<void>;
on(
event: 'add' | 'addDir' | 'change',
listener: (path: string, stats?: fs.Stats) => void
): this
on(event: 'add' | 'addDir' | 'change', listener: (path: string, stats?: fs.Stats) => void): this;
on(
event: 'all',
listener: (
eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',
path: string,
stats?: fs.Stats
) => void
): this
on(event: 'all', listener: (eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', path: string, stats?: fs.Stats) => void): this;
/**
* 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`
*/
on(
event: 'raw',
listener: (eventName: string, path: string, details: any) => void
): this
on(event: 'raw', listener: (eventName: string, path: string, details: any) => void): this;
/**
* 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 {
@ -109,7 +96,7 @@ export interface WatchOptions {
* set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`,
* even if the process continues to run.
*/
persistent?: boolean
persistent?: boolean;
/**
* ([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
* [`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
* 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
* 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
* 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
* 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
@ -151,44 +138,44 @@ export interface WatchOptions {
* watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides
* the `useFsEvents` default.
*/
usePolling?: boolean
usePolling?: boolean;
/**
* 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
* 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
* 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.
*/
alwaysStat?: boolean
alwaysStat?: boolean;
/**
* If set, limits how many levels of subdirectories will be traversed.
*/
depth?: number
depth?: number;
/**
* Interval of file system polling.
*/
interval?: number
interval?: number;
/**
* 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))
*/
binaryInterval?: number
binaryInterval?: number;
/**
* 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
* silently.
*/
ignorePermissionErrors?: boolean
ignorePermissionErrors?: boolean;
/**
* `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,
* 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:
@ -207,12 +194,12 @@ export interface WatchOptions {
/**
* Amount of time in milliseconds for a file size to remain constant before emitting its event.
*/
stabilityThreshold?: number
stabilityThreshold?: number;
/**
* File size polling interval.
*/
pollInterval?: number
pollInterval?: number;
}
| boolean
| boolean;
}

View file

@ -15,7 +15,7 @@ export interface RollupCommonJSOptions {
* statements or `transformMixedEsModules` is `true`.
* @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
* 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.
* @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
* order specified. Note that you need to make sure that non-JavaScript files
* are transpiled by another plugin first.
* @default [ '.js' ]
*/
extensions?: ReadonlyArray<string>
extensions?: ReadonlyArray<string>;
/**
* If true then uses of `global` won't be dealt with by this plugin
* @default false
*/
ignoreGlobal?: boolean
ignoreGlobal?: boolean;
/**
* If false, skips source map generation for CommonJS modules. This will improve performance.
* @default true
*/
sourceMap?: boolean
sourceMap?: boolean;
/**
* Some `require` calls cannot be resolved statically to be translated to
* imports.
@ -52,7 +52,7 @@ export interface RollupCommonJSOptions {
* code or use it as a fallback for `dynamicRequireTargets`.
* @default false
*/
ignoreDynamicRequires?: boolean
ignoreDynamicRequires?: boolean;
/**
* Instructs the plugin whether to enable mixed module transformations. This
* 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.
* @default false
*/
transformMixedEsModules?: boolean
transformMixedEsModules?: boolean;
/**
* Sometimes you have to leave require statements unconverted. Pass an array
* containing the IDs or a `id => boolean` function.
* @default []
*/
ignore?: ReadonlyArray<string> | ((id: string) => boolean)
ignore?: ReadonlyArray<string> | ((id: string) => boolean);
/**
* Controls how to render imports from external dependencies. By default,
* this plugin assumes that all external dependencies are CommonJS. This
@ -88,7 +88,7 @@ export interface RollupCommonJSOptions {
* module.
* @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.
* 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.
* @default false
*/
requireReturnsDefault?:
| boolean
| 'auto'
| 'preferred'
| 'namespace'
| ((id: string) => boolean | 'auto' | 'preferred' | 'namespace')
requireReturnsDefault?: boolean | 'auto' | 'preferred' | 'namespace' | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace');
/**
* Some modules contain dynamic `require` calls, or require modules that
* 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
* 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
/// <reference types="node" />
import * as http from 'http'
import * as http from 'http';
export namespace Connect {
export type ServerHandle = HandleFunction | http.Server
export type ServerHandle = HandleFunction | http.Server;
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 = (
req: IncomingMessage,
res: http.ServerResponse
) => void
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 type SimpleHandleFunction = (req: IncomingMessage, res: http.ServerResponse) => void;
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 {
route: string
handle: ServerHandle
route: string;
handle: ServerHandle;
}
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
stack: ServerStackItem[]
route: string;
stack: ServerStackItem[];
/**
* 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
* not be invoked for _/_, or _/posts_.
*/
use(fn: NextHandleFunction): Server
use(fn: HandleFunction): Server
use(route: string, fn: NextHandleFunction): Server
use(route: string, fn: HandleFunction): Server
use(fn: NextHandleFunction): Server;
use(fn: HandleFunction): Server;
use(route: string, fn: NextHandleFunction): Server;
use(route: string, fn: HandleFunction): Server;
/**
* Handle server requests, punting them down
* the middleware stack.
*/
handle(
req: http.IncomingMessage,
res: http.ServerResponse,
next: Function
): void
handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void;
/**
* Listen for connections.
@ -98,14 +79,9 @@ export namespace Connect {
* http.createServer(app).listen(80);
* https.createServer(options, app).listen(443);
*/
listen(
port: number,
hostname?: string,
backlog?: number,
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
listen(port: number, hostname?: string, backlog?: number, 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.
export type CustomEventName<T extends string> = (T extends `vite:${T}`
? never
: T) &
(`vite:${T}` extends T ? never : T)
export type CustomEventName<T extends string> = (T extends `vite:${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).
* @default []
*/
include?: string | RegExp | (string | RegExp)[]
include?: string | RegExp | (string | RegExp)[];
/**
* Files to exclude in this plugin (default none).
* @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.
* @default false
*/
warnOnError?: boolean
warnOnError?: boolean;
}

View file

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

View file

@ -13,45 +13,40 @@
/// <reference types="node" />
import * as net from 'net'
import * as http from 'http'
import * as events from 'events'
import * as url from 'url'
import * as stream from 'stream'
import * as net from 'net';
import * as http from 'http';
import * as events from 'events';
import * as url from 'url';
import * as stream from 'stream';
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 {
host: string
port: number
protocol?: string
hostname?: string
socketPath?: string
key?: string
passphrase?: string
pfx?: Buffer | string
cert?: string
ca?: string
ciphers?: string
secureProtocol?: string
host: string;
port: number;
protocol?: string;
hostname?: string;
socketPath?: string;
key?: string;
passphrase?: string;
pfx?: Buffer | string;
cert?: string;
ca?: string;
ciphers?: string;
secureProtocol?: string;
}
export type ErrorCallback = (
err: Error,
req: http.IncomingMessage,
res: http.ServerResponse,
target?: ProxyTargetUrl
) => void
export type ErrorCallback = (err: Error, req: http.IncomingMessage, res: http.ServerResponse, target?: ProxyTargetUrl) => void;
export class Server extends events.EventEmitter {
/**
* Creates the proxy server with specified options.
* @param options - Config object passed to the proxy
*/
constructor(options?: ServerOptions)
constructor(options?: ServerOptions);
/**
* Used for proxying regular HTTP(S) requests
@ -59,12 +54,7 @@ export namespace HttpProxy {
* @param res - Client response.
* @param options - Additionnal options.
*/
web(
req: http.IncomingMessage,
res: http.ServerResponse,
options?: ServerOptions,
callback?: ErrorCallback
): void
web(req: http.IncomingMessage, res: http.ServerResponse, options?: ServerOptions, callback?: ErrorCallback): void;
/**
* Used for proxying regular HTTP(S) requests
@ -73,170 +63,111 @@ export namespace HttpProxy {
* @param head - Client head.
* @param options - Additional options.
*/
ws(
req: http.IncomingMessage,
socket: unknown,
head: unknown,
options?: ServerOptions,
callback?: ErrorCallback
): void
ws(req: http.IncomingMessage, socket: unknown, head: unknown, options?: ServerOptions, callback?: ErrorCallback): void;
/**
* A function that wraps the object in a webserver, for your convenience
* @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
*/
close(callback?: () => void): void
close(callback?: () => void): void;
/**
* Creates the proxy server with specified options.
* @param options - Config object passed to the proxy
* @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.
* @param options - Config object passed to the proxy
* @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.
* @param options - Config object passed to the proxy
* @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
on(event: string, listener: () => void): this
on(event: 'error', listener: ErrorCallback): this
on(
event: 'start',
listener: (
req: http.IncomingMessage,
res: http.ServerResponse,
target: ProxyTargetUrl
) => void
): 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
addListener(event: string, listener: () => void): this;
on(event: string, listener: () => void): this;
on(event: 'error', listener: ErrorCallback): this;
on(event: 'start', listener: (req: http.IncomingMessage, res: http.ServerResponse, target: ProxyTargetUrl) => void): 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
removeListener(event: string, listener: () => void): this
removeAllListeners(event?: string): this
getMaxListeners(): number
setMaxListeners(n: number): this
listeners(event: string): Array<() => void>
emit(event: string, ...args: any[]): boolean
listenerCount(type: string): number
once(event: string, listener: () => void): this;
removeListener(event: string, listener: () => void): this;
removeAllListeners(event?: string): this;
getMaxListeners(): number;
setMaxListeners(n: number): this;
listeners(event: string): Array<() => void>;
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
}
export interface ServerOptions {
/** URL string to be parsed with the url module. */
target?: ProxyTarget
target?: ProxyTarget;
/** URL string to be parsed with the url module. */
forward?: ProxyTargetUrl
forward?: ProxyTargetUrl;
/** Object to be passed to http(s).request. */
agent?: any
agent?: any;
/** Object to be passed to https.createServer(). */
ssl?: any
ssl?: any;
/** If you want to proxy websockets. */
ws?: boolean
ws?: boolean;
/** Adds x- forward headers. */
xfwd?: boolean
xfwd?: boolean;
/** Verify SSL certificate. */
secure?: boolean
secure?: boolean;
/** 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. */
prependPath?: boolean
prependPath?: boolean;
/** 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. */
localAddress?: string
localAddress?: string;
/** 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 */
preserveHeaderKeyCase?: boolean
preserveHeaderKeyCase?: boolean;
/** 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. */
hostRewrite?: string
hostRewrite?: string;
/** 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. */
protocolRewrite?: string
protocolRewrite?: string;
/** 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 */
cookiePathRewrite?: false | string | { [oldPath: string]: string }
cookiePathRewrite?: false | string | { [oldPath: string]: string };
/** 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) */
proxyTimeout?: number
proxyTimeout?: number;
/** Timeout (in milliseconds) for incoming requests */
timeout?: number
timeout?: number;
/** 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 */
selfHandleResponse?: boolean
selfHandleResponse?: boolean;
/** Buffer */
buffer?: stream.Stream
buffer?: stream.Stream;
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -32,17 +32,17 @@ export const DEFAULT_REMARK_PLUGINS = [
'remark-footnotes',
// TODO: reenable smartypants!
// '@silvenon/remark-smartypants'
]
];
export const DEFAULT_REHYPE_PLUGINS = [
// empty
]
];
/** Shared utility for rendering markdown */
export async function renderMarkdown(content: string, opts?: MarkdownRenderingOptions | null) {
const { remarkPlugins = DEFAULT_REMARK_PLUGINS, rehypePlugins = DEFAULT_REHYPE_PLUGINS } = opts ?? {};
const scopedClassName = opts?.$?.scopedClassName;
const mode = opts?.mode ?? "mdx";
const mode = opts?.mode ?? 'mdx';
const isMDX = mode === 'mdx';
const { headers, rehypeCollectHeaders } = createCollectHeaders();
@ -52,7 +52,7 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
.use(markdown)
.use(isMDX ? [remarkJsx] : [])
.use(isMDX ? [remarkExpressions] : [])
.use([remarkUnwrap])
.use([remarkUnwrap]);
const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
@ -62,28 +62,25 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
});
if (scopedClassName) {
parser.use([scopedStyles(scopedClassName)]);
parser.use([scopedStyles(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]) => {
parser.use([[plugin, opts]]);
});
parser
.use(isMDX ? [rehypeJsx] : [])
.use(isMDX ? [rehypeExpressions] : [])
.use(isMDX ? [] : [rehypeRaw])
.use(rehypeIslands)
.use(rehypeIslands);
let result: string;
try {
const vfile = await parser
.use([rehypeCollectHeaders])
.use(rehypeStringify, { allowDangerousHtml: true })
.process(content);
const vfile = await parser.use([rehypeCollectHeaders]).use(rehypeStringify, { allowDangerousHtml: true }).process(content);
result = vfile.toString();
} catch (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.
// `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') {
visit(el, 'text', (child, index, parent) => {
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
if (parent && child.value.indexOf('<!--') > -1 && index != null) {
parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim()});
return [SKIP, index]
parent.children.splice(index, 1, { ...child, type: 'comment', value: child.value.replace('<!--', '').replace('-->', '').trim() });
return [SKIP, index];
}
// For some reason `rehype` likes to inject extra linebreaks,
// 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, '');
return child;
}
})
});
}
});
};

View file

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

View file

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

View file

@ -3,11 +3,11 @@
* @typedef {import('hast').Properties} Properties
*/
import {toString} from 'mdast-util-to-string'
import {visit} from 'unist-util-visit'
import BananaSlug from 'github-slugger'
import { toString } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
import BananaSlug from 'github-slugger';
const slugs = new BananaSlug()
const slugs = new BananaSlug();
/**
* Plugin to add anchors headings using GitHubs algorithm.
@ -16,19 +16,17 @@ const slugs = new BananaSlug()
*/
export default function remarkSlug() {
return (tree: any) => {
slugs.reset()
slugs.reset();
visit(tree, (node) => {
console.log(node);
});
visit(tree, 'heading', (node) => {
const data = node.data || (node.data = {})
const props = /** @type {Properties} */ (
data.hProperties || (data.hProperties = {})
)
let id = props.id
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node))
const data = node.data || (node.data = {});
const props = /** @type {Properties} */ data.hProperties || (data.hProperties = {});
let id = props.id;
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node));
data.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
export default function remarkUnwrap() {
@ -18,21 +18,17 @@ export default function remarkUnwrap() {
insideAstroRoot = false;
}
astroRootNodes.add(node);
})
});
visit(tree, 'paragraph', (node, index, parent) => {
if (
parent &&
typeof index === 'number' &&
containsAstroRootNode(node)
) {
parent.children.splice(index, 1, ...node.children)
return [SKIP, index]
if (parent && typeof index === 'number' && containsAstroRootNode(node)) {
parent.children.splice(index, 1, ...node.children);
return [SKIP, index];
}
})
}
});
};
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 interface AstroMarkdownOptions {
mode?: 'md'|'mdx';
mode?: 'md' | 'mdx';
remarkPlugins?: 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',
'lit/experimental-hydrate-support.js',
],
exclude: ['@astrojs/renderer-lit/server.js']
exclude: ['@astrojs/renderer-lit/server.js'],
},
ssr: {
external: [

View file

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