diff --git a/.eslintignore b/.eslintignore index 3e795e7a98280b..833faed81beb2b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,4 +1,4 @@ dist playground-temp temp - +packages/vite/client/types.d.ts diff --git a/.eslintrc.cjs b/.eslintrc.cjs index e14beca6015d94..2ce0e4fbf59c67 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -131,7 +131,7 @@ module.exports = defineConfig({ } }, { - files: ['packages/vite/types/**', '*.spec.ts'], + files: ['packages/vite/src/dep-types/**', '*.spec.ts'], rules: { 'node/no-extraneous-import': 'off' } diff --git a/.gitignore b/.gitignore index 7f1cab0e1f4356..8aafb6ab143259 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ *.local *.log /.vscode/ +/packages/vite/client/types.d.ts /packages/vite/LICENSE dist dist-ssr diff --git a/.prettierignore b/.prettierignore index b1ea458b9bb9d8..be3598b2ccb5b3 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,3 +9,4 @@ playground/tsconfig-json-load-error/has-error/tsconfig.json playground/html/invalid.html playground/html/valid.html playground/worker/classic-worker.js +packages/vite/client/types.d.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 350f36b0f25351..f2f04ce43f86c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -218,7 +218,7 @@ Avoid deps with large transitive dependencies that result in bloated size compar Vite aims to be fully usable as a dependency in a TypeScript project (e.g. it should provide proper typings for VitePress), and also in `vite.config.ts`. This means technically a dependency whose types are exposed needs to be part of `dependencies` instead of `devDependencies`. However, this also means we won't be able to bundle it. -To get around this, we inline some of these dependencies' types in `packages/vite/types`. This way, we can still expose the typing but bundle the dependency's source code. +To get around this, we inline some of these dependencies' types in `packages/vite/src/dep-types`. This way, we can still expose the typing but bundle the dependency's source code. Use `pnpm run check-dist-types` to check that the bundled types do not rely on types in `devDependencies`. If you are adding `dependencies`, make sure to configure `tsconfig.check.json`. diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index c18c6daca3263f..33d8ba0e9802b7 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -595,12 +595,21 @@ It is possible to type custom events by extending the `CustomEventMap` interface ```ts // events.d.ts -import 'vite/types/customEvent' +import 'vite' +import 'vite/client/types' -declare module 'vite/types/customEvent' { - interface CustomEventMap { - 'custom:foo': { msg: string } - // 'event-key': payload - } +interface MyCustomEventMap { + 'custom:foo': { msg: string } + // 'event-key': payload +} + +// extend interface for server-side +declare module 'vite' { + interface CustomEventMap extends MyCustomEventMap {} +} + +// extend interface for client-side +declare module 'vite/client/types' { + interface CustomEventMap extends MyCustomEventMap {} } ``` diff --git a/packages/plugin-legacy/tsconfig.json b/packages/plugin-legacy/tsconfig.json index ddb60f864b7e6d..bd94458fe2dc28 100644 --- a/packages/plugin-legacy/tsconfig.json +++ b/packages/plugin-legacy/tsconfig.json @@ -12,7 +12,6 @@ "noUnusedLocals": true, "esModuleInterop": true, "paths": { - "types/*": ["../vite/types/*"], "vite": ["../vite/src/node/index.js"] } } diff --git a/packages/plugin-react/tsconfig.json b/packages/plugin-react/tsconfig.json index ddb60f864b7e6d..bd94458fe2dc28 100644 --- a/packages/plugin-react/tsconfig.json +++ b/packages/plugin-react/tsconfig.json @@ -12,7 +12,6 @@ "noUnusedLocals": true, "esModuleInterop": true, "paths": { - "types/*": ["../vite/types/*"], "vite": ["../vite/src/node/index.js"] } } diff --git a/packages/plugin-vue-jsx/tsconfig.json b/packages/plugin-vue-jsx/tsconfig.json index ddb60f864b7e6d..bd94458fe2dc28 100644 --- a/packages/plugin-vue-jsx/tsconfig.json +++ b/packages/plugin-vue-jsx/tsconfig.json @@ -12,7 +12,6 @@ "noUnusedLocals": true, "esModuleInterop": true, "paths": { - "types/*": ["../vite/types/*"], "vite": ["../vite/src/node/index.js"] } } diff --git a/packages/plugin-vue/tsconfig.json b/packages/plugin-vue/tsconfig.json index d3a45a1b69dbd3..4bb9f95e2328ec 100644 --- a/packages/plugin-vue/tsconfig.json +++ b/packages/plugin-vue/tsconfig.json @@ -14,7 +14,6 @@ "esModuleInterop": true, "baseUrl": ".", "paths": { - "types/*": ["../vite/types/*"], "vite": ["../vite/src/node/index.js"] } } diff --git a/packages/vite/api-extractor.client.json b/packages/vite/api-extractor.client.json new file mode 100644 index 00000000000000..81188aa4870d54 --- /dev/null +++ b/packages/vite/api-extractor.client.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + + "projectFolder": "./src/client", + + "mainEntryPointFilePath": "./src/client-types.d.ts", + + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./client/types.d.ts" + }, + + "apiReport": { + "enabled": false + }, + + "docModel": { + "enabled": false + }, + + "tsdocMetadata": { + "enabled": false + }, + + "messages": { + "compilerMessageReporting": { + "default": { + "logLevel": "warning" + } + }, + + "extractorMessageReporting": { + "default": { + "logLevel": "warning", + "addToApiReportFile": true + }, + + "ae-missing-release-tag": { + "logLevel": "none" + } + }, + + "tsdocMessageReporting": { + "default": { + "logLevel": "warning" + }, + + "tsdoc-undefined-tag": { + "logLevel": "none" + } + } + } +} diff --git a/packages/vite/client.d.ts b/packages/vite/client.d.ts index e99b4a526b7a58..5ee6940825b119 100644 --- a/packages/vite/client.d.ts +++ b/packages/vite/client.d.ts @@ -1,4 +1,4 @@ -/// +/// // CSS modules type CSSModuleClasses = { readonly [key: string]: string } diff --git a/packages/vite/import-meta.d.ts b/packages/vite/import-meta.d.ts new file mode 100644 index 00000000000000..73baf3c106c74f --- /dev/null +++ b/packages/vite/import-meta.d.ts @@ -0,0 +1,10 @@ +import type { + ImportMeta as ViteImportMeta, + ImportMetaEnv as ViteImportMetaEnv + // eslint-disable-next-line node/no-missing-import -- use .js for `moduleResolution: "nodenext"` +} from './client/types.js' + +declare global { + interface ImportMeta extends ViteImportMeta {} + interface ImportMetaEnv extends ViteImportMetaEnv {} +} diff --git a/packages/vite/package.json b/packages/vite/package.json index b6462edb16c342..935a1dffa13461 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -20,6 +20,12 @@ "./client": { "types": "./client.d.ts" }, + "./import-meta": { + "types": "./import-meta.d.ts" + }, + "./client/types": { + "types": "./client/types.d.ts" + }, "./dist/client/*": "./dist/client/*", "./package.json": "./package.json" }, @@ -27,9 +33,11 @@ "bin", "dist", "client.d.ts", + "import-meta.d.ts", "index.cjs", "src/client", - "types" + "types", + "client/types.d.ts" ], "engines": { "node": "^14.18.0 || >=16.0.0" @@ -47,11 +55,13 @@ "dev": "rimraf dist && pnpm run build-bundle -w", "build": "rimraf dist && run-s build-bundle build-types", "build-bundle": "rollup --config rollup.config.ts --configPlugin typescript", - "build-types": "run-s build-temp-types patch-types roll-types check-dist-types", - "build-temp-types": "tsc --emitDeclarationOnly --outDir temp/node -p src/node", - "patch-types": "tsx scripts/patchTypes.ts", - "roll-types": "api-extractor run && rimraf temp", - "check-dist-types": "tsc --project tsconfig.check.json", + "build-types": "run-p build-node-types build-client-types", + "build-node-types": "run-s build-node-types-temp build-node-types-patch build-node-types-roll build-node-types-check", + "build-node-types-temp": "tsc --emitDeclarationOnly --outDir temp/node -p src/node", + "build-node-types-patch": "tsx scripts/patchTypes.ts", + "build-node-types-roll": "api-extractor run && rimraf temp", + "build-node-types-check": "tsc --project tsconfig.check.json", + "build-client-types": "api-extractor run -c api-extractor.client.json", "lint": "eslint --cache --ext .ts src/**", "format": "prettier --write --cache --parser typescript \"src/**/*.ts\"", "prepublishOnly": "npm run build" @@ -117,7 +127,8 @@ "strip-literal": "^0.4.2", "tsconfck": "^2.0.1", "tslib": "^2.4.0", - "types": "link:./types", + "dep-types": "link:./src/dep-types", + "types": "link:./src/types", "ufo": "^0.8.5", "ws": "^8.9.0" }, diff --git a/packages/vite/scripts/patchTypes.ts b/packages/vite/scripts/patchTypes.ts index bdd3953b269aba..8d86c9c7b76292 100644 --- a/packages/vite/scripts/patchTypes.ts +++ b/packages/vite/scripts/patchTypes.ts @@ -3,19 +3,20 @@ import { dirname, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import type { ParseResult } from '@babel/parser' import { parse } from '@babel/parser' -import type { File } from '@babel/types' +import type { File, StringLiteral } from '@babel/types' import colors from 'picocolors' import MagicString from 'magic-string' const dir = dirname(fileURLToPath(import.meta.url)) const tempDir = resolve(dir, '../temp/node') -const typesDir = resolve(dir, '../types') +const typesDir = resolve(dir, '../src/types') +const depTypesDir = resolve(dir, '../src/dep-types') -// walk through the temp dts dir, find all import/export of types/* +// walk through the temp dts dir, find all import/export of types/*, deps-types/* // and rewrite them into relative imports - so that api-extractor actually // includes them in the rolled-up final d.ts file. walkDir(tempDir) -console.log(colors.green(colors.bold(`patched types/* imports`))) +console.log(colors.green(colors.bold(`patched types/*, deps-types/* imports`))) function slash(p: string): string { return p.replace(/\\/g, '/') @@ -49,20 +50,34 @@ function rewriteFile(file: string): void { } for (const statement of ast.program.body) { if ( - (statement.type === 'ImportDeclaration' || - statement.type === 'ExportNamedDeclaration' || - statement.type === 'ExportAllDeclaration') && - statement.source?.value.startsWith('types/') + statement.type === 'ImportDeclaration' || + statement.type === 'ExportNamedDeclaration' || + statement.type === 'ExportAllDeclaration' ) { const source = statement.source - const absoluteTypePath = resolve(typesDir, source.value.slice(6)) - const relativeTypePath = slash(relative(dirname(file), absoluteTypePath)) - str.overwrite( - source.start!, - source.end!, - JSON.stringify(relativeTypePath) - ) + if (source?.value.startsWith('types/')) { + rewriteSource(str, source, file, typesDir, 'types') + } else if (source?.value.startsWith('dep-types/')) { + rewriteSource(str, source, file, depTypesDir, 'dep-types') + } } } writeFileSync(file, str.toString()) } + +function rewriteSource( + str: MagicString, + source: StringLiteral, + rewritingFile: string, + typesDir: string, + typesDirName: string +) { + const absoluteTypePath = resolve( + typesDir, + source.value.slice(typesDirName.length + 1) + ) + const relativeTypePath = slash( + relative(dirname(rewritingFile), absoluteTypePath) + ) + str.overwrite(source.start!, source.end!, JSON.stringify(relativeTypePath)) +} diff --git a/packages/vite/src/client-types.d.ts b/packages/vite/src/client-types.d.ts new file mode 100644 index 00000000000000..270a1ac29f2d8b --- /dev/null +++ b/packages/vite/src/client-types.d.ts @@ -0,0 +1,23 @@ +export type { + CustomEventMap, + InferCustomEventPayload +} from './types/customEvent' +export type { + HMRPayload, + ConnectedPayload, + UpdatePayload, + Update, + PrunePayload, + FullReloadPayload, + CustomPayload, + ErrorPayload +} from './types/hmrPayload' +export type { ModuleNamespace, ViteHotContext } from './types/hot' +export type { + ImportGlobOptions, + GeneralImportGlobOptions, + KnownAsTypeMap, + ImportGlobFunction, + ImportGlobEagerFunction +} from './types/importGlob' +export type { ImportMetaEnv, ImportMeta } from './types/importMeta' diff --git a/packages/vite/src/client/tsconfig.json b/packages/vite/src/client/tsconfig.json index 10e3e3fee1d5d7..a7b763fdf2e37c 100644 --- a/packages/vite/src/client/tsconfig.json +++ b/packages/vite/src/client/tsconfig.json @@ -1,6 +1,6 @@ { "extends": "../../tsconfig.base.json", - "include": ["./", "../../types"], + "include": ["./", "../types"], "compilerOptions": { "types": [], "target": "ES2019", diff --git a/packages/vite/src/dep-types/alias.d.ts b/packages/vite/src/dep-types/alias.d.ts new file mode 100644 index 00000000000000..3f4393586f1299 --- /dev/null +++ b/packages/vite/src/dep-types/alias.d.ts @@ -0,0 +1,59 @@ +/** +Types from https://github.com/rollup/plugins/blob/master/packages/alias/types/index.d.ts +Inlined because the plugin is bundled. + +https://github.com/rollup/plugins/blob/master/LICENSE + +The MIT License (MIT) + +Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +import type { PluginHooks } from 'rollup' + +export interface Alias { + 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 +} + +export type ResolverFunction = PluginHooks['resolveId'] + +export interface ResolverObject { + buildStart?: PluginHooks['buildStart'] + resolveId: ResolverFunction +} + +/** + * Specifies an `Object`, or an `Array` of `Object`, + * which defines aliases used to replace values in `import` or `require` statements. + * With either format, the order of the entries is important, + * in that the first defined rules are applied first. + * + * 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 } diff --git a/packages/vite/src/dep-types/anymatch.d.ts b/packages/vite/src/dep-types/anymatch.d.ts new file mode 100644 index 00000000000000..9204588583046d --- /dev/null +++ b/packages/vite/src/dep-types/anymatch.d.ts @@ -0,0 +1,5 @@ +export type AnymatchFn = (testString: string) => boolean +export type AnymatchPattern = string | RegExp | AnymatchFn +type AnymatchMatcher = AnymatchPattern | AnymatchPattern[] + +export { AnymatchMatcher as Matcher } diff --git a/packages/vite/src/dep-types/chokidar.d.ts b/packages/vite/src/dep-types/chokidar.d.ts new file mode 100644 index 00000000000000..0dc4bec1013643 --- /dev/null +++ b/packages/vite/src/dep-types/chokidar.d.ts @@ -0,0 +1,229 @@ +// Inlined to avoid extra dependency (chokidar is bundled in the published build) + +// https://github.com/paulmillr/chokidar/blob/master/types/index.d.ts +// MIT Licensed https://github.com/paulmillr/chokidar/blob/master/LICENSE + +/** +The MIT License (MIT) + +Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +/// + +import type * as fs from 'node:fs' +import { EventEmitter } from 'node:events' +import type { Matcher } from './anymatch' + +export class FSWatcher extends EventEmitter implements fs.FSWatcher { + options: WatchOptions + + /** + * Constructs a new FSWatcher instance with optional WatchOptions parameter. + */ + constructor(options?: WatchOptions) + + /** + * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one + * string. + */ + add(paths: string | ReadonlyArray): this + + /** + * Stop watching files, directories, or glob patterns. Takes an array of strings or just one + * string. + */ + unwatch(paths: string | ReadonlyArray): this + + /** + * Returns an object representing all the paths on the file system being watched by this + * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless + * the `cwd` option was used), and the values are arrays of the names of the items contained in + * each directory. + */ + getWatched(): { + [directory: string]: string[] + } + + /** + * Removes all listeners from watched files. + */ + close(): Promise + + 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 + + /** + * Error occurred + */ + 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 + + /** + * Fires when the initial scan is complete + */ + on(event: 'ready', listener: () => void): this + + on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this + + on(event: string, listener: (...args: any[]) => void): this +} + +export interface WatchOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched. If + * 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 + + /** + * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to + * be ignored. The whole relative or absolute path is tested, not just filename. If a function + * with two arguments is provided, it gets called twice per path - once with a single argument + * (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 + + /** + * 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 + + /** + * 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 + + /** + * The base directory from which watch `paths` are to be derived. Paths emitted with events will + * be relative to this. + */ + 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 + + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU + * utilization, consider setting this to `false`. It is typically necessary to **set this to + * `true` to successfully watch files over a network**, and it may be necessary to successfully + * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides + * the `useFsEvents` default. + */ + usePolling?: boolean + + /** + * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly + * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on + * OS X, `usePolling: true` becomes the default. + */ + 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 + + /** + * If set, limits how many levels of subdirectories will be traversed. + */ + depth?: number + + /** + * Interval of file system polling. + */ + 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 + + /** + * 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 + + /** + * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts + * that occur when using editors that use "atomic writes" instead of writing directly to the + * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` + * 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 + + /** + * can be set to an object in order to adjust timing params: + */ + awaitWriteFinish?: AwaitWriteFinishOptions | boolean +} + +export interface AwaitWriteFinishOptions { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event. + */ + stabilityThreshold?: number + + /** + * File size polling interval. + */ + pollInterval?: number +} + +/** + * produces an instance of `FSWatcher`. + */ +export function watch( + paths: string | ReadonlyArray, + options?: WatchOptions +): FSWatcher diff --git a/packages/vite/src/dep-types/commonjs.d.ts b/packages/vite/src/dep-types/commonjs.d.ts new file mode 100644 index 00000000000000..01948156deb1cd --- /dev/null +++ b/packages/vite/src/dep-types/commonjs.d.ts @@ -0,0 +1,230 @@ +/** + * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts + * + * This source code is licensed under the MIT license found in the + * LICENSE file at + * https://github.com/rollup/plugins/blob/master/LICENSE + */ +export interface RollupCommonJSOptions { + /** + * A minimatch pattern, or array of patterns, which specifies the files in + * the build the plugin should operate on. By default, all files with + * extension `".cjs"` or those in `extensions` are included, but you can + * narrow this list by only including specific files. These files will be + * analyzed and transpiled if either the analysis does not find ES module + * specific statements or `transformMixedEsModules` is `true`. + * @default undefined + */ + 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 + * extensions other than those in `extensions` or `".cjs"` are ignored, but you + * can exclude additional files. See also the `include` option. + * @default undefined + */ + 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 + /** + * If true then uses of `global` won't be dealt with by this plugin + * @default false + */ + ignoreGlobal?: boolean + /** + * If false, skips source map generation for CommonJS modules. This will + * improve performance. + * @default true + */ + sourceMap?: boolean + /** + * Some `require` calls cannot be resolved statically to be translated to + * imports. + * When this option is set to `false`, the generated code will either + * directly throw an error when such a call is encountered or, when + * `dynamicRequireTargets` is used, when such a call cannot be resolved with a + * configured dynamic require target. + * Setting this option to `true` will instead leave the `require` call in the + * code or use it as a fallback for `dynamicRequireTargets`. + * @default false + */ + 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` + * statements and CommonJS `require` expressions. Set to `true` if `require` + * calls should be transformed to imports in mixed modules, or `false` if the + * `require` expressions should survive the transformation. The latter can be + * important if the code contains environment detection, or you are coding + * for an environment with special treatment for `require` calls such as + * ElectronJS. See also the `ignore` option. + * @default false + */ + transformMixedEsModules?: boolean + /** + * By default, this plugin will try to hoist `require` statements as imports + * to the top of each file. While this works well for many code bases and + * allows for very efficient ESM output, it does not perfectly capture + * CommonJS semantics as the order of side effects like log statements may + * change. But it is especially problematic when there are circular `require` + * calls between CommonJS modules as those often rely on the lazy execution of + * nested `require` calls. + * + * Setting this option to `true` will wrap all CommonJS files in functions + * which are executed when they are required for the first time, preserving + * NodeJS semantics. Note that this can have an impact on the size and + * performance of the generated code. + * + * The default value of `"auto"` will only wrap CommonJS files when they are + * part of a CommonJS dependency cycle, e.g. an index file that is required by + * many of its dependencies. All other CommonJS files are hoisted. This is the + * recommended setting for most code bases. + * + * `false` will entirely prevent wrapping and hoist all files. This may still + * work depending on the nature of cyclic dependencies but will often cause + * problems. + * + * You can also provide a minimatch pattern, or array of patterns, to only + * specify a subset of files which should be wrapped in functions for proper + * `require` semantics. + * + * `"debug"` works like `"auto"` but after bundling, it will display a warning + * containing a list of ids that have been wrapped which can be used as + * minimatch pattern for fine-tuning. + * @default "auto" + */ + strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[] + /** + * Sometimes you have to leave require statements unconverted. Pass an array + * containing the IDs or a `id => boolean` function. + * @default [] + */ + ignore?: ReadonlyArray | ((id: string) => boolean) + /** + * In most cases, where `require` calls are inside a `try-catch` clause, + * they should be left unconverted as it requires an optional dependency + * that may or may not be installed beside the rolled up package. + * Due to the conversion of `require` to a static `import` - the call is + * hoisted to the top of the file, outside of the `try-catch` clause. + * + * - `true`: All `require` calls inside a `try` will be left unconverted. + * - `false`: All `require` calls inside a `try` will be converted as if the + * `try-catch` clause is not there. + * - `remove`: Remove all `require` calls from inside any `try` block. + * - `string[]`: Pass an array containing the IDs to left unconverted. + * - `((id: string) => boolean|'remove')`: Pass a function that control + * individual IDs. + * + * @default false + */ + ignoreTryCatch?: + | boolean + | 'remove' + | ReadonlyArray + | ((id: string) => boolean | 'remove') + /** + * Controls how to render imports from external dependencies. By default, + * this plugin assumes that all external dependencies are CommonJS. This + * means they are rendered as default imports to be compatible with e.g. + * NodeJS where ES modules can only import a default export from a CommonJS + * dependency. + * + * If you set `esmExternals` to `true`, this plugins assumes that all + * external dependencies are ES modules and respect the + * `requireReturnsDefault` option. If that option is not set, they will be + * rendered as namespace imports. + * + * You can also supply an array of ids to be treated as ES modules, or a + * function that will be passed each external id to determine if it is an ES + * module. + * @default false + */ + esmExternals?: boolean | ReadonlyArray | ((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 + * modules. By default, this plugin will render those imports as namespace + * imports i.e. + * + * ```js + * // input + * const foo = require('foo'); + * + * // output + * import * as foo from 'foo'; + * ``` + * + * However there are some situations where this may not be desired. + * For these situations, you can change Rollup's behaviour either globally or + * per module. To change it globally, set the `requireReturnsDefault` option + * to one of the following values: + * + * - `false`: This is the default, requiring an ES module returns its + * namespace. This is the only option that will also add a marker + * `__esModule: true` to the namespace to support interop patterns in + * CommonJS modules that are transpiled ES modules. + * - `"namespace"`: Like `false`, requiring an ES module returns its + * namespace, but the plugin does not add the `__esModule` marker and thus + * creates more efficient code. For external dependencies when using + * `esmExternals: true`, no additional interop code is generated. + * - `"auto"`: This is complementary to how `output.exports: "auto"` works in + * Rollup: If a module has a default export and no named exports, requiring + * that module returns the default export. In all other cases, the namespace + * is returned. For external dependencies when using `esmExternals: true`, a + * corresponding interop helper is added. + * - `"preferred"`: If a module has a default export, requiring that module + * always returns the default export, no matter whether additional named + * exports exist. This is similar to how previous versions of this plugin + * worked. Again for external dependencies when using `esmExternals: true`, + * an interop helper is added. + * - `true`: This will always try to return the default export on require + * without checking if it actually exists. This can throw at build time if + * there is no default export. This is how external dependencies are handled + * when `esmExternals` is not used. The advantage over the other options is + * that, like `false`, this does not add an interop helper for external + * dependencies, keeping the code lean. + * + * To change this for individual modules, you can supply a function for + * `requireReturnsDefault` instead. This function will then be called once for + * each required ES module or external dependency with the corresponding id + * and allows you to return different values for different modules. + * @default false + */ + requireReturnsDefault?: + | boolean + | 'auto' + | 'preferred' + | 'namespace' + | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace') + + /** + * @default "auto" + */ + defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto') + /** + * Some modules contain dynamic `require` calls, or require modules that + * contain circular dependencies, which are not handled well by static + * imports. Including those modules as `dynamicRequireTargets` will simulate a + * CommonJS (NodeJS-like) environment for them with support for dynamic + * dependencies. It also enables `strictRequires` for those modules. + * + * Note: In extreme cases, this feature may result in some paths being + * rendered as absolute in the final bundle. The plugin tries to avoid + * exposing paths from the local machine, but if you are `dynamicRequirePaths` + * 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 + /** + * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory + * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` + * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your + * home directory name. By default it uses the current working directory. + */ + dynamicRequireRoot?: string +} diff --git a/packages/vite/src/dep-types/connect.d.ts b/packages/vite/src/dep-types/connect.d.ts new file mode 100644 index 00000000000000..74c559b6a436f5 --- /dev/null +++ b/packages/vite/src/dep-types/connect.d.ts @@ -0,0 +1,111 @@ +// Inlined to avoid extra dependency +// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE + +// Type definitions for connect v3.4.0 +// Project: https://github.com/senchalabs/connect +// Definitions by: Maxime LUCE +// Evan Hahn +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as http from 'node:http' + +export namespace Connect { + export type ServerHandle = HandleFunction | http.Server + + export class IncomingMessage extends http.IncomingMessage { + originalUrl?: http.IncomingMessage['url'] | undefined + } + + 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 interface ServerStackItem { + route: string + handle: ServerHandle + } + + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void + + route: string + stack: ServerStackItem[] + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * 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 + + /** + * Handle server requests, punting them down + * the middleware stack. + */ + handle( + req: http.IncomingMessage, + res: http.ServerResponse, + next: Function + ): void + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = 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 + } +} diff --git a/packages/vite/src/dep-types/dynamicImportVars.d.ts b/packages/vite/src/dep-types/dynamicImportVars.d.ts new file mode 100644 index 00000000000000..99f1b5c453ba97 --- /dev/null +++ b/packages/vite/src/dep-types/dynamicImportVars.d.ts @@ -0,0 +1,17 @@ +export interface RollupDynamicImportVarsOptions { + /** + * Files to include in this plugin (default all). + * @default [] + */ + include?: string | RegExp | (string | RegExp)[] + /** + * Files to exclude in this plugin (default none). + * @default [] + */ + 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 +} diff --git a/packages/vite/src/dep-types/http-proxy.d.ts b/packages/vite/src/dep-types/http-proxy.d.ts new file mode 100644 index 00000000000000..1cae820dcdfa8f --- /dev/null +++ b/packages/vite/src/dep-types/http-proxy.d.ts @@ -0,0 +1,250 @@ +// Inlined to avoid extra dependency +// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE + +// Type definitions for node-http-proxy 1.17 +// Project: https://github.com/nodejitsu/node-http-proxy +// Definitions by: Maxime LUCE +// Florian Oellerich +// Daniel Schmidt +// Jordan Abreu +// Samuel Bodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import type * as net from 'node:net' +import type * as http from 'node:http' +import * as events from 'node:events' +import type * as url from 'node:url' +import type * as stream from 'node:stream' + +export namespace HttpProxy { + export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed + + export type ProxyTargetUrl = string | Partial + + export interface ProxyTargetDetailed { + host: string + port: number + protocol?: string | undefined + hostname?: string | undefined + socketPath?: string | undefined + key?: string | undefined + passphrase?: string | undefined + pfx?: Buffer | string | undefined + cert?: string | undefined + ca?: string | undefined + ciphers?: string | undefined + secureProtocol?: string | undefined + } + + 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) + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param res - Client response. + * @param options - Additional options. + */ + web( + req: http.IncomingMessage, + res: http.ServerResponse, + options?: ServerOptions, + callback?: ErrorCallback + ): void + + /** + * Used for proxying regular HTTP(S) requests + * @param req - Client request. + * @param socket - Client socket. + * @param head - Client head. + * @param options - Additional options. + */ + 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 + + /** + * A function that closes the inner webserver and stops listening on given port + */ + 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 + + /** + * 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 + + /** + * 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 + + 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 + } + + export interface ServerOptions { + /** URL string to be parsed with the url module. */ + target?: ProxyTarget | undefined + /** URL string to be parsed with the url module. */ + forward?: ProxyTargetUrl | undefined + /** Object to be passed to http(s).request. */ + agent?: any + /** Object to be passed to https.createServer(). */ + ssl?: any + /** If you want to proxy websockets. */ + ws?: boolean | undefined + /** Adds x- forward headers. */ + xfwd?: boolean | undefined + /** Verify SSL certificate. */ + secure?: boolean | undefined + /** Explicitly specify if we are proxying to another proxy. */ + toProxy?: boolean | undefined + /** Specify whether you want to prepend the target's path to the proxy path. */ + prependPath?: boolean | undefined + /** Specify whether you want to ignore the proxy path of the incoming request. */ + ignorePath?: boolean | undefined + /** Local interface string to bind for outgoing connections. */ + localAddress?: string | undefined + /** Changes the origin of the host header to the target URL. */ + changeOrigin?: boolean | undefined + /** specify whether you want to keep letter case of response header key */ + preserveHeaderKeyCase?: boolean | undefined + /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ + auth?: string | undefined + /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ + hostRewrite?: string | undefined + /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ + autoRewrite?: boolean | undefined + /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ + protocolRewrite?: string | undefined + /** rewrites domain of set-cookie headers. */ + cookieDomainRewrite?: + | false + | string + | { [oldDomain: string]: string } + | undefined + /** rewrites path of set-cookie headers. Default: false */ + cookiePathRewrite?: + | false + | string + | { [oldPath: string]: string } + | undefined + /** object with extra headers to be added to target requests. */ + headers?: { [header: string]: string } | undefined + /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ + proxyTimeout?: number | undefined + /** Timeout (in milliseconds) for incoming requests */ + timeout?: number | undefined + /** Specify whether you want to follow redirects. Default: false */ + followRedirects?: boolean | undefined + /** 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 | undefined + /** Buffer */ + buffer?: stream.Stream | undefined + } +} diff --git a/packages/vite/types/package.json b/packages/vite/src/dep-types/package.json similarity index 100% rename from packages/vite/types/package.json rename to packages/vite/src/dep-types/package.json diff --git a/packages/vite/types/shims.d.ts b/packages/vite/src/dep-types/shims.d.ts similarity index 100% rename from packages/vite/types/shims.d.ts rename to packages/vite/src/dep-types/shims.d.ts diff --git a/packages/vite/src/dep-types/terser.d.ts b/packages/vite/src/dep-types/terser.d.ts new file mode 100644 index 00000000000000..a704a20cdc71ae --- /dev/null +++ b/packages/vite/src/dep-types/terser.d.ts @@ -0,0 +1,250 @@ +// Modified and inlined to avoid extra dependency +// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts +// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE + +/* +Terser is released under the BSD license: + +Copyright 2012-2018 (c) Mihai Bazon + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +*/ + +export namespace Terser { + export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 + + export interface ParseOptions { + bare_returns?: boolean + /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */ + 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 + } + + export enum InlineFunctions { + Disabled = 0, + SimpleFunctions = 1, + WithArguments = 2, + WithArgumentsAndVariables = 3 + } + + export interface MangleOptions { + eval?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + module?: boolean + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler + properties?: boolean | ManglePropertiesOptions + reserved?: string[] + safari10?: boolean + toplevel?: boolean + } + + /** + * An identifier mangler for which the output is invariant with respect to the source code. + */ + export interface SimpleIdentifierMangler { + /** + * Obtains the nth most favored (usually shortest) identifier to rename a variable to. + * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. + * This function is expected to be stable; Evaluating get(n) === get(n) should always return true. + * @param n - The ordinal of the identifier. + */ + get(n: number): string + } + + /** + * An identifier mangler that leverages character frequency analysis to determine identifier precedence. + */ + export interface WeightedIdentifierMangler extends SimpleIdentifierMangler { + /** + * Modifies the internal weighting of the input characters by the specified delta. + * Will be invoked on the entire printed AST, and then deduct mangleable identifiers. + * @param chars - The characters to modify the weighting of. + * @param delta - The numeric weight to add to the characters. + */ + consider(chars: string, delta: number): number + /** + * Resets character weights. + */ + reset(): void + /** + * Sorts identifiers by character frequency, in preparation for calls to get(n). + */ + sort(): void + } + + export interface ManglePropertiesOptions { + builtins?: boolean + debug?: boolean + keep_quoted?: boolean | 'strict' + nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler + regex?: RegExp | string + reserved?: string[] + } + + export interface FormatOptions { + ascii_only?: boolean + /** @deprecated Not implemented anymore */ + beautify?: boolean + braces?: boolean + comments?: + | boolean + | 'all' + | 'some' + | RegExp + | (( + node: any, + comment: { + value: string + type: 'comment1' | 'comment2' | 'comment3' | 'comment4' + pos: number + line: number + col: number + } + ) => boolean) + ecma?: ECMA + ie8?: boolean + keep_numbers?: 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 + } + + export interface MinifyOptions { + compress?: boolean | CompressOptions + ecma?: ECMA + enclose?: boolean | string + ie8?: boolean + keep_classnames?: boolean | RegExp + keep_fnames?: boolean | RegExp + mangle?: boolean | MangleOptions + module?: boolean + nameCache?: object + format?: FormatOptions + /** @deprecated deprecated */ + output?: FormatOptions + parse?: ParseOptions + safari10?: boolean + sourceMap?: boolean | SourceMapOptions + toplevel?: boolean + } + + export interface MinifyOutput { + code?: string + map?: object | string + decoded_map?: object | null + } + + export interface SourceMapOptions { + /** Source map object, 'inline' or source map file content */ + content?: object | string + includeSources?: boolean + filename?: string + root?: string + url?: string | 'inline' + } +} diff --git a/packages/vite/src/dep-types/ws.d.ts b/packages/vite/src/dep-types/ws.d.ts new file mode 100644 index 00000000000000..a06341fca9eeb9 --- /dev/null +++ b/packages/vite/src/dep-types/ws.d.ts @@ -0,0 +1,553 @@ +// Modified and inlined to avoid extra dependency +// Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts + +// Type definitions for ws 8.5 +// Project: https://github.com/websockets/ws +// Definitions by: Paul Loyd +// Margus Lamp +// Philippe D'Alva +// reduckted +// teidesu +// Bartosz Wojtkowiak +// Kyle Hensel +// Samuel Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'node:events' +import type { + Agent, + ClientRequest, + ClientRequestArgs, + Server as HTTPServer, + IncomingMessage, + OutgoingHttpHeaders +} from 'node:http' +import type { Server as HTTPSServer } from 'node:https' +import type { Duplex, DuplexOptions } from 'node:stream' +import type { SecureContextOptions } from 'node:tls' +import type { URL } from 'node:url' +import type { ZlibOptions } from 'node:zlib' + +// WebSocket socket. +declare class WebSocket extends EventEmitter { + /** The connection is not yet open. */ + static readonly CONNECTING: 0 + /** The connection is open and ready to communicate. */ + static readonly OPEN: 1 + /** The connection is in the process of closing. */ + static readonly CLOSING: 2 + /** The connection is closed. */ + static readonly CLOSED: 3 + + binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments' + readonly bufferedAmount: number + readonly extensions: string + /** Indicates whether the websocket is paused */ + readonly isPaused: boolean + 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 + + /** The connection is not yet open. */ + readonly CONNECTING: 0 + /** The connection is open and ready to communicate. */ + readonly OPEN: 1 + /** The connection is in the process of closing. */ + readonly CLOSING: 2 + /** The connection is closed. */ + readonly CLOSED: 3 + + onopen: ((event: WebSocket.Event) => void) | null + onerror: ((event: WebSocket.ErrorEvent) => void) | null + onclose: ((event: WebSocket.CloseEvent) => void) | null + onmessage: ((event: WebSocket.MessageEvent) => void) | null + + constructor(address: null) + constructor( + address: string | URL, + options?: WebSocket.ClientOptions | ClientRequestArgs + ) + constructor( + address: string | URL, + protocols?: string | string[], + options?: WebSocket.ClientOptions | ClientRequestArgs + ) + + close(code?: number, data?: string | Buffer): 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 + }, + cb?: (err?: Error) => void + ): void + terminate(): void + + /** + * Pause the websocket causing it to stop emitting events. Some events can still be + * emitted after this is called, until all buffered data is consumed. This method + * is a noop if the ready state is `CONNECTING` or `CLOSED`. + */ + pause(): void + /** + * Make a paused socket resume emitting events. This method is a noop if the ready + * state is `CONNECTING` or `CLOSED`. + */ + resume(): void + + // HTML5 WebSocket events + addEventListener( + method: 'message', + cb: (event: WebSocket.MessageEvent) => void, + options?: WebSocket.EventListenerOptions + ): void + addEventListener( + method: 'close', + cb: (event: WebSocket.CloseEvent) => void, + options?: WebSocket.EventListenerOptions + ): void + addEventListener( + method: 'error', + cb: (event: WebSocket.ErrorEvent) => void, + options?: WebSocket.EventListenerOptions + ): void + addEventListener( + method: 'open', + cb: (event: WebSocket.Event) => void, + options?: WebSocket.EventListenerOptions + ): void + + removeEventListener( + method: 'message', + cb: (event: WebSocket.MessageEvent) => void + ): void + removeEventListener( + method: 'close', + cb: (event: WebSocket.CloseEvent) => void + ): void + removeEventListener( + method: 'error', + cb: (event: WebSocket.ErrorEvent) => void + ): void + removeEventListener( + method: 'open', + cb: (event: WebSocket.Event) => void + ): void + + // Events + on( + event: 'close', + listener: (this: WebSocket, code: number, reason: Buffer) => 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.RawData, + isBinary: boolean + ) => 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: Buffer) => 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.RawData, + isBinary: boolean + ) => 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: Buffer) => 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.RawData, + isBinary: boolean + ) => 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, reason: Buffer) => void + ): this + addListener(event: 'error', listener: (err: Error) => void): this + addListener( + event: 'upgrade', + listener: (request: IncomingMessage) => void + ): this + addListener( + event: 'message', + listener: (data: WebSocket.RawData, isBinary: boolean) => 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, reason: Buffer) => void + ): this + removeListener(event: 'error', listener: (err: Error) => void): this + removeListener( + event: 'upgrade', + listener: (request: IncomingMessage) => void + ): this + removeListener( + event: 'message', + listener: (data: WebSocket.RawData, isBinary: boolean) => 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 +} + +declare const WebSocketAlias: typeof WebSocket +interface WebSocketAlias extends WebSocket {} // tslint:disable-line no-empty-interface + +declare namespace WebSocket { + /** + * Data represents the raw message payload received over the WebSocket. + */ + type RawData = Buffer | ArrayBuffer | Buffer[] + + /** + * Data represents the message payload received over the WebSocket. + */ + type Data = string | Buffer | ArrayBuffer | Buffer[] + + /** + * CertMeta represents the accepted types for certificate & key data. + */ + 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 + + /** + * VerifyClientCallbackAsync is an asynchronous callback used to inspect the + * incoming message. The return value (boolean) of the function determines + * whether or not to accept the handshake. + */ + type VerifyClientCallbackAsync = ( + info: { origin: string; secure: boolean; req: IncomingMessage }, + callback: ( + res: boolean, + code?: number, + message?: string, + headers?: OutgoingHttpHeaders + ) => void + ) => void + + interface ClientOptions extends SecureContextOptions { + protocol?: string | undefined + followRedirects?: boolean | undefined + generateMask?(mask: Buffer): void + 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 + skipUTF8Validation?: boolean | undefined + } + + interface PerMessageDeflateOptions { + 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 + } + | undefined + zlibInflateOptions?: ZlibOptions | undefined + threshold?: number | undefined + concurrencyLimit?: number | undefined + } + + interface Event { + type: string + target: WebSocket + } + + interface ErrorEvent { + error: any + message: string + type: string + target: WebSocket + } + + interface CloseEvent { + wasClean: boolean + code: number + reason: string + type: string + target: WebSocket + } + + interface MessageEvent { + data: Data + type: string + target: WebSocket + } + + interface EventListenerOptions { + once?: boolean | undefined + } + + interface ServerOptions { + host?: string | undefined + port?: number | undefined + backlog?: number | undefined + server?: HTTPServer | HTTPSServer | undefined + verifyClient?: + | VerifyClientCallbackAsync + | VerifyClientCallbackSync + | undefined + handleProtocols?: ( + protocols: Set, + request: IncomingMessage + ) => string | false + path?: string | undefined + noServer?: boolean | undefined + clientTracking?: boolean | undefined + perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined + maxPayload?: number | undefined + skipUTF8Validation?: boolean | undefined + WebSocket?: typeof WebSocket.WebSocket | undefined + } + + interface AddressInfo { + address: string + family: string + port: number + } + + // WebSocket Server + class Server extends EventEmitter { + options: ServerOptions + path: string + clients: Set + + constructor(options?: ServerOptions, callback?: () => void) + + address(): AddressInfo | string + close(cb?: (err?: Error) => void): void + handleUpgrade( + request: IncomingMessage, + socket: Duplex, + upgradeHead: Buffer, + callback: (client: T, request: IncomingMessage) => void + ): void + shouldHandle(request: IncomingMessage): boolean | Promise + + // Events + on( + event: 'connection', + cb: (this: Server, socket: T, 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: T, 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: (this: Server, ...args: any[]) => void + ): this + + off( + event: 'connection', + cb: (this: Server, socket: T, 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: T, 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: T) => 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 + } + + const WebSocketServer: typeof Server + interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface + const WebSocket: typeof WebSocketAlias + interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface + + // WebSocket stream + function createWebSocketStream( + websocket: WebSocket, + options?: DuplexOptions + ): Duplex +} + +// export = WebSocket +export { WebSocket, WebSocketAlias } diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap b/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap index 6eeb763c4117bd..f4103222acebdd 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap +++ b/packages/vite/src/node/__tests__/plugins/importGlob/__snapshots__/fixture.test.ts.snap @@ -1,8 +1,7 @@ // Vitest Snapshot v1 exports[`fixture > transform 1`] = ` -"import * as __vite_glob_1_0 from \\"./modules/a.ts\\";import * as __vite_glob_1_1 from \\"./modules/b.ts\\";import * as __vite_glob_1_2 from \\"./modules/index.ts\\";import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\";import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\";import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\";import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\";import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\";import \\"../../../../../../types/importMeta\\"; -export const basic = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"),\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\")}); +"import * as __vite_glob_1_0 from \\"./modules/a.ts\\";import * as __vite_glob_1_1 from \\"./modules/b.ts\\";import * as __vite_glob_1_2 from \\"./modules/index.ts\\";import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\";import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\";import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\";import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\";import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\";export const basic = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"),\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\")}); export const basicEager = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": __vite_glob_1_0,\\"./modules/b.ts\\": __vite_glob_1_1,\\"./modules/index.ts\\": __vite_glob_1_2}); export const ignore = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\")}); export const namedEager = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": __vite_glob_3_0,\\"./modules/b.ts\\": __vite_glob_3_1,\\"./modules/index.ts\\": __vite_glob_3_2}); @@ -20,8 +19,7 @@ export const cleverCwd2 = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": ( `; exports[`fixture > transform with restoreQueryExtension 1`] = ` -"import * as __vite_glob_1_0 from \\"./modules/a.ts\\";import * as __vite_glob_1_1 from \\"./modules/b.ts\\";import * as __vite_glob_1_2 from \\"./modules/index.ts\\";import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\";import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\";import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\";import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\";import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\";import \\"../../../../../../types/importMeta\\"; -export const basic = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"),\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\")}); +"import * as __vite_glob_1_0 from \\"./modules/a.ts\\";import * as __vite_glob_1_1 from \\"./modules/b.ts\\";import * as __vite_glob_1_2 from \\"./modules/index.ts\\";import { name as __vite_glob_3_0 } from \\"./modules/a.ts\\";import { name as __vite_glob_3_1 } from \\"./modules/b.ts\\";import { name as __vite_glob_3_2 } from \\"./modules/index.ts\\";import { default as __vite_glob_5_0 } from \\"./modules/a.ts?raw\\";import { default as __vite_glob_5_1 } from \\"./modules/b.ts?raw\\";export const basic = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\"),\\"./modules/index.ts\\": () => import(\\"./modules/index.ts\\")}); export const basicEager = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": __vite_glob_1_0,\\"./modules/b.ts\\": __vite_glob_1_1,\\"./modules/index.ts\\": __vite_glob_1_2}); export const ignore = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": () => import(\\"./modules/a.ts\\"),\\"./modules/b.ts\\": () => import(\\"./modules/b.ts\\")}); export const namedEager = /* #__PURE__ */ Object.assign({\\"./modules/a.ts\\": __vite_glob_3_0,\\"./modules/b.ts\\": __vite_glob_3_1,\\"./modules/index.ts\\": __vite_glob_3_2}); diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts index 5a3f6d487ff154..ccf47d4edca6cf 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts @@ -1,4 +1,8 @@ -import '../../../../../../types/importMeta' +import type { ImportMeta as ViteImportMeta } from 'types/importMeta' + +declare global { + interface ImportMeta extends ViteImportMeta {} +} export interface ModuleType { name: string diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 1d8b0e209680fe..41b5d0524aad04 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -16,10 +16,10 @@ import type { WarningHandler, WatcherOptions } from 'rollup' -import type { Terser } from 'types/terser' +import type { Terser } from 'dep-types/terser' import commonjsPlugin from '@rollup/plugin-commonjs' -import type { RollupCommonJSOptions } from 'types/commonjs' -import type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars' +import type { RollupCommonJSOptions } from 'dep-types/commonjs' +import type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars' import type { TransformOptions } from 'esbuild' import type { InlineConfig, ResolvedConfig } from './config' import { isDepsOptimizerEnabled, resolveConfig } from './config' diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 46ee9476677c2d..a760a06fb86601 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -4,7 +4,7 @@ import { parse as parseUrl, pathToFileURL } from 'node:url' import { performance } from 'node:perf_hooks' import { createRequire } from 'node:module' import colors from 'picocolors' -import type { Alias, AliasOptions } from 'types/alias' +import type { Alias, AliasOptions } from 'dep-types/alias' import aliasPlugin from '@rollup/plugin-alias' import { build } from 'esbuild' import type { RollupOptions } from 'rollup' diff --git a/packages/vite/src/node/http.ts b/packages/vite/src/node/http.ts index af66a6356da05f..c77f5ec664ba3c 100644 --- a/packages/vite/src/node/http.ts +++ b/packages/vite/src/node/http.ts @@ -5,7 +5,7 @@ import type { OutgoingHttpHeaders as HttpServerHeaders } from 'node:http' import type { ServerOptions as HttpsServerOptions } from 'node:https' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import colors from 'picocolors' import { isObject } from './utils' import type { ProxyOptions } from './server/middlewares/proxy' diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts index c595ff0aa7e7e3..2bc81f001d6947 100644 --- a/packages/vite/src/node/index.ts +++ b/packages/vite/src/node/index.ts @@ -60,12 +60,6 @@ export type { LogType, LoggerOptions } from './logger' -export type { - AliasOptions, - ResolverFunction, - ResolverObject, - Alias -} from 'types/alias' export type { IndexHtmlTransform, IndexHtmlTransformHook, @@ -108,26 +102,36 @@ export type { PrunePayload, ErrorPayload } from 'types/hmrPayload' -export type { Connect } from 'types/connect' -export type { WebSocket, WebSocketAlias } from 'types/ws' -export type { HttpProxy } from 'types/http-proxy' -export type { - FSWatcher, - WatchOptions, - AwaitWriteFinishOptions -} from 'types/chokidar' -export type { Terser } from 'types/terser' -export type { RollupCommonJSOptions } from 'types/commonjs' -export type { RollupDynamicImportVarsOptions } from 'types/dynamicImportVars' export type { CustomEventMap, InferCustomEventPayload } from 'types/customEvent' -export type { Matcher, AnymatchPattern, AnymatchFn } from 'types/anymatch' +// [deprecated: use vite/client/types instead] export type { ImportGlobFunction, ImportGlobEagerFunction, ImportGlobOptions, + GeneralImportGlobOptions, KnownAsTypeMap } from 'types/importGlob' +// dep types +export type { + AliasOptions, + ResolverFunction, + ResolverObject, + Alias +} from 'dep-types/alias' +export type { Connect } from 'dep-types/connect' +export type { WebSocket, WebSocketAlias } from 'dep-types/ws' +export type { HttpProxy } from 'dep-types/http-proxy' +export type { + FSWatcher, + WatchOptions, + AwaitWriteFinishOptions +} from 'dep-types/chokidar' +export type { Terser } from 'dep-types/terser' +export type { RollupCommonJSOptions } from 'dep-types/commonjs' +export type { RollupDynamicImportVarsOptions } from 'dep-types/dynamicImportVars' +export type { Matcher, AnymatchPattern, AnymatchFn } from 'dep-types/anymatch' + declare module 'rollup' { export interface RenderedChunk { viteMetadata: ChunkMetadata diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 70ab1d3d268d8b..bcc5359d17ca93 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -18,7 +18,7 @@ import type * as PostCSS from 'postcss' import type Sass from 'sass' import type Stylus from 'stylus' import type Less from 'less' -import type { Alias } from 'types/alias' +import type { Alias } from 'dep-types/alias' import type { TransformOptions } from 'esbuild' import { formatMessages, transform } from 'esbuild' import type { RawSourceMap } from '@ampproject/remapping' diff --git a/packages/vite/src/node/plugins/terser.ts b/packages/vite/src/node/plugins/terser.ts index 6362ca0b726fbf..bfbb924032d120 100644 --- a/packages/vite/src/node/plugins/terser.ts +++ b/packages/vite/src/node/plugins/terser.ts @@ -1,5 +1,5 @@ import { Worker } from 'okie' -import type { Terser } from 'types/terser' +import type { Terser } from 'dep-types/terser' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '..' import { requireResolveFromRootWithFallback } from '../utils' diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index 577758357072d6..d17fc0845326dc 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -2,7 +2,7 @@ import path from 'node:path' import type * as http from 'node:http' import sirv from 'sirv' import connect from 'connect' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import corsMiddleware from 'cors' import type { ResolvedServerOptions, ResolvedServerUrls } from './server' import type { CommonServerOptions } from './http' diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index a5cf8f171dd038..57a6a01e1fea12 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -7,8 +7,8 @@ import connect from 'connect' import corsMiddleware from 'cors' import colors from 'picocolors' import chokidar from 'chokidar' -import type { FSWatcher, WatchOptions } from 'types/chokidar' -import type { Connect } from 'types/connect' +import type { FSWatcher, WatchOptions } from 'dep-types/chokidar' +import type { Connect } from 'dep-types/connect' import launchEditorMiddleware from 'launch-editor-middleware' import type { SourceMap } from 'rollup' import picomatch from 'picomatch' diff --git a/packages/vite/src/node/server/middlewares/base.ts b/packages/vite/src/node/server/middlewares/base.ts index 002ec111335128..27960f900b44b7 100644 --- a/packages/vite/src/node/server/middlewares/base.ts +++ b/packages/vite/src/node/server/middlewares/base.ts @@ -1,4 +1,4 @@ -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import type { ViteDevServer } from '..' // this middleware is only active when (config.base !== '/') diff --git a/packages/vite/src/node/server/middlewares/error.ts b/packages/vite/src/node/server/middlewares/error.ts index c43901a5b0a265..643e90a5c38e83 100644 --- a/packages/vite/src/node/server/middlewares/error.ts +++ b/packages/vite/src/node/server/middlewares/error.ts @@ -1,6 +1,6 @@ import colors from 'picocolors' import type { RollupError } from 'rollup' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import strip from 'strip-ansi' import type { ErrorPayload } from 'types/hmrPayload' import { pad } from '../../utils' diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 1fc921573c0cbe..199468727c17c2 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -2,7 +2,7 @@ import fs from 'node:fs' import path from 'node:path' import MagicString from 'magic-string' import type { SourceMapInput } from 'rollup' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import type { DefaultTreeAdapterMap, Token } from 'parse5' import type { IndexHtmlTransformHook } from '../../plugins/html' import { diff --git a/packages/vite/src/node/server/middlewares/proxy.ts b/packages/vite/src/node/server/middlewares/proxy.ts index 6554358f091028..dc9ff4753006aa 100644 --- a/packages/vite/src/node/server/middlewares/proxy.ts +++ b/packages/vite/src/node/server/middlewares/proxy.ts @@ -1,8 +1,8 @@ import type * as http from 'node:http' import type * as net from 'node:net' import httpProxy from 'http-proxy' -import type { Connect } from 'types/connect' -import type { HttpProxy } from 'types/http-proxy' +import type { Connect } from 'dep-types/connect' +import type { HttpProxy } from 'dep-types/http-proxy' import colors from 'picocolors' import { HMR_HEADER } from '../ws' import { createDebugger, isObject } from '../../utils' diff --git a/packages/vite/src/node/server/middlewares/spaFallback.ts b/packages/vite/src/node/server/middlewares/spaFallback.ts index 6970eef9df5706..6f5b645cd02429 100644 --- a/packages/vite/src/node/server/middlewares/spaFallback.ts +++ b/packages/vite/src/node/server/middlewares/spaFallback.ts @@ -1,7 +1,7 @@ import fs from 'node:fs' import path from 'node:path' import history from 'connect-history-api-fallback' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import { createDebugger } from '../../utils' export function spaFallbackMiddleware( diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index dff31d19bff209..c877022a63cde7 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -2,7 +2,7 @@ import path from 'node:path' import type { OutgoingHttpHeaders, ServerResponse } from 'node:http' import type { Options } from 'sirv' import sirv from 'sirv' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import type { ViteDevServer } from '../..' import { FS_PREFIX } from '../../constants' import { diff --git a/packages/vite/src/node/server/middlewares/time.ts b/packages/vite/src/node/server/middlewares/time.ts index 41a42f63270e50..7fdc7172f1ed58 100644 --- a/packages/vite/src/node/server/middlewares/time.ts +++ b/packages/vite/src/node/server/middlewares/time.ts @@ -1,5 +1,5 @@ import { performance } from 'node:perf_hooks' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import { createDebugger, prettifyUrl, timeFrom } from '../../utils' const logTime = createDebugger('vite:time') diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index 1bba1711e1b326..929c6856d34748 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -1,6 +1,6 @@ import { promises as fs } from 'node:fs' import path from 'node:path' -import type { Connect } from 'types/connect' +import type { Connect } from 'dep-types/connect' import colors from 'picocolors' import type { ViteDevServer } from '..' import { diff --git a/packages/vite/src/node/server/ws.ts b/packages/vite/src/node/server/ws.ts index 54eaa21e94de45..cb8555122b6840 100644 --- a/packages/vite/src/node/server/ws.ts +++ b/packages/vite/src/node/server/ws.ts @@ -6,7 +6,7 @@ import type { Socket } from 'node:net' import colors from 'picocolors' import type { ServerOptions, WebSocket as WebSocketRaw } from 'ws' import { WebSocketServer as WebSocketServerRaw } from 'ws' -import type { WebSocket as WebSocketTypes } from 'types/ws' +import type { WebSocket as WebSocketTypes } from 'dep-types/ws' import type { CustomPayload, ErrorPayload, HMRPayload } from 'types/hmrPayload' import type { InferCustomEventPayload } from 'types/customEvent' import type { ResolvedConfig } from '..' diff --git a/packages/vite/src/node/tsconfig.json b/packages/vite/src/node/tsconfig.json index 270b34189571e1..bfaac1db6cbf00 100644 --- a/packages/vite/src/node/tsconfig.json +++ b/packages/vite/src/node/tsconfig.json @@ -1,6 +1,6 @@ { "extends": "../../tsconfig.base.json", - "include": ["./", "../../types"], + "include": ["./", "../dep-types", "../types"], "exclude": ["**/__tests__"], "compilerOptions": { "lib": ["ESNext", "DOM"] diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 032ec10da8dabe..2c6a8c790c607c 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -14,7 +14,7 @@ import remapping from '@ampproject/remapping' import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping' import colors from 'picocolors' import debug from 'debug' -import type { Alias, AliasOptions } from 'types/alias' +import type { Alias, AliasOptions } from 'dep-types/alias' import type MagicString from 'magic-string' import type { TransformResult } from 'rollup' diff --git a/packages/vite/src/node/watch.ts b/packages/vite/src/node/watch.ts index 378610e28f3799..47a455a0cd0e76 100644 --- a/packages/vite/src/node/watch.ts +++ b/packages/vite/src/node/watch.ts @@ -1,4 +1,4 @@ -import type { WatchOptions } from 'types/chokidar' +import type { WatchOptions } from 'dep-types/chokidar' export function resolveChokidarOptions( options: WatchOptions | undefined diff --git a/packages/vite/src/types/customEvent.d.ts b/packages/vite/src/types/customEvent.d.ts new file mode 100644 index 00000000000000..af4db5d14fbe97 --- /dev/null +++ b/packages/vite/src/types/customEvent.d.ts @@ -0,0 +1,16 @@ +import type { + ErrorPayload, + FullReloadPayload, + PrunePayload, + UpdatePayload +} from './hmrPayload' + +export interface CustomEventMap { + 'vite:beforeUpdate': UpdatePayload + 'vite:beforePrune': PrunePayload + 'vite:beforeFullReload': FullReloadPayload + 'vite:error': ErrorPayload +} + +export type InferCustomEventPayload = + T extends keyof CustomEventMap ? CustomEventMap[T] : any diff --git a/packages/vite/src/types/hmrPayload.d.ts b/packages/vite/src/types/hmrPayload.d.ts new file mode 100644 index 00000000000000..839095009e76fb --- /dev/null +++ b/packages/vite/src/types/hmrPayload.d.ts @@ -0,0 +1,61 @@ +export type HMRPayload = + | ConnectedPayload + | UpdatePayload + | FullReloadPayload + | CustomPayload + | ErrorPayload + | PrunePayload + +export interface ConnectedPayload { + type: 'connected' +} + +export interface UpdatePayload { + type: 'update' + updates: Update[] +} + +export interface Update { + type: 'js-update' | 'css-update' + path: string + acceptedPath: string + timestamp: number + /** + * @experimental internal + */ + explicitImportRequired?: boolean | undefined +} + +export interface PrunePayload { + type: 'prune' + paths: string[] +} + +export interface FullReloadPayload { + type: 'full-reload' + path?: string +} + +export interface CustomPayload { + type: 'custom' + event: string + data?: any +} + +export interface ErrorPayload { + type: 'error' + err: { + [name: string]: any + message: string + stack: string + id?: string + frame?: string + plugin?: string + pluginCode?: string + loc?: { + file?: string + line: number + column: number + } + } +} diff --git a/packages/vite/src/types/hot.d.ts b/packages/vite/src/types/hot.d.ts new file mode 100644 index 00000000000000..985f3a47197c43 --- /dev/null +++ b/packages/vite/src/types/hot.d.ts @@ -0,0 +1,33 @@ +import type { InferCustomEventPayload } from './customEvent' + +export type ModuleNamespace = Record & { + [Symbol.toStringTag]: 'Module' +} + +export interface ViteHotContext { + readonly data: any + + accept(): void + accept(cb: (mod: ModuleNamespace | undefined) => void): void + accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void + accept( + deps: readonly string[], + cb: (mods: Array) => void + ): void + + acceptExports(exportNames: string | readonly string[]): void + acceptExports( + exportNames: string | readonly string[], + cb: (mod: ModuleNamespace | undefined) => void + ): void + + dispose(cb: (data: any) => void): void + decline(): void + invalidate(): void + + on( + event: T, + cb: (payload: InferCustomEventPayload) => void + ): void + send(event: T, data?: InferCustomEventPayload): void +} diff --git a/packages/vite/src/types/importGlob.d.ts b/packages/vite/src/types/importGlob.d.ts new file mode 100644 index 00000000000000..321e3804a7e09a --- /dev/null +++ b/packages/vite/src/types/importGlob.d.ts @@ -0,0 +1,97 @@ +export interface ImportGlobOptions< + Eager extends boolean, + AsType extends string +> { + /** + * Import type for the import url. + */ + as?: AsType + /** + * Import as static or dynamic + * + * @default false + */ + eager?: Eager + /** + * Import only the specific named export. Set to `default` to import the default export. + */ + import?: string + /** + * Custom queries + */ + query?: string | Record + /** + * Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance. + * + * @default false + */ + exhaustive?: boolean +} + +export type GeneralImportGlobOptions = ImportGlobOptions + +export interface KnownAsTypeMap { + raw: string + url: string + worker: Worker +} + +export interface ImportGlobFunction { + /** + * Import a list of files with a glob pattern. + * + * Overload 1: No generic provided, infer the type from `eager` and `as` + */ + < + Eager extends boolean, + As extends string, + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + >( + glob: string | string[], + options?: ImportGlobOptions + ): (Eager extends true ? true : false) extends true + ? Record + : Record Promise> + /** + * Import a list of files with a glob pattern. + * + * Overload 2: Module generic provided, infer the type from `eager: false` + */ + ( + glob: string | string[], + options?: ImportGlobOptions + ): Record Promise> + /** + * Import a list of files with a glob pattern. + * + * Overload 3: Module generic provided, infer the type from `eager: true` + */ + ( + glob: string | string[], + options: ImportGlobOptions + ): Record +} + +export interface ImportGlobEagerFunction { + /** + * Eagerly import a list of files with a glob pattern. + * + * Overload 1: No generic provided, infer the type from `as` + */ + < + As extends string, + T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown + >( + glob: string | string[], + options?: Omit, 'eager'> + ): Record + /** + * Eagerly import a list of files with a glob pattern. + * + * Overload 2: Module generic provided + */ + ( + glob: string | string[], + options?: Omit, 'eager'> + ): Record +} diff --git a/packages/vite/src/types/importMeta.d.ts b/packages/vite/src/types/importMeta.d.ts new file mode 100644 index 00000000000000..794c27c73c102c --- /dev/null +++ b/packages/vite/src/types/importMeta.d.ts @@ -0,0 +1,25 @@ +import type { ViteHotContext } from './hot' +import type { ImportGlobEagerFunction, ImportGlobFunction } from './importGlob' + +export interface ImportMetaEnv { + [key: string]: any + BASE_URL: string + MODE: string + DEV: boolean + PROD: boolean + SSR: boolean +} + +export interface ImportMeta { + url: string + + readonly hot?: ViteHotContext + + readonly env: ImportMetaEnv + + glob: ImportGlobFunction + /** + * @deprecated Use `import.meta.glob('*', { eager: true })` instead + */ + globEager: ImportGlobEagerFunction +} diff --git a/packages/vite/src/types/package.json b/packages/vite/src/types/package.json new file mode 100644 index 00000000000000..3d6a75c81455a0 --- /dev/null +++ b/packages/vite/src/types/package.json @@ -0,0 +1,3 @@ +{ + "//": "this file is just here to make pnpm happy with --frozen-lockfile" +} diff --git a/packages/vite/types/alias.d.ts b/packages/vite/types/alias.d.ts index 3f4393586f1299..91f73635584ffb 100644 --- a/packages/vite/types/alias.d.ts +++ b/packages/vite/types/alias.d.ts @@ -1,59 +1,6 @@ -/** -Types from https://github.com/rollup/plugins/blob/master/packages/alias/types/index.d.ts -Inlined because the plugin is bundled. - -https://github.com/rollup/plugins/blob/master/LICENSE - -The MIT License (MIT) - -Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ - -import type { PluginHooks } from 'rollup' - -export interface Alias { - 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 -} - -export type ResolverFunction = PluginHooks['resolveId'] - -export interface ResolverObject { - buildStart?: PluginHooks['buildStart'] - resolveId: ResolverFunction -} - -/** - * Specifies an `Object`, or an `Array` of `Object`, - * which defines aliases used to replace values in `import` or `require` statements. - * With either format, the order of the entries is important, - * in that the first defined rules are applied first. - * - * 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 { + Alias, + ResolverFunction, + ResolverObject, + AliasOptions +} from '../dist/node' diff --git a/packages/vite/types/anymatch.d.ts b/packages/vite/types/anymatch.d.ts index 9204588583046d..c98e9505f3f90f 100644 --- a/packages/vite/types/anymatch.d.ts +++ b/packages/vite/types/anymatch.d.ts @@ -1,5 +1 @@ -export type AnymatchFn = (testString: string) => boolean -export type AnymatchPattern = string | RegExp | AnymatchFn -type AnymatchMatcher = AnymatchPattern | AnymatchPattern[] - -export { AnymatchMatcher as Matcher } +export type { AnymatchFn, AnymatchPattern, Matcher } from '../dist/node' diff --git a/packages/vite/types/chokidar.d.ts b/packages/vite/types/chokidar.d.ts index 0dc4bec1013643..eae22093bf9d7d 100644 --- a/packages/vite/types/chokidar.d.ts +++ b/packages/vite/types/chokidar.d.ts @@ -1,228 +1,10 @@ -// Inlined to avoid extra dependency (chokidar is bundled in the published build) +export type { + FSWatcher, + WatchOptions, + AwaitWriteFinishOptions +} from '../dist/node' -// https://github.com/paulmillr/chokidar/blob/master/types/index.d.ts -// MIT Licensed https://github.com/paulmillr/chokidar/blob/master/LICENSE - -/** -The MIT License (MIT) - -Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the “Software”), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ -/// - -import type * as fs from 'node:fs' -import { EventEmitter } from 'node:events' -import type { Matcher } from './anymatch' - -export class FSWatcher extends EventEmitter implements fs.FSWatcher { - options: WatchOptions - - /** - * Constructs a new FSWatcher instance with optional WatchOptions parameter. - */ - constructor(options?: WatchOptions) - - /** - * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one - * string. - */ - add(paths: string | ReadonlyArray): this - - /** - * Stop watching files, directories, or glob patterns. Takes an array of strings or just one - * string. - */ - unwatch(paths: string | ReadonlyArray): this - - /** - * Returns an object representing all the paths on the file system being watched by this - * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless - * the `cwd` option was used), and the values are arrays of the names of the items contained in - * each directory. - */ - getWatched(): { - [directory: string]: string[] - } - - /** - * Removes all listeners from watched files. - */ - close(): Promise - - 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 - - /** - * Error occurred - */ - 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 - - /** - * Fires when the initial scan is complete - */ - on(event: 'ready', listener: () => void): this - - on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this - - on(event: string, listener: (...args: any[]) => void): this -} - -export interface WatchOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched. If - * 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 - - /** - * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to - * be ignored. The whole relative or absolute path is tested, not just filename. If a function - * with two arguments is provided, it gets called twice per path - once with a single argument - * (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 - - /** - * 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 - - /** - * 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 - - /** - * The base directory from which watch `paths` are to be derived. Paths emitted with events will - * be relative to this. - */ - 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 - - /** - * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU - * utilization, consider setting this to `false`. It is typically necessary to **set this to - * `true` to successfully watch files over a network**, and it may be necessary to successfully - * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides - * the `useFsEvents` default. - */ - usePolling?: boolean - - /** - * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly - * and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on - * OS X, `usePolling: true` becomes the default. - */ - 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 - - /** - * If set, limits how many levels of subdirectories will be traversed. - */ - depth?: number - - /** - * Interval of file system polling. - */ - 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 - - /** - * 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 - - /** - * `true` if `useFsEvents` and `usePolling` are `false`. Automatically filters out artifacts - * that occur when using editors that use "atomic writes" instead of writing directly to the - * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` - * 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 - - /** - * can be set to an object in order to adjust timing params: - */ - awaitWriteFinish?: AwaitWriteFinishOptions | boolean -} - -export interface AwaitWriteFinishOptions { - /** - * Amount of time in milliseconds for a file size to remain constant before emitting its event. - */ - stabilityThreshold?: number - - /** - * File size polling interval. - */ - pollInterval?: number -} - -/** - * produces an instance of `FSWatcher`. - */ +import type { FSWatcher, WatchOptions } from '../dist/node' export function watch( paths: string | ReadonlyArray, options?: WatchOptions diff --git a/packages/vite/types/commonjs.d.ts b/packages/vite/types/commonjs.d.ts index 01948156deb1cd..8b95405a14257e 100644 --- a/packages/vite/types/commonjs.d.ts +++ b/packages/vite/types/commonjs.d.ts @@ -1,230 +1 @@ -/** - * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts - * - * This source code is licensed under the MIT license found in the - * LICENSE file at - * https://github.com/rollup/plugins/blob/master/LICENSE - */ -export interface RollupCommonJSOptions { - /** - * A minimatch pattern, or array of patterns, which specifies the files in - * the build the plugin should operate on. By default, all files with - * extension `".cjs"` or those in `extensions` are included, but you can - * narrow this list by only including specific files. These files will be - * analyzed and transpiled if either the analysis does not find ES module - * specific statements or `transformMixedEsModules` is `true`. - * @default undefined - */ - 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 - * extensions other than those in `extensions` or `".cjs"` are ignored, but you - * can exclude additional files. See also the `include` option. - * @default undefined - */ - 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 - /** - * If true then uses of `global` won't be dealt with by this plugin - * @default false - */ - ignoreGlobal?: boolean - /** - * If false, skips source map generation for CommonJS modules. This will - * improve performance. - * @default true - */ - sourceMap?: boolean - /** - * Some `require` calls cannot be resolved statically to be translated to - * imports. - * When this option is set to `false`, the generated code will either - * directly throw an error when such a call is encountered or, when - * `dynamicRequireTargets` is used, when such a call cannot be resolved with a - * configured dynamic require target. - * Setting this option to `true` will instead leave the `require` call in the - * code or use it as a fallback for `dynamicRequireTargets`. - * @default false - */ - 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` - * statements and CommonJS `require` expressions. Set to `true` if `require` - * calls should be transformed to imports in mixed modules, or `false` if the - * `require` expressions should survive the transformation. The latter can be - * important if the code contains environment detection, or you are coding - * for an environment with special treatment for `require` calls such as - * ElectronJS. See also the `ignore` option. - * @default false - */ - transformMixedEsModules?: boolean - /** - * By default, this plugin will try to hoist `require` statements as imports - * to the top of each file. While this works well for many code bases and - * allows for very efficient ESM output, it does not perfectly capture - * CommonJS semantics as the order of side effects like log statements may - * change. But it is especially problematic when there are circular `require` - * calls between CommonJS modules as those often rely on the lazy execution of - * nested `require` calls. - * - * Setting this option to `true` will wrap all CommonJS files in functions - * which are executed when they are required for the first time, preserving - * NodeJS semantics. Note that this can have an impact on the size and - * performance of the generated code. - * - * The default value of `"auto"` will only wrap CommonJS files when they are - * part of a CommonJS dependency cycle, e.g. an index file that is required by - * many of its dependencies. All other CommonJS files are hoisted. This is the - * recommended setting for most code bases. - * - * `false` will entirely prevent wrapping and hoist all files. This may still - * work depending on the nature of cyclic dependencies but will often cause - * problems. - * - * You can also provide a minimatch pattern, or array of patterns, to only - * specify a subset of files which should be wrapped in functions for proper - * `require` semantics. - * - * `"debug"` works like `"auto"` but after bundling, it will display a warning - * containing a list of ids that have been wrapped which can be used as - * minimatch pattern for fine-tuning. - * @default "auto" - */ - strictRequires?: boolean | string | RegExp | readonly (string | RegExp)[] - /** - * Sometimes you have to leave require statements unconverted. Pass an array - * containing the IDs or a `id => boolean` function. - * @default [] - */ - ignore?: ReadonlyArray | ((id: string) => boolean) - /** - * In most cases, where `require` calls are inside a `try-catch` clause, - * they should be left unconverted as it requires an optional dependency - * that may or may not be installed beside the rolled up package. - * Due to the conversion of `require` to a static `import` - the call is - * hoisted to the top of the file, outside of the `try-catch` clause. - * - * - `true`: All `require` calls inside a `try` will be left unconverted. - * - `false`: All `require` calls inside a `try` will be converted as if the - * `try-catch` clause is not there. - * - `remove`: Remove all `require` calls from inside any `try` block. - * - `string[]`: Pass an array containing the IDs to left unconverted. - * - `((id: string) => boolean|'remove')`: Pass a function that control - * individual IDs. - * - * @default false - */ - ignoreTryCatch?: - | boolean - | 'remove' - | ReadonlyArray - | ((id: string) => boolean | 'remove') - /** - * Controls how to render imports from external dependencies. By default, - * this plugin assumes that all external dependencies are CommonJS. This - * means they are rendered as default imports to be compatible with e.g. - * NodeJS where ES modules can only import a default export from a CommonJS - * dependency. - * - * If you set `esmExternals` to `true`, this plugins assumes that all - * external dependencies are ES modules and respect the - * `requireReturnsDefault` option. If that option is not set, they will be - * rendered as namespace imports. - * - * You can also supply an array of ids to be treated as ES modules, or a - * function that will be passed each external id to determine if it is an ES - * module. - * @default false - */ - esmExternals?: boolean | ReadonlyArray | ((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 - * modules. By default, this plugin will render those imports as namespace - * imports i.e. - * - * ```js - * // input - * const foo = require('foo'); - * - * // output - * import * as foo from 'foo'; - * ``` - * - * However there are some situations where this may not be desired. - * For these situations, you can change Rollup's behaviour either globally or - * per module. To change it globally, set the `requireReturnsDefault` option - * to one of the following values: - * - * - `false`: This is the default, requiring an ES module returns its - * namespace. This is the only option that will also add a marker - * `__esModule: true` to the namespace to support interop patterns in - * CommonJS modules that are transpiled ES modules. - * - `"namespace"`: Like `false`, requiring an ES module returns its - * namespace, but the plugin does not add the `__esModule` marker and thus - * creates more efficient code. For external dependencies when using - * `esmExternals: true`, no additional interop code is generated. - * - `"auto"`: This is complementary to how `output.exports: "auto"` works in - * Rollup: If a module has a default export and no named exports, requiring - * that module returns the default export. In all other cases, the namespace - * is returned. For external dependencies when using `esmExternals: true`, a - * corresponding interop helper is added. - * - `"preferred"`: If a module has a default export, requiring that module - * always returns the default export, no matter whether additional named - * exports exist. This is similar to how previous versions of this plugin - * worked. Again for external dependencies when using `esmExternals: true`, - * an interop helper is added. - * - `true`: This will always try to return the default export on require - * without checking if it actually exists. This can throw at build time if - * there is no default export. This is how external dependencies are handled - * when `esmExternals` is not used. The advantage over the other options is - * that, like `false`, this does not add an interop helper for external - * dependencies, keeping the code lean. - * - * To change this for individual modules, you can supply a function for - * `requireReturnsDefault` instead. This function will then be called once for - * each required ES module or external dependency with the corresponding id - * and allows you to return different values for different modules. - * @default false - */ - requireReturnsDefault?: - | boolean - | 'auto' - | 'preferred' - | 'namespace' - | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace') - - /** - * @default "auto" - */ - defaultIsModuleExports?: boolean | 'auto' | ((id: string) => boolean | 'auto') - /** - * Some modules contain dynamic `require` calls, or require modules that - * contain circular dependencies, which are not handled well by static - * imports. Including those modules as `dynamicRequireTargets` will simulate a - * CommonJS (NodeJS-like) environment for them with support for dynamic - * dependencies. It also enables `strictRequires` for those modules. - * - * Note: In extreme cases, this feature may result in some paths being - * rendered as absolute in the final bundle. The plugin tries to avoid - * exposing paths from the local machine, but if you are `dynamicRequirePaths` - * 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 - /** - * To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory - * that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` - * may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your - * home directory name. By default it uses the current working directory. - */ - dynamicRequireRoot?: string -} +export type { RollupCommonJSOptions } from '../dist/node' diff --git a/packages/vite/types/connect.d.ts b/packages/vite/types/connect.d.ts index 74c559b6a436f5..50502555f0f56c 100644 --- a/packages/vite/types/connect.d.ts +++ b/packages/vite/types/connect.d.ts @@ -1,111 +1 @@ -// Inlined to avoid extra dependency -// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE - -// Type definitions for connect v3.4.0 -// Project: https://github.com/senchalabs/connect -// Definitions by: Maxime LUCE -// Evan Hahn -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -import * as http from 'node:http' - -export namespace Connect { - export type ServerHandle = HandleFunction | http.Server - - export class IncomingMessage extends http.IncomingMessage { - originalUrl?: http.IncomingMessage['url'] | undefined - } - - 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 interface ServerStackItem { - route: string - handle: ServerHandle - } - - export interface Server extends NodeJS.EventEmitter { - (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void - - route: string - stack: ServerStackItem[] - - /** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * 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 - - /** - * Handle server requests, punting them down - * the middleware stack. - */ - handle( - req: http.IncomingMessage, - res: http.ServerResponse, - next: Function - ): void - - /** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = 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 - } -} +export type { Connect } from '../dist/node' diff --git a/packages/vite/types/customEvent.d.ts b/packages/vite/types/customEvent.d.ts index af4db5d14fbe97..09fd7dc36ea481 100644 --- a/packages/vite/types/customEvent.d.ts +++ b/packages/vite/types/customEvent.d.ts @@ -1,16 +1 @@ -import type { - ErrorPayload, - FullReloadPayload, - PrunePayload, - UpdatePayload -} from './hmrPayload' - -export interface CustomEventMap { - 'vite:beforeUpdate': UpdatePayload - 'vite:beforePrune': PrunePayload - 'vite:beforeFullReload': FullReloadPayload - 'vite:error': ErrorPayload -} - -export type InferCustomEventPayload = - T extends keyof CustomEventMap ? CustomEventMap[T] : any +export type { CustomEventMap, InferCustomEventPayload } from '../client/types' diff --git a/packages/vite/types/dynamicImportVars.d.ts b/packages/vite/types/dynamicImportVars.d.ts index 99f1b5c453ba97..2d46aaf582de8b 100644 --- a/packages/vite/types/dynamicImportVars.d.ts +++ b/packages/vite/types/dynamicImportVars.d.ts @@ -1,17 +1 @@ -export interface RollupDynamicImportVarsOptions { - /** - * Files to include in this plugin (default all). - * @default [] - */ - include?: string | RegExp | (string | RegExp)[] - /** - * Files to exclude in this plugin (default none). - * @default [] - */ - 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 -} +export type { RollupDynamicImportVarsOptions } from '../dist/node' diff --git a/packages/vite/types/hmrPayload.d.ts b/packages/vite/types/hmrPayload.d.ts index 839095009e76fb..8bbb5e2fdf3e57 100644 --- a/packages/vite/types/hmrPayload.d.ts +++ b/packages/vite/types/hmrPayload.d.ts @@ -1,61 +1,10 @@ -export type HMRPayload = - | ConnectedPayload - | UpdatePayload - | FullReloadPayload - | CustomPayload - | ErrorPayload - | PrunePayload - -export interface ConnectedPayload { - type: 'connected' -} - -export interface UpdatePayload { - type: 'update' - updates: Update[] -} - -export interface Update { - type: 'js-update' | 'css-update' - path: string - acceptedPath: string - timestamp: number - /** - * @experimental internal - */ - explicitImportRequired?: boolean | undefined -} - -export interface PrunePayload { - type: 'prune' - paths: string[] -} - -export interface FullReloadPayload { - type: 'full-reload' - path?: string -} - -export interface CustomPayload { - type: 'custom' - event: string - data?: any -} - -export interface ErrorPayload { - type: 'error' - err: { - [name: string]: any - message: string - stack: string - id?: string - frame?: string - plugin?: string - pluginCode?: string - loc?: { - file?: string - line: number - column: number - } - } -} +export type { + HMRPayload, + ConnectedPayload, + UpdatePayload, + Update, + PrunePayload, + FullReloadPayload, + CustomPayload, + ErrorPayload +} from '../client/types' diff --git a/packages/vite/types/hot.d.ts b/packages/vite/types/hot.d.ts index 985f3a47197c43..83727b7019997e 100644 --- a/packages/vite/types/hot.d.ts +++ b/packages/vite/types/hot.d.ts @@ -1,33 +1 @@ -import type { InferCustomEventPayload } from './customEvent' - -export type ModuleNamespace = Record & { - [Symbol.toStringTag]: 'Module' -} - -export interface ViteHotContext { - readonly data: any - - accept(): void - accept(cb: (mod: ModuleNamespace | undefined) => void): void - accept(dep: string, cb: (mod: ModuleNamespace | undefined) => void): void - accept( - deps: readonly string[], - cb: (mods: Array) => void - ): void - - acceptExports(exportNames: string | readonly string[]): void - acceptExports( - exportNames: string | readonly string[], - cb: (mod: ModuleNamespace | undefined) => void - ): void - - dispose(cb: (data: any) => void): void - decline(): void - invalidate(): void - - on( - event: T, - cb: (payload: InferCustomEventPayload) => void - ): void - send(event: T, data?: InferCustomEventPayload): void -} +export type { ModuleNamespace, ViteHotContext } from '../client/types' diff --git a/packages/vite/types/http-proxy.d.ts b/packages/vite/types/http-proxy.d.ts index 1cae820dcdfa8f..54bbefc05c8c48 100644 --- a/packages/vite/types/http-proxy.d.ts +++ b/packages/vite/types/http-proxy.d.ts @@ -1,250 +1 @@ -// Inlined to avoid extra dependency -// MIT Licensed https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/LICENSE - -// Type definitions for node-http-proxy 1.17 -// Project: https://github.com/nodejitsu/node-http-proxy -// Definitions by: Maxime LUCE -// Florian Oellerich -// Daniel Schmidt -// Jordan Abreu -// Samuel Bodin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -/// - -import type * as net from 'node:net' -import type * as http from 'node:http' -import * as events from 'node:events' -import type * as url from 'node:url' -import type * as stream from 'node:stream' - -export namespace HttpProxy { - export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed - - export type ProxyTargetUrl = string | Partial - - export interface ProxyTargetDetailed { - host: string - port: number - protocol?: string | undefined - hostname?: string | undefined - socketPath?: string | undefined - key?: string | undefined - passphrase?: string | undefined - pfx?: Buffer | string | undefined - cert?: string | undefined - ca?: string | undefined - ciphers?: string | undefined - secureProtocol?: string | undefined - } - - 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) - - /** - * Used for proxying regular HTTP(S) requests - * @param req - Client request. - * @param res - Client response. - * @param options - Additional options. - */ - web( - req: http.IncomingMessage, - res: http.ServerResponse, - options?: ServerOptions, - callback?: ErrorCallback - ): void - - /** - * Used for proxying regular HTTP(S) requests - * @param req - Client request. - * @param socket - Client socket. - * @param head - Client head. - * @param options - Additional options. - */ - 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 - - /** - * A function that closes the inner webserver and stops listening on given port - */ - 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 - - /** - * 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 - - /** - * 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 - - 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 - } - - export interface ServerOptions { - /** URL string to be parsed with the url module. */ - target?: ProxyTarget | undefined - /** URL string to be parsed with the url module. */ - forward?: ProxyTargetUrl | undefined - /** Object to be passed to http(s).request. */ - agent?: any - /** Object to be passed to https.createServer(). */ - ssl?: any - /** If you want to proxy websockets. */ - ws?: boolean | undefined - /** Adds x- forward headers. */ - xfwd?: boolean | undefined - /** Verify SSL certificate. */ - secure?: boolean | undefined - /** Explicitly specify if we are proxying to another proxy. */ - toProxy?: boolean | undefined - /** Specify whether you want to prepend the target's path to the proxy path. */ - prependPath?: boolean | undefined - /** Specify whether you want to ignore the proxy path of the incoming request. */ - ignorePath?: boolean | undefined - /** Local interface string to bind for outgoing connections. */ - localAddress?: string | undefined - /** Changes the origin of the host header to the target URL. */ - changeOrigin?: boolean | undefined - /** specify whether you want to keep letter case of response header key */ - preserveHeaderKeyCase?: boolean | undefined - /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ - auth?: string | undefined - /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ - hostRewrite?: string | undefined - /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ - autoRewrite?: boolean | undefined - /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ - protocolRewrite?: string | undefined - /** rewrites domain of set-cookie headers. */ - cookieDomainRewrite?: - | false - | string - | { [oldDomain: string]: string } - | undefined - /** rewrites path of set-cookie headers. Default: false */ - cookiePathRewrite?: - | false - | string - | { [oldPath: string]: string } - | undefined - /** object with extra headers to be added to target requests. */ - headers?: { [header: string]: string } | undefined - /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ - proxyTimeout?: number | undefined - /** Timeout (in milliseconds) for incoming requests */ - timeout?: number | undefined - /** Specify whether you want to follow redirects. Default: false */ - followRedirects?: boolean | undefined - /** 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 | undefined - /** Buffer */ - buffer?: stream.Stream | undefined - } -} +export type { HttpProxy } from '../dist/node' diff --git a/packages/vite/types/importGlob.d.ts b/packages/vite/types/importGlob.d.ts index 321e3804a7e09a..7951020049d0dc 100644 --- a/packages/vite/types/importGlob.d.ts +++ b/packages/vite/types/importGlob.d.ts @@ -1,97 +1,7 @@ -export interface ImportGlobOptions< - Eager extends boolean, - AsType extends string -> { - /** - * Import type for the import url. - */ - as?: AsType - /** - * Import as static or dynamic - * - * @default false - */ - eager?: Eager - /** - * Import only the specific named export. Set to `default` to import the default export. - */ - import?: string - /** - * Custom queries - */ - query?: string | Record - /** - * Search files also inside `node_modules/` and hidden directories (e.g. `.git/`). This might have impact on performance. - * - * @default false - */ - exhaustive?: boolean -} - -export type GeneralImportGlobOptions = ImportGlobOptions - -export interface KnownAsTypeMap { - raw: string - url: string - worker: Worker -} - -export interface ImportGlobFunction { - /** - * Import a list of files with a glob pattern. - * - * Overload 1: No generic provided, infer the type from `eager` and `as` - */ - < - Eager extends boolean, - As extends string, - T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown - >( - glob: string | string[], - options?: ImportGlobOptions - ): (Eager extends true ? true : false) extends true - ? Record - : Record Promise> - /** - * Import a list of files with a glob pattern. - * - * Overload 2: Module generic provided, infer the type from `eager: false` - */ - ( - glob: string | string[], - options?: ImportGlobOptions - ): Record Promise> - /** - * Import a list of files with a glob pattern. - * - * Overload 3: Module generic provided, infer the type from `eager: true` - */ - ( - glob: string | string[], - options: ImportGlobOptions - ): Record -} - -export interface ImportGlobEagerFunction { - /** - * Eagerly import a list of files with a glob pattern. - * - * Overload 1: No generic provided, infer the type from `as` - */ - < - As extends string, - T = As extends keyof KnownAsTypeMap ? KnownAsTypeMap[As] : unknown - >( - glob: string | string[], - options?: Omit, 'eager'> - ): Record - /** - * Eagerly import a list of files with a glob pattern. - * - * Overload 2: Module generic provided - */ - ( - glob: string | string[], - options?: Omit, 'eager'> - ): Record -} +export type { + ImportGlobOptions, + GeneralImportGlobOptions, + KnownAsTypeMap, + ImportGlobFunction, + ImportGlobEagerFunction +} from '../client/types' diff --git a/packages/vite/types/importMeta.d.ts b/packages/vite/types/importMeta.d.ts index 54eaa9f4c4c140..97a9518f5d8e4f 100644 --- a/packages/vite/types/importMeta.d.ts +++ b/packages/vite/types/importMeta.d.ts @@ -1,35 +1,13 @@ -// This file is an augmentation to the built-in ImportMeta interface -// Thus cannot contain any top-level imports -// - -/* eslint-disable @typescript-eslint/consistent-type-imports */ - -// Duplicate of import('../src/node/importGlob').GlobOptions in order to -// avoid breaking the production client type. Because this file is referenced -// in vite/client.d.ts and in production src/node/importGlob.ts doesn't exist. -interface GlobOptions { - as?: string -} - -interface ImportMeta { - url: string - - readonly hot?: import('./hot').ViteHotContext - - readonly env: ImportMetaEnv - - glob: import('./importGlob').ImportGlobFunction - /** - * @deprecated Use `import.meta.glob('*', { eager: true })` instead - */ - globEager: import('./importGlob').ImportGlobEagerFunction -} - -interface ImportMetaEnv { - [key: string]: any - BASE_URL: string - MODE: string - DEV: boolean - PROD: boolean - SSR: boolean +import type { + ImportMeta as ViteImportMeta, + ImportMetaEnv as ViteImportMetaEnv +} from '../client/types' + +declare global { + interface GlobOptions { + as?: string + } + + interface ImportMeta extends ViteImportMeta {} + interface ImportMetaEnv extends ViteImportMetaEnv {} } diff --git a/packages/vite/types/terser.d.ts b/packages/vite/types/terser.d.ts index a704a20cdc71ae..695795d4df448f 100644 --- a/packages/vite/types/terser.d.ts +++ b/packages/vite/types/terser.d.ts @@ -1,250 +1 @@ -// Modified and inlined to avoid extra dependency -// Source: https://github.com/terser/terser/blob/master/tools/terser.d.ts -// BSD Licensed https://github.com/terser/terser/blob/master/LICENSE - -/* -Terser is released under the BSD license: - -Copyright 2012-2018 (c) Mihai Bazon - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, -OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR -TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. -*/ - -export namespace Terser { - export type ECMA = 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 - - export interface ParseOptions { - bare_returns?: boolean - /** @deprecated legacy option. Currently, all supported EcmaScript is valid to parse. */ - 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 - } - - export enum InlineFunctions { - Disabled = 0, - SimpleFunctions = 1, - WithArguments = 2, - WithArgumentsAndVariables = 3 - } - - export interface MangleOptions { - eval?: boolean - keep_classnames?: boolean | RegExp - keep_fnames?: boolean | RegExp - module?: boolean - nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler - properties?: boolean | ManglePropertiesOptions - reserved?: string[] - safari10?: boolean - toplevel?: boolean - } - - /** - * An identifier mangler for which the output is invariant with respect to the source code. - */ - export interface SimpleIdentifierMangler { - /** - * Obtains the nth most favored (usually shortest) identifier to rename a variable to. - * The mangler will increment n and retry until the return value is not in use in scope, and is not a reserved word. - * This function is expected to be stable; Evaluating get(n) === get(n) should always return true. - * @param n - The ordinal of the identifier. - */ - get(n: number): string - } - - /** - * An identifier mangler that leverages character frequency analysis to determine identifier precedence. - */ - export interface WeightedIdentifierMangler extends SimpleIdentifierMangler { - /** - * Modifies the internal weighting of the input characters by the specified delta. - * Will be invoked on the entire printed AST, and then deduct mangleable identifiers. - * @param chars - The characters to modify the weighting of. - * @param delta - The numeric weight to add to the characters. - */ - consider(chars: string, delta: number): number - /** - * Resets character weights. - */ - reset(): void - /** - * Sorts identifiers by character frequency, in preparation for calls to get(n). - */ - sort(): void - } - - export interface ManglePropertiesOptions { - builtins?: boolean - debug?: boolean - keep_quoted?: boolean | 'strict' - nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler - regex?: RegExp | string - reserved?: string[] - } - - export interface FormatOptions { - ascii_only?: boolean - /** @deprecated Not implemented anymore */ - beautify?: boolean - braces?: boolean - comments?: - | boolean - | 'all' - | 'some' - | RegExp - | (( - node: any, - comment: { - value: string - type: 'comment1' | 'comment2' | 'comment3' | 'comment4' - pos: number - line: number - col: number - } - ) => boolean) - ecma?: ECMA - ie8?: boolean - keep_numbers?: 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 - } - - export interface MinifyOptions { - compress?: boolean | CompressOptions - ecma?: ECMA - enclose?: boolean | string - ie8?: boolean - keep_classnames?: boolean | RegExp - keep_fnames?: boolean | RegExp - mangle?: boolean | MangleOptions - module?: boolean - nameCache?: object - format?: FormatOptions - /** @deprecated deprecated */ - output?: FormatOptions - parse?: ParseOptions - safari10?: boolean - sourceMap?: boolean | SourceMapOptions - toplevel?: boolean - } - - export interface MinifyOutput { - code?: string - map?: object | string - decoded_map?: object | null - } - - export interface SourceMapOptions { - /** Source map object, 'inline' or source map file content */ - content?: object | string - includeSources?: boolean - filename?: string - root?: string - url?: string | 'inline' - } -} +export type { Terser } from '../dist/node' diff --git a/packages/vite/types/ws.d.ts b/packages/vite/types/ws.d.ts index a06341fca9eeb9..3916212d392bff 100644 --- a/packages/vite/types/ws.d.ts +++ b/packages/vite/types/ws.d.ts @@ -1,553 +1 @@ -// Modified and inlined to avoid extra dependency -// Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts - -// Type definitions for ws 8.5 -// Project: https://github.com/websockets/ws -// Definitions by: Paul Loyd -// Margus Lamp -// Philippe D'Alva -// reduckted -// teidesu -// Bartosz Wojtkowiak -// Kyle Hensel -// Samuel Skeen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import { EventEmitter } from 'node:events' -import type { - Agent, - ClientRequest, - ClientRequestArgs, - Server as HTTPServer, - IncomingMessage, - OutgoingHttpHeaders -} from 'node:http' -import type { Server as HTTPSServer } from 'node:https' -import type { Duplex, DuplexOptions } from 'node:stream' -import type { SecureContextOptions } from 'node:tls' -import type { URL } from 'node:url' -import type { ZlibOptions } from 'node:zlib' - -// WebSocket socket. -declare class WebSocket extends EventEmitter { - /** The connection is not yet open. */ - static readonly CONNECTING: 0 - /** The connection is open and ready to communicate. */ - static readonly OPEN: 1 - /** The connection is in the process of closing. */ - static readonly CLOSING: 2 - /** The connection is closed. */ - static readonly CLOSED: 3 - - binaryType: 'nodebuffer' | 'arraybuffer' | 'fragments' - readonly bufferedAmount: number - readonly extensions: string - /** Indicates whether the websocket is paused */ - readonly isPaused: boolean - 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 - - /** The connection is not yet open. */ - readonly CONNECTING: 0 - /** The connection is open and ready to communicate. */ - readonly OPEN: 1 - /** The connection is in the process of closing. */ - readonly CLOSING: 2 - /** The connection is closed. */ - readonly CLOSED: 3 - - onopen: ((event: WebSocket.Event) => void) | null - onerror: ((event: WebSocket.ErrorEvent) => void) | null - onclose: ((event: WebSocket.CloseEvent) => void) | null - onmessage: ((event: WebSocket.MessageEvent) => void) | null - - constructor(address: null) - constructor( - address: string | URL, - options?: WebSocket.ClientOptions | ClientRequestArgs - ) - constructor( - address: string | URL, - protocols?: string | string[], - options?: WebSocket.ClientOptions | ClientRequestArgs - ) - - close(code?: number, data?: string | Buffer): 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 - }, - cb?: (err?: Error) => void - ): void - terminate(): void - - /** - * Pause the websocket causing it to stop emitting events. Some events can still be - * emitted after this is called, until all buffered data is consumed. This method - * is a noop if the ready state is `CONNECTING` or `CLOSED`. - */ - pause(): void - /** - * Make a paused socket resume emitting events. This method is a noop if the ready - * state is `CONNECTING` or `CLOSED`. - */ - resume(): void - - // HTML5 WebSocket events - addEventListener( - method: 'message', - cb: (event: WebSocket.MessageEvent) => void, - options?: WebSocket.EventListenerOptions - ): void - addEventListener( - method: 'close', - cb: (event: WebSocket.CloseEvent) => void, - options?: WebSocket.EventListenerOptions - ): void - addEventListener( - method: 'error', - cb: (event: WebSocket.ErrorEvent) => void, - options?: WebSocket.EventListenerOptions - ): void - addEventListener( - method: 'open', - cb: (event: WebSocket.Event) => void, - options?: WebSocket.EventListenerOptions - ): void - - removeEventListener( - method: 'message', - cb: (event: WebSocket.MessageEvent) => void - ): void - removeEventListener( - method: 'close', - cb: (event: WebSocket.CloseEvent) => void - ): void - removeEventListener( - method: 'error', - cb: (event: WebSocket.ErrorEvent) => void - ): void - removeEventListener( - method: 'open', - cb: (event: WebSocket.Event) => void - ): void - - // Events - on( - event: 'close', - listener: (this: WebSocket, code: number, reason: Buffer) => 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.RawData, - isBinary: boolean - ) => 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: Buffer) => 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.RawData, - isBinary: boolean - ) => 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: Buffer) => 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.RawData, - isBinary: boolean - ) => 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, reason: Buffer) => void - ): this - addListener(event: 'error', listener: (err: Error) => void): this - addListener( - event: 'upgrade', - listener: (request: IncomingMessage) => void - ): this - addListener( - event: 'message', - listener: (data: WebSocket.RawData, isBinary: boolean) => 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, reason: Buffer) => void - ): this - removeListener(event: 'error', listener: (err: Error) => void): this - removeListener( - event: 'upgrade', - listener: (request: IncomingMessage) => void - ): this - removeListener( - event: 'message', - listener: (data: WebSocket.RawData, isBinary: boolean) => 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 -} - -declare const WebSocketAlias: typeof WebSocket -interface WebSocketAlias extends WebSocket {} // tslint:disable-line no-empty-interface - -declare namespace WebSocket { - /** - * Data represents the raw message payload received over the WebSocket. - */ - type RawData = Buffer | ArrayBuffer | Buffer[] - - /** - * Data represents the message payload received over the WebSocket. - */ - type Data = string | Buffer | ArrayBuffer | Buffer[] - - /** - * CertMeta represents the accepted types for certificate & key data. - */ - 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 - - /** - * VerifyClientCallbackAsync is an asynchronous callback used to inspect the - * incoming message. The return value (boolean) of the function determines - * whether or not to accept the handshake. - */ - type VerifyClientCallbackAsync = ( - info: { origin: string; secure: boolean; req: IncomingMessage }, - callback: ( - res: boolean, - code?: number, - message?: string, - headers?: OutgoingHttpHeaders - ) => void - ) => void - - interface ClientOptions extends SecureContextOptions { - protocol?: string | undefined - followRedirects?: boolean | undefined - generateMask?(mask: Buffer): void - 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 - skipUTF8Validation?: boolean | undefined - } - - interface PerMessageDeflateOptions { - 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 - } - | undefined - zlibInflateOptions?: ZlibOptions | undefined - threshold?: number | undefined - concurrencyLimit?: number | undefined - } - - interface Event { - type: string - target: WebSocket - } - - interface ErrorEvent { - error: any - message: string - type: string - target: WebSocket - } - - interface CloseEvent { - wasClean: boolean - code: number - reason: string - type: string - target: WebSocket - } - - interface MessageEvent { - data: Data - type: string - target: WebSocket - } - - interface EventListenerOptions { - once?: boolean | undefined - } - - interface ServerOptions { - host?: string | undefined - port?: number | undefined - backlog?: number | undefined - server?: HTTPServer | HTTPSServer | undefined - verifyClient?: - | VerifyClientCallbackAsync - | VerifyClientCallbackSync - | undefined - handleProtocols?: ( - protocols: Set, - request: IncomingMessage - ) => string | false - path?: string | undefined - noServer?: boolean | undefined - clientTracking?: boolean | undefined - perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined - maxPayload?: number | undefined - skipUTF8Validation?: boolean | undefined - WebSocket?: typeof WebSocket.WebSocket | undefined - } - - interface AddressInfo { - address: string - family: string - port: number - } - - // WebSocket Server - class Server extends EventEmitter { - options: ServerOptions - path: string - clients: Set - - constructor(options?: ServerOptions, callback?: () => void) - - address(): AddressInfo | string - close(cb?: (err?: Error) => void): void - handleUpgrade( - request: IncomingMessage, - socket: Duplex, - upgradeHead: Buffer, - callback: (client: T, request: IncomingMessage) => void - ): void - shouldHandle(request: IncomingMessage): boolean | Promise - - // Events - on( - event: 'connection', - cb: (this: Server, socket: T, 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: T, 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: (this: Server, ...args: any[]) => void - ): this - - off( - event: 'connection', - cb: (this: Server, socket: T, 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: T, 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: T) => 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 - } - - const WebSocketServer: typeof Server - interface WebSocketServer extends Server {} // tslint:disable-line no-empty-interface - const WebSocket: typeof WebSocketAlias - interface WebSocket extends WebSocketAlias {} // tslint:disable-line no-empty-interface - - // WebSocket stream - function createWebSocketStream( - websocket: WebSocket, - options?: DuplexOptions - ): Duplex -} - -// export = WebSocket -export { WebSocket, WebSocketAlias } +export type { WebSocket, WebSocketAlias } from '../dist/node' diff --git a/playground/hmr/event.d.ts b/playground/hmr/event.d.ts index 151a9cc3b861cd..5b4818294ed744 100644 --- a/playground/hmr/event.d.ts +++ b/playground/hmr/event.d.ts @@ -1,9 +1,16 @@ -import 'vite/types/customEvent' +import 'vite' +import 'vite/client/types' -declare module 'vite/types/customEvent' { - interface CustomEventMap { - 'custom:foo': { msg: string } - 'custom:remote-add': { a: number; b: number } - 'custom:remote-add-result': { result: string } - } +interface MyCustomEventMap { + 'custom:foo': { msg: string } + 'custom:remote-add': { a: number; b: number } + 'custom:remote-add-result': { result: string } +} + +declare module 'vite' { + interface CustomEventMap extends MyCustomEventMap {} +} + +declare module 'vite/client/types' { + interface CustomEventMap extends MyCustomEventMap {} } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dea753ab70b7d2..3eeeda1cd37e39 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -233,6 +233,7 @@ importers: cors: ^2.8.5 cross-spawn: ^7.0.3 debug: ^4.3.4 + dep-types: link:./src/dep-types dotenv: ^14.3.2 dotenv-expand: ^5.1.0 es-module-lexer: ^1.0.3 @@ -268,7 +269,7 @@ importers: strip-literal: ^0.4.2 tsconfck: ^2.0.1 tslib: ^2.4.0 - types: link:./types + types: link:./src/types ufo: ^0.8.5 ws: ^8.9.0 dependencies: @@ -299,6 +300,7 @@ importers: cors: 2.8.5 cross-spawn: 7.0.3 debug: 4.3.4 + dep-types: link:src/dep-types dotenv: 14.3.2 dotenv-expand: 5.1.0 es-module-lexer: 1.0.3 @@ -329,7 +331,7 @@ importers: strip-literal: 0.4.2 tsconfck: 2.0.1 tslib: 2.4.0 - types: link:types + types: link:src/types ufo: 0.8.5 ws: 8.9.0