Compare commits

...

1 commit

Author SHA1 Message Date
Matthew Phillips
37ab8ba13c Update vite 2022-01-25 10:20:46 -05:00
25 changed files with 6630 additions and 16004 deletions

30
packages/astro/vendor/vite/dist/client/client.mjs vendored Executable file → Normal file
View file

@ -195,20 +195,15 @@ function warnFailedFetch(err, path) {
`This could be due to syntax errors or importing non-existent ` +
`modules. (see errors above)`);
}
function cleanUrl(pathname) {
const url = new URL(pathname, location.toString());
url.searchParams.delete('direct');
return url.pathname + url.search;
}
// Listen for messages
socket.addEventListener('message', async ({ data }) => {
handleMessage(JSON.parse(data));
});
/**
* This cleans up the query params and removes the `direct` param which is internal.
* Other query params are preserved.
*/
function cleanUrl(pathname) {
let url = new URL(pathname, location);
url.searchParams.delete('direct');
return url.pathname + url.search;
}
let isFirstUpdate = true;
async function handleMessage(payload) {
switch (payload.type) {
@ -239,19 +234,18 @@ async function handleMessage(payload) {
else {
// css-update
// this is only sent when a css file referenced with <link> is updated
let { path, timestamp } = update;
let searchUrl = cleanUrl(path);
const { path, timestamp } = update;
const searchUrl = cleanUrl(path);
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => {
return cleanUrl(e.href).includes(searchUrl)
});
const el = Array.from(document.querySelectorAll('link')).find((e) => cleanUrl(e.href).includes(searchUrl));
if (el) {
const newPath = `${base}${path.slice(1)}${path.includes('?') ? '&' : '?'}t=${timestamp}`;
const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`;
el.href = new URL(newPath, el.href).href;
}
console.log(`[vite] css hot updated: ${path}`);
console.log(`[vite] css hot updated: ${searchUrl}`);
notifyListeners('vite:afterUpdate:css', el);
}
});
break;
@ -389,8 +383,6 @@ function removeStyle(id) {
const style = sheetsMap.get(id);
if (style) {
if (style instanceof CSSStyleSheet) {
// @ts-ignore
document.adoptedStyleSheets.indexOf(style);
// @ts-ignore
document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style);
}

2
packages/astro/vendor/vite/dist/client/client.mjs.map vendored Executable file → Normal file

File diff suppressed because one or more lines are too long

0
packages/astro/vendor/vite/dist/client/env.mjs vendored Executable file → Normal file
View file

0
packages/astro/vendor/vite/dist/client/env.mjs.map vendored Executable file → Normal file
View file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -10,11 +10,11 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -743,4 +743,4 @@ var index = /*#__PURE__*/_mergeNamespaces({
}, [postcssImport]);
exports.index = index;
//# sourceMappingURL=dep-e39b05d6.js.map
//# sourceMappingURL=dep-2d8e2cb1.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,15 +1,15 @@
'use strict';
var build = require('./dep-35df7f96.js');
var build = require('./dep-ac6ff16a.js');
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -376,12 +376,12 @@ function escapeHtml(string) {
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
html += str.slice(lastIndex, index);
}
lastIndex = index + 1;
html += escaped;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
}
// https://www.w3.org/TR/html52/syntax.html#comments
const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
@ -476,17 +476,6 @@ const replacer = (_key, val) => {
return val;
};
/**
* List of @babel/parser plugins that are used for template expression
* transforms and SFC script transforms. By default we enable proposals slated
* for ES2020. This will need to be updated as the spec moves forward.
* Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
*/
const babelParserDefaultPlugins = [
'bigInt',
'optionalChaining',
'nullishCoalescingOperator'
];
const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
? Object.freeze({})
: {};
@ -603,7 +592,6 @@ var shared_esmBundler = {
NO: NO,
NOOP: NOOP,
PatchFlagNames: PatchFlagNames,
babelParserDefaultPlugins: babelParserDefaultPlugins,
camelize: camelize$1,
capitalize: capitalize,
def: def,
@ -1110,7 +1098,7 @@ const isMemberExpressionNode = NOOP
const isMemberExpression = isMemberExpressionBrowser
;
function getInnerRange(loc, offset, length) {
const source = loc.source.substr(offset, length);
const source = loc.source.slice(offset, offset + length);
const newLoc = {
source,
start: advancePositionWithClone(loc.start, loc.source, offset),
@ -1870,6 +1858,7 @@ function parseTag(context, type, parent) {
}
if (hasIf && hasFor) {
warnDeprecation("COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */, context, getSelection(context, start));
break;
}
}
}
@ -2027,10 +2016,10 @@ function parseAttribute(context, nameSet) {
isStatic = false;
if (!content.endsWith(']')) {
emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
content = content.substr(1);
content = content.slice(1);
}
else {
content = content.substr(1, content.length - 2);
content = content.slice(1, content.length - 1);
}
}
else if (isSlot) {
@ -2056,7 +2045,7 @@ function parseAttribute(context, nameSet) {
valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
valueLoc.source = valueLoc.source.slice(1, -1);
}
const modifiers = match[3] ? match[3].substr(1).split('.') : [];
const modifiers = match[3] ? match[3].slice(1).split('.') : [];
if (isPropShorthand)
modifiers.push('prop');
// 2.x compat v-bind:foo.sync -> v-model:foo
@ -2277,7 +2266,7 @@ function isEnd(context, mode, ancestors) {
}
function startsWithEndTagOpen(source, tag) {
return (startsWith(source, '</') &&
source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
/[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
}
@ -4865,7 +4854,7 @@ function stringifyDynamicPropNames(props) {
return propsNamesString + `]`;
}
function isComponentTag(tag) {
return tag[0].toLowerCase() + tag.slice(1) === 'component';
return tag === 'component' || tag === 'Component';
}
(process.env.NODE_ENV !== 'production')
@ -7933,7 +7922,7 @@ const decodeHtml = (rawText, asAttr) => {
maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
}
for (let length = maxCRNameLength; !value && length > 0; --length) {
name = rawText.substr(1, length);
name = rawText.slice(1, 1 + length);
value = namedCharacterReferences[name];
}
if (value) {
@ -8731,4 +8720,4 @@ var compilerDom_cjs$1 = /*#__PURE__*/_mergeNamespaces({
}, [compilerDom_cjs$2]);
exports.compilerDom_cjs = compilerDom_cjs$1;
//# sourceMappingURL=dep-a5b4350d.js.map
//# sourceMappingURL=dep-59e05bf6.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

0
packages/astro/vendor/vite/dist/node/chunks/dep-ac1b4bf9.js vendored Executable file → Normal file
View file

0
packages/astro/vendor/vite/dist/node/chunks/dep-ac1b4bf9.js.map vendored Executable file → Normal file
View file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,6 @@
'use strict';
var build = require('./dep-35df7f96.js');
var build = require('./dep-ac6ff16a.js');
var require$$1 = require('crypto');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
@ -8,11 +8,11 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
function _mergeNamespaces(n, m) {
for (var i = 0; i < m.length; i++) {
var e = m[i];
for (var k in e) {
if (typeof e !== 'string' && !Array.isArray(e)) { for (var k in e) {
if (k !== 'default' && !(k in n)) {
n[k] = e[k];
}
}
} }
}
return n;
}
@ -29179,4 +29179,4 @@ var index = /*#__PURE__*/_mergeNamespaces({
}, [selfsigned]);
exports.index = index;
//# sourceMappingURL=dep-34d2edc0.js.map
//# sourceMappingURL=dep-d7c10dfc.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

67
packages/astro/vendor/vite/dist/node/cli.js vendored Executable file → Normal file
View file

@ -1,30 +1,31 @@
'use strict';
var require$$0 = require('events');
var build = require('./chunks/dep-35df7f96.js');
var build = require('./chunks/dep-ac6ff16a.js');
var perf_hooks = require('perf_hooks');
require('fs');
require('path');
require('util');
require('stream');
require('os');
require('url');
require('crypto');
require('module');
require('esbuild');
require('worker_threads');
require('assert');
require('child_process');
require('readline');
require('zlib');
require('resolve');
require('querystring');
require('tty');
require('util');
require('net');
require('url');
require('http');
require('buffer');
require('stream');
require('resolve');
require('module');
require('https');
require('zlib');
require('crypto');
require('tls');
require('assert');
require('buffer');
require('querystring');
require('esbuild');
require('child_process');
require('json5');
require('worker_threads');
require('readline');
function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
@ -373,7 +374,10 @@ class Command {
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
});
}
const options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
if (!this.isGlobalCommand && !this.isDefaultCommand) {
options = options.filter((option) => option.name !== "version");
}
if (options.length > 0) {
const longestOptionName = findLongest(options.map((option) => option.rawName));
sections.push({
@ -550,7 +554,7 @@ class CAC extends require$$0.EventEmitter {
run = false;
this.unsetMatchedCommand();
}
if (this.options.version && this.showVersionOnExit) {
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
this.outputVersion();
run = false;
this.unsetMatchedCommand();
@ -645,8 +649,6 @@ function cleanOptions(options) {
delete ret['--'];
delete ret.c;
delete ret.config;
delete ret.r;
delete ret.root;
delete ret.base;
delete ret.l;
delete ret.logLevel;
@ -661,7 +663,6 @@ function cleanOptions(options) {
}
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('-r, --root <path>', `[string] use specified root directory`)
.option('--base <path>', `[string] public base path (default: /)`)
.option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
@ -671,7 +672,8 @@ cli
// dev
cli
.command('[root]') // default command
.alias('serve')
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
@ -682,7 +684,7 @@ cli
.action(async (root, options) => {
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.index$1; });
const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-ac6ff16a.js'); }).then(function (n) { return n.index$1; });
try {
const server = await createServer({
root,
@ -731,7 +733,7 @@ cli
.option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
.action(async (root, options) => {
const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.build$1; });
const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-ac6ff16a.js'); }).then(function (n) { return n.build$1; });
const buildOptions = cleanOptions(options);
try {
await build$1({
@ -754,7 +756,7 @@ cli
.command('optimize [root]')
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
.action(async (root, options) => {
const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-35df7f96.js'); }).then(function (n) { return n.index; });
const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-ac6ff16a.js'); }).then(function (n) { return n.index; });
try {
const config = await build.resolveConfig({
root,
@ -773,24 +775,25 @@ cli
.command('preview [root]')
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.action(async (root, options) => {
try {
const config = await build.resolveConfig({
const server = await build.preview({
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel,
server: {
open: options.open,
preview: {
port: options.port,
strictPort: options.strictPort,
https: options.https
host: options.host,
https: options.https,
open: options.open
}
}, 'serve', 'production');
const server = await build.preview(config, cleanOptions(options));
build.printHttpServerUrls(server, config);
});
server.printUrls();
}
catch (e) {
build.createLogger(options.logLevel).error(build.source.red(`error when starting preview server:\n${e.stack}`), { error: e });

2
packages/astro/vendor/vite/dist/node/cli.js.map vendored Executable file → Normal file

File diff suppressed because one or more lines are too long

254
packages/astro/vendor/vite/dist/node/index.d.ts vendored Executable file → Normal file
View file

@ -12,11 +12,11 @@ import { EventEmitter } from 'events';
import * as events from 'events';
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import { IncomingMessage } from 'http';
import { InputOptions } from 'rollup';
import { LoadResult } from 'rollup';
import { ModuleFormat } from 'rollup';
import { ModuleInfo } from 'rollup';
import * as net from 'net';
import { OutgoingHttpHeaders } from 'http';
import { OutputBundle } from 'rollup';
@ -33,8 +33,9 @@ import { RollupOutput } from 'rollup';
import { RollupWatcher } from 'rollup';
import { SecureContextOptions } from 'tls';
import { Server } from 'http';
import { Server as Server_2 } from 'https';
import { Server as Server_3 } from 'net';
import { Server as Server_2 } from 'net';
import { Server as Server_3 } from 'https';
import { ServerOptions as ServerOptions_2 } from 'https';
import { ServerResponse } from 'http';
import { Socket } from 'net';
import { SourceDescription } from 'rollup';
@ -46,6 +47,7 @@ import { TransformResult as TransformResult_3 } from 'rollup';
import { URL } from 'url';
import * as url from 'url';
import { WatcherOptions } from 'rollup';
import { WebSocketServer as WebSocketServer_2 } from 'ws';
import { ZlibOptions } from 'zlib';
export declare interface Alias {
@ -255,6 +257,63 @@ export declare interface BuildOptions {
watch?: WatcherOptions | null;
}
export declare interface CommonServerOptions {
/**
* Specify server port. Note if the port is already being used, Vite will
* automatically try the next available port so this may not be the actual
* port the server ends up listening on.
*/
port?: number;
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean;
/**
* Specify which IP addresses the server should listen on.
* Set to 0.0.0.0 to listen on all addresses, including LAN and public addresses.
*/
host?: string | boolean;
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | ServerOptions_2;
/**
* Open browser window on startup
*/
open?: boolean | string;
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>;
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean;
}
export declare interface ConfigEnv {
command: 'build' | 'serve';
mode: string;
@ -516,21 +575,28 @@ export declare interface FileSystemServeOptions {
* Strictly restrict file accessing outside of allowing paths.
*
* Set to `false` to disable the warning
* Default to false at this moment, will enabled by default in the future versions.
*
* @experimental
* @default undefined
* @default true
*/
strict?: boolean | undefined;
strict?: boolean;
/**
* Restrict accessing files outside the allowed directories.
*
* Accepts absolute path or a path relative to project root.
* Will try to search up for workspace root by default.
*/
allow?: string[];
/**
* Restrict accessing files that matches the patterns.
*
* This will have higher priority than `allow`.
* Glob patterns are supported.
*
* @default ['.env', '.env.*', '*.crt', '*.pem']
*
* @experimental
*/
allow?: string[];
deny?: string[];
}
export declare interface FSWatcher extends fs.FSWatcher {
@ -906,6 +972,7 @@ export declare interface InternalResolveOptions extends ResolveOptions {
isBuild: boolean;
isProduction: boolean;
ssrConfig?: SSROptions;
packageCache?: PackageCache;
/**
* src code mode also attempts the following:
* - resolving /xxx as URLs
@ -916,7 +983,10 @@ export declare interface InternalResolveOptions extends ResolveOptions {
tryPrefix?: string;
skipPackageJson?: boolean;
preferRelative?: boolean;
preserveSymlinks?: boolean;
isRequire?: boolean;
isFromTsImporter?: boolean;
tryEsmOnly?: boolean;
}
export declare interface JsonOptions {
@ -997,12 +1067,12 @@ export declare type Matcher = AnymatchPattern | AnymatchPattern[]
export declare function mergeConfig(a: Record<string, any>, b: Record<string, any>, isRoot?: boolean): Record<string, any>;
export declare class ModuleGraph {
private resolveId;
urlToModuleMap: Map<string, ModuleNode>;
idToModuleMap: Map<string, ModuleNode>;
fileToModulesMap: Map<string, Set<ModuleNode>>;
safeModulesPath: Set<string>;
container: PluginContainer;
constructor(container: PluginContainer);
constructor(resolveId: (url: string) => Promise<PartialResolvedId | null>);
getModuleByUrl(rawUrl: string): Promise<ModuleNode | undefined>;
getModuleById(id: string): ModuleNode | undefined;
getModulesByFile(file: string): Set<ModuleNode> | undefined;
@ -1017,7 +1087,7 @@ export declare class ModuleGraph {
updateModuleInfo(mod: ModuleNode, importedModules: Set<string | ModuleNode>, acceptedModules: Set<string | ModuleNode>, isSelfAccepting: boolean): Promise<Set<ModuleNode> | undefined>;
ensureEntryFromUrl(rawUrl: string): Promise<ModuleNode>;
createFileOnlyEntry(file: string): ModuleNode;
resolveUrl(url: string): Promise<[string, string]>;
resolveUrl(url: string): Promise<ResolvedUrl>;
}
export declare class ModuleNode {
@ -1031,6 +1101,8 @@ export declare class ModuleNode {
id: string | null;
file: string | null;
type: 'js' | 'css';
info?: ModuleInfo;
meta?: Record<string, any>;
importers: Set<ModuleNode>;
importedModules: Set<ModuleNode>;
acceptedHmrDeps: Set<ModuleNode>;
@ -1047,9 +1119,12 @@ export declare function normalizePath(id: string): string;
export declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean, newDeps?: Record<string, string>, // missing imports encountered after server has started
ssr?: boolean): Promise<DepOptimizationMetadata | null>;
/** Cache for package.json resolution and package.json contents */
export declare type PackageCache = Map<string, PackageData>;
export declare interface PackageData {
dir: string;
hasSideEffects: (id: string) => boolean;
hasSideEffects: (id: string) => boolean | 'no-treeshake';
webResolvedImports: Record<string, string | undefined>;
nodeResolvedImports: Record<string, string | undefined>;
setResolvedCache: (key: string, entry: string, targetWeb: boolean) => void;
@ -1164,17 +1239,31 @@ export declare interface Plugin extends Plugin_2 {
*/
resolveId?(this: PluginContext, source: string, importer: string | undefined, options: {
custom?: CustomPluginOptions;
}, ssr?: boolean): Promise<ResolveIdResult> | ResolveIdResult;
load?(this: PluginContext, id: string, ssr?: boolean): Promise<LoadResult> | LoadResult;
transform?(this: TransformPluginContext, code: string, id: string, ssr?: boolean): Promise<TransformResult_3> | TransformResult_3;
ssr?: boolean;
}): Promise<ResolveIdResult> | ResolveIdResult;
load?(this: PluginContext, id: string, options?: {
ssr?: boolean;
}): Promise<LoadResult> | LoadResult;
transform?(this: TransformPluginContext, code: string, id: string, options?: {
ssr?: boolean;
}): Promise<TransformResult_3> | TransformResult_3;
}
export declare interface PluginContainer {
options: InputOptions;
getModuleInfo(id: string): ModuleInfo | null;
buildStart(options: InputOptions): Promise<void>;
resolveId(id: string, importer?: string, skip?: Set<Plugin>, ssr?: boolean): Promise<PartialResolvedId | null>;
transform(code: string, id: string, inMap?: SourceDescription['map'], ssr?: boolean): Promise<SourceDescription | null>;
load(id: string, ssr?: boolean): Promise<LoadResult | null>;
resolveId(id: string, importer?: string, options?: {
skip?: Set<Plugin>;
ssr?: boolean;
}): Promise<PartialResolvedId | null>;
transform(code: string, id: string, options?: {
inMap?: SourceDescription['map'];
ssr?: boolean;
}): Promise<SourceDescription | null>;
load(id: string, options?: {
ssr?: boolean;
}): Promise<LoadResult | null>;
close(): Promise<void>;
}
@ -1186,9 +1275,30 @@ export declare type PluginOption = Plugin | false | null | undefined;
* @param serverOptions - what host and port to use
* @experimental
*/
export declare function preview(config: ResolvedConfig, serverOptions: Pick<ServerOptions, 'port' | 'host'>): Promise<Server>;
export declare function preview(inlineConfig: InlineConfig): Promise<PreviewServer>;
export declare function printHttpServerUrls(server: Server_3, config: ResolvedConfig): void;
export declare interface PreviewOptions extends CommonServerOptions {
}
export declare interface PreviewServer {
/**
* The resolved vite config object
*/
config: ResolvedConfig;
/**
* native Node http server instance
*/
httpServer: Server;
/**
* Print server urls
*/
printUrls: () => void;
}
/**
* @deprecated Use `server.printUrls()` instead
*/
export declare function printHttpServerUrls(server: Server_2, config: ResolvedConfig): void;
export declare interface ProxyOptions extends HttpProxy.ServerOptions {
/**
@ -1231,16 +1341,27 @@ export declare type ResolvedConfig = Readonly<Omit<UserConfig, 'plugins' | 'alia
plugins: readonly Plugin[];
server: ResolvedServerOptions;
build: ResolvedBuildOptions;
preview: ResolvedPreviewOptions;
assetsInclude: (file: string) => boolean;
logger: Logger;
createResolver: (options?: Partial<InternalResolveOptions>) => ResolveFn;
optimizeDeps: Omit<DepOptimizationOptions, 'keepNames'>;
/* Excluded from this release type: packageCache */
}>;
export declare interface ResolvedPreviewOptions extends PreviewOptions {
}
export declare interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>;
}
export declare type ResolvedUrl = [
url: string,
resolvedId: string,
meta: object | null | undefined
];
export declare function resolveEnvPrefix({ envPrefix }: UserConfig): string[];
export declare type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean, ssr?: boolean) => Promise<string | undefined>;
@ -1253,9 +1374,9 @@ export declare interface ResolveOptions {
preserveSymlinks?: boolean;
}
export declare function resolvePackageData(id: string, basedir: string, preserveSymlinks?: boolean): PackageData | undefined;
export declare function resolvePackageData(id: string, basedir: string, preserveSymlinks?: boolean, packageCache?: PackageCache): PackageData | null;
export declare function resolvePackageEntry(id: string, { dir, data, setResolvedCache, getResolvedCache }: PackageData, options: InternalResolveOptions, targetWeb: boolean, preserveSymlinks?: boolean): string | undefined;
export declare function resolvePackageEntry(id: string, { dir, data, setResolvedCache, getResolvedCache }: PackageData, targetWeb: boolean, options: InternalResolveOptions): string | undefined;
export declare type ResolverFunction = PluginHooks['resolveId']
@ -1273,7 +1394,7 @@ export declare interface ResolverObject {
*/
export declare interface RollupCommonJSOptions {
/**
* A minimatch pattern, or array of patterns, which specifies the files in
* A picomatch 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
@ -1283,7 +1404,7 @@ export declare interface RollupCommonJSOptions {
*/
include?: string | RegExp | readonly (string | RegExp)[]
/**
* A minimatch pattern, or array of patterns, which specifies the files in
* A picomatch 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.
@ -1337,6 +1458,26 @@ export declare interface RollupCommonJSOptions {
* @default []
*/
ignore?: ReadonlyArray<string> | ((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<string>
| ((id: string) => boolean | 'remove')
/**
* Controls how to render imports from external dependencies. By default,
* this plugin assumes that all external dependencies are CommonJS. This
@ -1454,18 +1595,7 @@ export declare function send(req: IncomingMessage, res: ServerResponse, content:
export declare type ServerHook = (server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>;
export declare interface ServerOptions {
host?: string | boolean;
port?: number;
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | https.ServerOptions;
/**
* Open browser window on startup
*/
open?: boolean | string;
export declare interface ServerOptions extends CommonServerOptions {
/**
* Force dep pre-optimization regardless of whether deps have changed.
*/
@ -1479,40 +1609,6 @@ export declare interface ServerOptions {
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions;
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>;
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean;
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean;
/**
* Create Vite dev server to be used as a middleware in an existing server
*/
@ -1823,6 +1919,10 @@ export declare interface UserConfig {
* Build specific options
*/
build?: BuildOptions;
/**
* Preview specific options, e.g. host, port, https...
*/
preview?: PreviewOptions;
/**
* Dep optimization options
*/
@ -1946,9 +2046,17 @@ export declare interface ViteDevServer {
* Print server urls
*/
printUrls(): void;
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>;
/* Excluded from this release type: _optimizeDepsMetadata */
/* Excluded from this release type: _ssrExternals */
/* Excluded from this release type: _globImporters */
/* Excluded from this release type: _restartPromise */
/* Excluded from this release type: _forceOptimizeOnRestart */
/* Excluded from this release type: _isRunningOptimizer */
/* Excluded from this release type: _registerMissingImport */
/* Excluded from this release type: _pendingReload */
@ -2455,7 +2563,7 @@ export declare namespace WebSocket {
host?: string | undefined
port?: number | undefined
backlog?: number | undefined
server?: Server | Server_2 | undefined
server?: Server | Server_3 | undefined
verifyClient?:
| VerifyClientCallbackAsync
| VerifyClientCallbackSync
@ -2571,8 +2679,8 @@ export declare namespace WebSocket {
}
export declare interface WebSocketServer {
on: WebSocket.Server['on'];
off: WebSocket.Server['off'];
on: WebSocketServer_2['on'];
off: WebSocketServer_2['off'];
send(payload: HMRPayload): void;
close(): Promise<void>;
}

35
packages/astro/vendor/vite/dist/node/index.js vendored Executable file → Normal file
View file

@ -2,31 +2,32 @@
Object.defineProperty(exports, '__esModule', { value: true });
var build = require('./chunks/dep-35df7f96.js');
var build = require('./chunks/dep-ac6ff16a.js');
require('fs');
require('path');
require('events');
require('util');
require('stream');
require('os');
require('perf_hooks');
require('url');
require('crypto');
require('module');
require('esbuild');
require('worker_threads');
require('assert');
require('child_process');
require('readline');
require('zlib');
require('resolve');
require('querystring');
require('tty');
require('util');
require('net');
require('events');
require('url');
require('http');
require('buffer');
require('stream');
require('resolve');
require('module');
require('perf_hooks');
require('https');
require('zlib');
require('crypto');
require('tls');
require('assert');
require('buffer');
require('querystring');
require('esbuild');
require('child_process');
require('json5');
require('worker_threads');
require('readline');

2
packages/astro/vendor/vite/dist/node/index.js.map vendored Executable file → Normal file
View file

@ -1 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}

240
packages/astro/vendor/vite/dist/node/terser.js vendored Executable file → Normal file
View file

@ -4613,7 +4613,7 @@ function parse($TEXT, options) {
}
if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) {
next();
var node = import_();
var node = import_statement();
semicolon();
return node;
}
@ -4765,7 +4765,7 @@ function parse($TEXT, options) {
case "export":
if (!is_token(peek(), "punc", "(")) {
next();
var node = export_();
var node = export_statement();
if (is("punc", ";")) semicolon();
return node;
}
@ -5942,7 +5942,7 @@ function parse($TEXT, options) {
};
const is_not_method_start = () =>
!is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("operator", "=");
!is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "=");
var is_async = false;
var is_static = false;
@ -6057,7 +6057,15 @@ function parse($TEXT, options) {
}
}
function import_() {
function maybe_import_assertion() {
if (is("name", "assert") && !has_newline_before(S.token)) {
next();
return object_or_destructuring_();
}
return null;
}
function import_statement() {
var start = prev();
var imported_name;
@ -6080,16 +6088,20 @@ function parse($TEXT, options) {
unexpected();
}
next();
const assert_clause = maybe_import_assertion();
return new AST_Import({
start: start,
imported_name: imported_name,
imported_names: imported_names,
start,
imported_name,
imported_names,
module_name: new AST_String({
start: mod_str,
value: mod_str.value,
quote: mod_str.quote,
end: mod_str,
}),
assert_clause,
end: S.token,
});
}
@ -6197,7 +6209,7 @@ function parse($TEXT, options) {
return names;
}
function export_() {
function export_statement() {
var start = S.token;
var is_default;
var exported_names;
@ -6215,6 +6227,8 @@ function parse($TEXT, options) {
}
next();
const assert_clause = maybe_import_assertion();
return new AST_Export({
start: start,
is_default: is_default,
@ -6226,6 +6240,7 @@ function parse($TEXT, options) {
end: mod_str,
}),
end: prev(),
assert_clause
});
} else {
return new AST_Export({
@ -6271,6 +6286,7 @@ function parse($TEXT, options) {
exported_value: exported_value,
exported_definition: exported_definition,
end: prev(),
assert_clause: null
});
}
@ -7604,12 +7620,13 @@ var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", {
},
});
var AST_Import = DEFNODE("Import", "imported_name imported_names module_name", {
var AST_Import = DEFNODE("Import", "imported_name imported_names module_name assert_clause", {
$documentation: "An `import` statement",
$propdoc: {
imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.",
imported_names: "[AST_NameMapping*] The names of non-default imported variables",
module_name: "[AST_String] String literal describing where this module came from",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
@ -7638,14 +7655,15 @@ var AST_ImportMeta = DEFNODE("ImportMeta", null, {
$documentation: "A reference to import.meta",
});
var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name", {
var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name assert_clause", {
$documentation: "An `export` statement",
$propdoc: {
exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition",
exported_value: "[AST_Node?] An exported value",
exported_names: "[AST_NameMapping*?] List of exported names",
module_name: "[AST_String?] Name of the file to load exports from",
is_default: "[Boolean] Whether this is the default exported value of this module"
is_default: "[Boolean] Whether this is the default exported value of this module",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function (visitor) {
return visitor._visit(this, function () {
@ -8898,6 +8916,24 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
return body;
};
const assert_clause_from_moz = (assertions) => {
if (assertions && assertions.length > 0) {
return new AST_Object({
start: my_start_token(assertions),
end: my_end_token(assertions),
properties: assertions.map((assertion_kv) =>
new AST_ObjectKeyVal({
start: my_start_token(assertion_kv),
end: my_end_token(assertion_kv),
key: assertion_kv.key.name || assertion_kv.key.value,
value: from_moz(assertion_kv.value)
})
)
});
}
return null;
};
var MOZ_TO_ME = {
Program: function(M) {
return new AST_Toplevel({
@ -9218,7 +9254,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
end : my_end_token(M),
imported_name: imported_name,
imported_names : imported_names,
module_name : from_moz(M.source)
module_name : from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportAllDeclaration: function(M) {
@ -9231,7 +9268,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
foreign_name: new AST_SymbolExportForeign({ name: "*" })
})
],
module_name: from_moz(M.source)
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportNamedDeclaration: function(M) {
@ -9245,7 +9283,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
name: from_moz(specifier.local)
});
}) : null,
module_name: from_moz(M.source)
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportDefaultDeclaration: function(M) {
@ -9537,12 +9576,30 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
};
});
const assert_clause_to_moz = assert_clause => {
const assertions = [];
if (assert_clause) {
for (const { key, value } of assert_clause.properties) {
const key_moz = is_basic_identifier_string(key)
? { type: "Identifier", name: key }
: { type: "Literal", value: key, raw: JSON.stringify(key) };
assertions.push({
type: "ImportAttribute",
key: key_moz,
value: to_moz(value)
});
}
}
return assertions;
};
def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) {
if (M.exported_names) {
if (M.exported_names[0].name.name === "*") {
return {
type: "ExportAllDeclaration",
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
}
return {
@ -9555,7 +9612,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
};
}),
declaration: to_moz(M.exported_definition),
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
}
return {
@ -9589,7 +9647,8 @@ def_transform(AST_PrefixedTemplateString, function(self, tw) {
return {
type: "ImportDeclaration",
specifiers: specifiers,
source: to_moz(M.module_name)
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
});
@ -10146,6 +10205,48 @@ function is_some_comments(comment) {
);
}
class Rope {
constructor() {
this.committed = "";
this.current = "";
}
append(str) {
this.current += str;
}
insertAt(char, index) {
const { committed, current } = this;
if (index < committed.length) {
this.committed = committed.slice(0, index) + char + committed.slice(index);
} else if (index === committed.length) {
this.committed += char;
} else {
index -= committed.length;
this.committed += current.slice(0, index) + char;
this.current = current.slice(index);
}
}
charAt(index) {
const { committed } = this;
if (index < committed.length) return committed[index];
return this.current[index - committed.length];
}
curLength() {
return this.current.length;
}
length() {
return this.committed.length + this.current.length;
}
toString() {
return this.committed + this.current;
}
}
function OutputStream(options) {
var readonly = !options;
@ -10210,7 +10311,7 @@ function OutputStream(options) {
var current_col = 0;
var current_line = 1;
var current_pos = 0;
var OUTPUT = "";
var OUTPUT = new Rope();
let printed_comments = new Set();
var to_utf8 = options.ascii_only ? function(str, identifier) {
@ -10341,19 +10442,18 @@ function OutputStream(options) {
var ensure_line_len = options.max_line_len ? function() {
if (current_col > options.max_line_len) {
if (might_add_newline) {
var left = OUTPUT.slice(0, might_add_newline);
var right = OUTPUT.slice(might_add_newline);
OUTPUT.insertAt("\n", might_add_newline);
const curLength = OUTPUT.curLength();
if (mappings) {
var delta = right.length - current_col;
var delta = curLength - current_col;
mappings.forEach(function(mapping) {
mapping.line++;
mapping.col += delta;
});
}
OUTPUT = left + "\n" + right;
current_line++;
current_pos++;
current_col = right.length;
current_col = curLength;
}
}
if (might_add_newline) {
@ -10387,13 +10487,13 @@ function OutputStream(options) {
if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") {
if (options.semicolons || requireSemicolonChars.has(ch)) {
OUTPUT += ";";
OUTPUT.append(";");
current_col++;
current_pos++;
} else {
ensure_line_len();
if (current_col > 0) {
OUTPUT += "\n";
OUTPUT.append("\n");
current_pos++;
current_line++;
current_col = 0;
@ -10417,7 +10517,7 @@ function OutputStream(options) {
|| (ch == "/" && ch == prev)
|| ((ch == "+" || ch == "-") && ch == last)
) {
OUTPUT += " ";
OUTPUT.append(" ");
current_col++;
current_pos++;
}
@ -10435,7 +10535,7 @@ function OutputStream(options) {
if (!might_add_newline) do_add_mapping();
}
OUTPUT += str;
OUTPUT.append(str);
has_parens = str[str.length - 1] == "(";
current_pos += str.length;
var a = str.split(/\r?\n/), n = a.length - 1;
@ -10475,15 +10575,15 @@ function OutputStream(options) {
var newline = options.beautify ? function() {
if (newline_insert < 0) return print("\n");
if (OUTPUT[newline_insert] != "\n") {
OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert);
if (OUTPUT.charAt(newline_insert) != "\n") {
OUTPUT.insertAt("\n", newline_insert);
current_pos++;
current_line++;
}
newline_insert++;
} : options.max_line_len ? function() {
ensure_line_len();
might_add_newline = OUTPUT.length;
might_add_newline = OUTPUT.length();
} : noop;
var semicolon = options.beautify ? function() {
@ -10549,13 +10649,14 @@ function OutputStream(options) {
if (might_add_newline) {
ensure_line_len();
}
return OUTPUT;
return OUTPUT.toString();
}
function has_nlb() {
let n = OUTPUT.length - 1;
const output = OUTPUT.toString();
let n = output.length - 1;
while (n >= 0) {
const code = OUTPUT.charCodeAt(n);
const code = output.charCodeAt(n);
if (code === CODE_LINE_BREAK) {
return true;
}
@ -10692,7 +10793,7 @@ function OutputStream(options) {
!/comment[134]/.test(c.type)
))) return;
printed_comments.add(comments);
var insert = OUTPUT.length;
var insert = OUTPUT.length();
comments.filter(comment_filter, node).forEach(function(c, i) {
if (printed_comments.has(c)) return;
printed_comments.add(c);
@ -10721,7 +10822,7 @@ function OutputStream(options) {
need_space = true;
}
});
if (OUTPUT.length > insert) newline_insert = insert;
if (OUTPUT.length() > insert) newline_insert = insert;
}
var stack = [];
@ -10751,7 +10852,7 @@ function OutputStream(options) {
var encoded = encode_string(str, quote);
if (escape_directive === true && !encoded.includes("\\")) {
// Insert semicolons to break directive prologue
if (!EXPECT_DIRECTIVE.test(OUTPUT)) {
if (!EXPECT_DIRECTIVE.test(OUTPUT.toString())) {
force_semicolon();
}
force_semicolon();
@ -11607,6 +11708,10 @@ function OutputStream(options) {
output.space();
}
self.module_name.print(output);
if (self.assert_clause) {
output.print("assert");
self.assert_clause.print(output);
}
output.semicolon();
});
DEFPRINT(AST_ImportMeta, function(self, output) {
@ -11672,6 +11777,10 @@ function OutputStream(options) {
output.space();
self.module_name.print(output);
}
if (self.assert_clause) {
output.print("assert");
self.assert_clause.print(output);
}
if (self.exported_value
&& !(self.exported_value instanceof AST_Defun ||
self.exported_value instanceof AST_Function ||
@ -13222,6 +13331,8 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
}
const mangled_names = this.mangled_names = new Set();
unmangleable_names = new Set();
if (options.cache) {
this.globals.forEach(collect);
if (options.cache.props) {
@ -13274,7 +13385,6 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
this.walk(tw);
if (options.keep_fnames || options.keep_classnames) {
unmangleable_names = new Set();
// Collect a set of short names which are unmangleable,
// for use in avoiding collisions in next_mangled.
to_mangle.forEach(def => {
@ -13290,9 +13400,9 @@ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
unmangleable_names = null;
function collect(symbol) {
const should_mangle = !options.reserved.has(symbol.name)
&& !(symbol.export & MASK_EXPORT_DONT_MANGLE);
if (should_mangle) {
if (symbol.export & MASK_EXPORT_DONT_MANGLE) {
unmangleable_names.add(symbol.name);
} else if (!options.reserved.has(symbol.name)) {
to_mangle.push(symbol);
}
}
@ -14330,6 +14440,7 @@ const is_pure_native_fn = make_nested_lookup({
"isExtensible",
"isFrozen",
"isSealed",
"hasOwn",
"keys",
],
String: [
@ -19357,7 +19468,7 @@ def_optimize(AST_Switch, function(self, compressor) {
// that way the next micro-optimization will merge them.
// ** bail micro-optimization if not a simple switch case with breaks
if (body.every((branch, i) =>
(branch === default_or_exact || !branch.expression.has_side_effects(compressor))
(branch === default_or_exact || branch.expression instanceof AST_Constant)
&& (branch.body.length === 0 || aborts(branch) || body.length - 1 === i))
) {
for (let i = 0; i < body.length; i++) {
@ -19445,12 +19556,16 @@ def_optimize(AST_Switch, function(self, compressor) {
// Prune side-effect free branches that fall into default.
if (default_or_exact) {
DEFAULT: if (default_or_exact) {
let default_index = body.indexOf(default_or_exact);
let default_body_index = default_index;
for (; default_body_index < body.length - 1; default_body_index++) {
if (!is_inert_body(body[default_body_index])) break;
}
if (default_body_index < body.length - 1) {
break DEFAULT;
}
let side_effect_index = body.length - 1;
for (; side_effect_index >= 0; side_effect_index--) {
let branch = body[side_effect_index];
@ -20497,16 +20612,16 @@ def_optimize(AST_UnaryPostfix, function(self, compressor) {
def_optimize(AST_UnaryPrefix, function(self, compressor) {
var e = self.expression;
if (self.operator == "delete"
&& !(e instanceof AST_SymbolRef
|| e instanceof AST_PropAccess
|| is_identifier_atom(e))) {
if (e instanceof AST_Sequence) {
const exprs = e.expressions.slice();
exprs.push(make_node(AST_True, self));
return make_sequence(self, exprs).optimize(compressor);
}
return make_sequence(self, [ e, make_node(AST_True, self) ]).optimize(compressor);
if (
self.operator == "delete" &&
!(
e instanceof AST_SymbolRef ||
e instanceof AST_PropAccess ||
e instanceof AST_Chain ||
is_identifier_atom(e)
)
) {
return make_sequence(self, [e, make_node(AST_True, self)]).optimize(compressor);
}
var seq = self.lift_sequences(compressor);
if (seq !== self) {
@ -21338,7 +21453,15 @@ function is_reachable(self, defs) {
if (node instanceof AST_Scope && node !== self) {
var parent = info.parent();
if (parent instanceof AST_Call && parent.expression === node) return;
if (
parent instanceof AST_Call
&& parent.expression === node
// Async/Generators aren't guaranteed to sync evaluate all of
// their body steps, so it's possible they close over the variable.
&& !(node.async || node.is_generator)
) {
return;
}
if (walk(node, find_ref)) return walk_abort;
@ -21990,7 +22113,16 @@ def_optimize(AST_Sub, function(self, compressor) {
});
def_optimize(AST_Chain, function (self, compressor) {
if (is_nullish(self.expression, compressor)) return make_node(AST_Undefined, self);
if (is_nullish(self.expression, compressor)) {
let parent = compressor.parent();
// It's valid to delete a nullish optional chain, but if we optimized
// this to `delete undefined` then it would appear to be a syntax error
// when we try to optimize the delete. Thankfully, `delete 0` is fine.
if (parent instanceof AST_UnaryPrefix && parent.operator === "delete") {
return make_node_from_constant(0, self);
}
return make_node(AST_Undefined, self);
}
return self;
});