docs:更新文档

This commit is contained in:
张益铭
2021-03-01 15:06:11 +08:00
parent 1542135ab0
commit 9064b372e8
5835 changed files with 904126 additions and 161722 deletions

27
node_modules/vite/dist/node/server/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
/// <reference types="node" />
import { Server } from 'http';
import Koa, { DefaultState, DefaultContext } from 'koa';
import { InternalResolver } from '../resolver';
import { HMRWatcher } from './serverPluginHmr';
import { ServerConfig } from '../config';
export { rewriteImports } from './serverPluginModuleRewrite';
import { SourceMap } from './serverPluginSourceMap';
export declare type ServerPlugin = (ctx: ServerPluginContext) => void;
export interface ServerPluginContext {
root: string;
app: Koa<State, Context>;
server: Server;
watcher: HMRWatcher;
resolver: InternalResolver;
config: ServerConfig & {
__path?: string;
};
port: number;
}
export interface State extends DefaultState {
}
export declare type Context = DefaultContext & ServerPluginContext & {
read: (filePath: string) => Promise<Buffer | string>;
map?: SourceMap | null;
};
export declare function createServer(config: ServerConfig): Server;

149
node_modules/vite/dist/node/server/index.js generated vendored Normal file
View File

@@ -0,0 +1,149 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createServer = exports.rewriteImports = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const koa_1 = __importDefault(require("koa"));
const chokidar_1 = __importDefault(require("chokidar"));
const resolver_1 = require("../resolver");
const serverPluginModuleRewrite_1 = require("./serverPluginModuleRewrite");
const serverPluginModuleResolve_1 = require("./serverPluginModuleResolve");
const serverPluginVue_1 = require("./serverPluginVue");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginServeStatic_1 = require("./serverPluginServeStatic");
const serverPluginJson_1 = require("./serverPluginJson");
const serverPluginCss_1 = require("./serverPluginCss");
const serverPluginAssets_1 = require("./serverPluginAssets");
const serverPluginEsbuild_1 = require("./serverPluginEsbuild");
const transform_1 = require("../transform");
const serverPluginHtml_1 = require("./serverPluginHtml");
const serverPluginProxy_1 = require("./serverPluginProxy");
const createCertificate_1 = require("../utils/createCertificate");
const utils_1 = require("../utils");
const serverPluginEnv_1 = require("./serverPluginEnv");
var serverPluginModuleRewrite_2 = require("./serverPluginModuleRewrite");
Object.defineProperty(exports, "rewriteImports", { enumerable: true, get: function () { return serverPluginModuleRewrite_2.rewriteImports; } });
const serverPluginSourceMap_1 = require("./serverPluginSourceMap");
const serverPluginWebWorker_1 = require("./serverPluginWebWorker");
const serverPluginWasm_1 = require("./serverPluginWasm");
const serverPluginClient_1 = require("./serverPluginClient");
function createServer(config) {
const { root = process.cwd(), configureServer = [], resolvers = [], alias = {}, transforms = [], vueCustomBlockTransforms = {}, optimizeDeps = {}, enableEsbuild = true, assetsInclude } = config;
const app = new koa_1.default();
const server = resolveServer(config, app.callback());
const watcher = chokidar_1.default.watch(root, {
ignored: [/node_modules/, /\.git/],
// #610
awaitWriteFinish: {
stabilityThreshold: 100,
pollInterval: 10
}
});
const resolver = resolver_1.createResolver(root, resolvers, alias, assetsInclude);
const context = {
root,
app,
server,
watcher,
resolver,
config,
// port is exposed on the context for hmr client connection
// in case the files are served under a different port
port: config.port || 3000
};
// attach server context to koa context
app.use((ctx, next) => {
Object.assign(ctx, context);
ctx.read = utils_1.cachedRead.bind(null, ctx);
return next();
});
// cors
if (config.cors) {
app.use(require('@koa/cors')(typeof config.cors === 'boolean' ? {} : config.cors));
}
const resolvedPlugins = [
// rewrite and source map plugins take highest priority and should be run
// after all other middlewares have finished
serverPluginSourceMap_1.sourceMapPlugin,
serverPluginModuleRewrite_1.moduleRewritePlugin,
serverPluginHtml_1.htmlRewritePlugin,
// user plugins
...utils_1.toArray(configureServer),
serverPluginEnv_1.envPlugin,
serverPluginModuleResolve_1.moduleResolvePlugin,
serverPluginProxy_1.proxyPlugin,
serverPluginClient_1.clientPlugin,
serverPluginHmr_1.hmrPlugin,
...(transforms.length || Object.keys(vueCustomBlockTransforms).length
? [
transform_1.createServerTransformPlugin(transforms, vueCustomBlockTransforms, resolver)
]
: []),
serverPluginVue_1.vuePlugin,
serverPluginCss_1.cssPlugin,
enableEsbuild ? serverPluginEsbuild_1.esbuildPlugin : null,
serverPluginJson_1.jsonPlugin,
serverPluginAssets_1.assetPathPlugin,
serverPluginWebWorker_1.webWorkerPlugin,
serverPluginWasm_1.wasmPlugin,
serverPluginServeStatic_1.serveStaticPlugin
];
resolvedPlugins.forEach((m) => m && m(context));
const listen = server.listen.bind(server);
server.listen = (async (port, ...args) => {
if (optimizeDeps.auto !== false) {
await require('../optimizer').optimizeDeps(config);
}
return listen(port, ...args);
});
server.once('listening', () => {
context.port = server.address().port;
});
return server;
}
exports.createServer = createServer;
function resolveServer({ https = false, httpsOptions = {}, proxy }, requestListener) {
if (https) {
if (proxy) {
// #484 fallback to http1 when proxy is needed.
return require('https').createServer(resolveHttpsConfig(httpsOptions), requestListener);
}
else {
return require('http2').createSecureServer({
...resolveHttpsConfig(httpsOptions),
allowHTTP1: true
}, requestListener);
}
}
else {
return require('http').createServer(requestListener);
}
}
function resolveHttpsConfig(httpsOption) {
const { ca, cert, key, pfx } = httpsOption;
Object.assign(httpsOption, {
ca: readFileIfExists(ca),
cert: readFileIfExists(cert),
key: readFileIfExists(key),
pfx: readFileIfExists(pfx)
});
if (!httpsOption.key || !httpsOption.cert) {
httpsOption.cert = httpsOption.key = createCertificate_1.createCertificate();
}
return httpsOption;
}
function readFileIfExists(value) {
if (value && !Buffer.isBuffer(value)) {
try {
return fs_extra_1.default.readFileSync(path_1.default.resolve(value));
}
catch (e) {
return value;
}
}
return value;
}
//# sourceMappingURL=index.js.map

1
node_modules/vite/dist/node/server/index.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/server/index.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,wDAAyB;AAGzB,8CAAuD;AACvD,wDAA+B;AAC/B,0CAA8D;AAC9D,2E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AAE,EAAE,gBAAgB,CAAC,EAAE,CAAC;QACxB,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC;QAC5B,GAAG,EAAE,gBAAgB,CAAC,GAAG,CAAC;QAC1B,GAAG,EAAE,gBAAgB,CAAC,GAAG,CAAC;KAC3B,CAAC,CAAA;IACF,IAAI,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;QACzC,WAAW,CAAC,IAAI,GAAG,WAAW,CAAC,GAAG,GAAG,qCAAiB,EAAE,CAAA;KACzD;IACD,OAAO,WAAW,CAAA;AACpB,CAAC;AAED,SAAS,gBAAgB,CAAC,KAA6B;IACrD,IAAI,KAAK,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACpC,IAAI;YACF,OAAO,kBAAE,CAAC,YAAY,CAAC,cAAI,CAAC,OAAO,CAAC,KAAe,CAAC,CAAC,CAAA;SACtD;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,KAAK,CAAA;SACb;KACF;IACD,OAAO,KAAK,CAAA;AACd,CAAC"}

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from '.';
export declare const assetPathPlugin: ServerPlugin;

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assetPathPlugin = void 0;
const utils_1 = require("../utils");
exports.assetPathPlugin = ({ app, resolver }) => {
app.use(async (ctx, next) => {
if (resolver.isAssetRequest(ctx.path) && utils_1.isImportRequest(ctx)) {
ctx.type = 'js';
ctx.body = `export default ${JSON.stringify(ctx.path)}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginAssets.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginAssets.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginAssets.ts"],"names":[],"mappings":";;;AACA,oCAA0C;AAE7B,QAAA,eAAe,GAAiB,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE;IACjE,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,IAAI,QAAQ,CAAC,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,uBAAe,CAAC,GAAG,CAAC,EAAE;YAC7D,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,kBAAkB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAA;YACvD,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,4 @@
import { ServerPlugin } from '.';
export declare const clientFilePath: string;
export declare const clientPublicPath = "/vite/client";
export declare const clientPlugin: ServerPlugin;

View File

@@ -0,0 +1,53 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.clientPlugin = exports.clientPublicPath = exports.clientFilePath = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const config_1 = require("../config");
exports.clientFilePath = path_1.default.resolve(__dirname, '../../client/client.js');
exports.clientPublicPath = `/vite/client`;
const legacyPublicPath = '/vite/hmr';
exports.clientPlugin = ({ app, config }) => {
const clientCode = fs_1.default
.readFileSync(exports.clientFilePath, 'utf-8')
.replace(`__MODE__`, JSON.stringify(config.mode || 'development'))
.replace(`__DEFINES__`, JSON.stringify({
...config_1.defaultDefines,
...config.define
}));
app.use(async (ctx, next) => {
if (ctx.path === exports.clientPublicPath) {
let socketPort = ctx.port;
// infer on client by default
let socketProtocol = null;
let socketHostname = null;
if (config.hmr && typeof config.hmr === 'object') {
// hmr option has highest priory
socketProtocol = config.hmr.protocol || null;
socketHostname = config.hmr.hostname || null;
socketPort = config.hmr.port || ctx.port;
if (config.hmr.path) {
socketPort = `${socketPort}/${config.hmr.path}`;
}
}
ctx.type = 'js';
ctx.status = 200;
ctx.body = clientCode
.replace(`__HMR_PROTOCOL__`, JSON.stringify(socketProtocol))
.replace(`__HMR_HOSTNAME__`, JSON.stringify(socketHostname))
.replace(`__HMR_PORT__`, JSON.stringify(socketPort));
}
else {
if (ctx.path === legacyPublicPath) {
console.error(chalk_1.default.red(`[vite] client import path has changed from "/vite/hmr" to "/vite/client". ` +
`please update your code accordingly.`));
}
return next();
}
});
};
//# sourceMappingURL=serverPluginClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginClient.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginClient.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAmB;AACnB,gDAAuB;AACvB,kDAAyB;AAEzB,sCAA0C;AAE7B,QAAA,cAAc,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,wBAAwB,CAAC,CAAA;AAElE,QAAA,gBAAgB,GAAG,cAAc,CAAA;AAE9C,MAAM,gBAAgB,GAAG,WAAW,CAAA;AAEvB,QAAA,YAAY,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;IAC5D,MAAM,UAAU,GAAG,YAAE;SAClB,YAAY,CAAC,sBAAc,EAAE,OAAO,CAAC;SACrC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,IAAI,aAAa,CAAC,CAAC;SACjE,OAAO,CACN,aAAa,EACb,IAAI,CAAC,SAAS,CAAC;QACb,GAAG,uBAAc;QACjB,GAAG,MAAM,CAAC,MAAM;KACjB,CAAC,CACH,CAAA;IAEH,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,IAAI,GAAG,CAAC,IAAI,KAAK,wBAAgB,EAAE;YACjC,IAAI,UAAU,GAAoB,GAAG,CAAC,IAAI,CAAA;YAC1C,6BAA6B;YAC7B,IAAI,cAAc,GAAG,IAAI,CAAA;YACzB,IAAI,cAAc,GAAG,IAAI,CAAA;YACzB,IAAI,MAAM,CAAC,GAAG,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ,EAAE;gBAChD,gCAAgC;gBAChC,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,IAAI,IAAI,CAAA;gBAC5C,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,IAAI,IAAI,CAAA;gBAC5C,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,CAAA;gBACxC,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE;oBACnB,UAAU,GAAG,GAAG,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;iBAChD;aACF;YACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,MAAM,GAAG,GAAG,CAAA;YAChB,GAAG,CAAC,IAAI,GAAG,UAAU;iBAClB,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;iBAC3D,OAAO,CAAC,kBAAkB,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;iBAC3D,OAAO,CAAC,cAAc,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAA;SACvD;aAAM;YACL,IAAI,GAAG,CAAC,IAAI,KAAK,gBAAgB,EAAE;gBACjC,OAAO,CAAC,KAAK,CACX,eAAK,CAAC,GAAG,CACP,4EAA4E;oBAC1E,sCAAsC,CACzC,CACF,CAAA;aACF;YACD,OAAO,IAAI,EAAE,CAAA;SACd;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,4 @@
import { ServerPlugin } from '.';
export declare const debugCSS: any;
export declare const cssPlugin: ServerPlugin;
export declare function codegenCss(id: string, css: string, modules?: Record<string, string>): string;

165
node_modules/vite/dist/node/server/serverPluginCss.js generated vendored Normal file
View File

@@ -0,0 +1,165 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.codegenCss = exports.cssPlugin = exports.debugCSS = void 0;
const path_1 = require("path");
const hash_sum_1 = __importDefault(require("hash-sum"));
const utils_1 = require("../utils");
const serverPluginVue_1 = require("./serverPluginVue");
const cssUtils_1 = require("../utils/cssUtils");
const querystring_1 = __importDefault(require("querystring"));
const chalk_1 = __importDefault(require("chalk"));
const serverPluginClient_1 = require("./serverPluginClient");
const pluginutils_1 = require("@rollup/pluginutils");
exports.debugCSS = require('debug')('vite:css');
exports.cssPlugin = ({ root, app, watcher, resolver }) => {
app.use(async (ctx, next) => {
await next();
// handle .css imports
if (cssUtils_1.isCSSRequest(ctx.path) &&
// note ctx.body could be null if upstream set status to 304
ctx.body) {
const id = JSON.stringify(hash_sum_1.default(ctx.path));
if (utils_1.isImportRequest(ctx)) {
const { css, modules } = await processCss(root, ctx);
ctx.type = 'js';
// we rewrite css with `?import` to a js module that inserts a style
// tag linking to the actual raw url
ctx.body = codegenCss(id, css, modules);
}
}
});
watcher.on('change', (filePath) => {
if (cssUtils_1.isCSSRequest(filePath)) {
const publicPath = resolver.fileToRequest(filePath);
/** filter unused files */
if (!cssUtils_1.cssImporterMap.has(filePath) &&
!processedCSS.has(publicPath) &&
!serverPluginVue_1.srcImportMap.has(filePath)) {
return exports.debugCSS(`${path_1.basename(publicPath)} has changed, but it is not currently in use`);
}
if (serverPluginVue_1.srcImportMap.has(filePath)) {
// handle HMR for <style src="xxx.css">
// it cannot be handled as simple css import because it may be scoped
const styleImport = serverPluginVue_1.srcImportMap.get(filePath);
serverPluginVue_1.vueCache.del(filePath);
vueStyleUpdate(styleImport);
return;
}
// handle HMR for module css
// it cannot be handled as normal css because the js exports may change
if (filePath.includes('.module')) {
moduleCssUpdate(filePath, resolver);
}
const boundaries = cssUtils_1.getCssImportBoundaries(filePath);
if (boundaries.size) {
boundaryCssUpdate(boundaries);
return;
}
// no boundaries
normalCssUpdate(publicPath);
}
else if (cssUtils_1.cssImporterMap.has(filePath)) {
const boundaries = cssUtils_1.getCssImportBoundaries(filePath);
if (boundaries.size) {
boundaryCssUpdate(boundaries);
}
}
});
function boundaryCssUpdate(boundaries) {
for (let boundary of boundaries) {
if (boundary.includes('.module')) {
moduleCssUpdate(boundary, resolver);
}
else if (boundary.includes('.vue')) {
serverPluginVue_1.vueCache.del(utils_1.cleanUrl(boundary));
vueStyleUpdate(resolver.fileToRequest(boundary));
}
else {
normalCssUpdate(resolver.fileToRequest(boundary));
}
}
}
function vueStyleUpdate(styleImport) {
const publicPath = utils_1.cleanUrl(styleImport);
const index = querystring_1.default.parse(styleImport.split('?', 2)[1]).index;
const path = `${publicPath}?type=style&index=${index}`;
console.log(chalk_1.default.green(`[vite:hmr] `) + `${publicPath} updated. (style)`);
watcher.send({
type: 'style-update',
path,
changeSrcPath: path,
timestamp: Date.now()
});
}
function moduleCssUpdate(filePath, resolver) {
// bust process cache
processedCSS.delete(resolver.fileToRequest(filePath));
watcher.handleJSReload(filePath);
}
function normalCssUpdate(publicPath) {
// bust process cache
processedCSS.delete(publicPath);
watcher.send({
type: 'style-update',
path: publicPath,
changeSrcPath: publicPath,
timestamp: Date.now()
});
}
// processed CSS is cached in case the user ticks "disable cache" during dev
// which can lead to unnecessary processing on page reload
const processedCSS = new Map();
async function processCss(root, ctx) {
// source didn't change (marker added by cachedRead)
// just use previously cached result
if (ctx.__notModified && processedCSS.has(ctx.path)) {
return processedCSS.get(ctx.path);
}
const css = (await utils_1.readBody(ctx.body));
const filePath = resolver.requestToFile(ctx.path);
const preprocessLang = (ctx.path.match(cssUtils_1.cssPreprocessLangRE) || [])[1];
const result = await cssUtils_1.compileCss(root, ctx.path, {
id: '',
source: css,
filename: filePath,
scoped: false,
modules: ctx.path.includes('.module'),
preprocessLang,
preprocessOptions: ctx.config.cssPreprocessOptions,
modulesOptions: ctx.config.cssModuleOptions
});
if (typeof result === 'string') {
const res = { css: await cssUtils_1.rewriteCssUrls(css, ctx.path) };
processedCSS.set(ctx.path, res);
return res;
}
cssUtils_1.recordCssImportChain(result.dependencies, filePath);
if (result.errors.length) {
console.error(`[vite] error applying css transforms: `);
result.errors.forEach(console.error);
}
const res = {
css: await cssUtils_1.rewriteCssUrls(result.code, ctx.path),
modules: result.modules
};
processedCSS.set(ctx.path, res);
return res;
}
};
function codegenCss(id, css, modules) {
let code = `import { updateStyle } from "${serverPluginClient_1.clientPublicPath}"\n` +
`const css = ${JSON.stringify(css)}\n` +
`updateStyle(${JSON.stringify(id)}, css)\n`;
if (modules) {
code += pluginutils_1.dataToEsm(modules, { namedExports: true });
}
else {
code += `export default css`;
}
return code;
}
exports.codegenCss = codegenCss;
//# sourceMappingURL=serverPluginCss.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
import { ServerPlugin } from '.';
export declare const envPublicPath = "/vite/env";
export declare const envPlugin: ServerPlugin;

27
node_modules/vite/dist/node/server/serverPluginEnv.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.envPlugin = exports.envPublicPath = void 0;
exports.envPublicPath = '/vite/env';
exports.envPlugin = ({ app, config }) => {
// configMode = mode of the .env{.mode} file that was loaded
const configMode = config.mode || 'development';
// resolvedMode = potentially overwritten by NODE_ENV inside the .env
// (which is set as VITE_ENV to avoid system default NODE_ENV)
const resolvedMode = process.env.VITE_ENV || configMode;
const env = JSON.stringify({
...config.env,
BASE_URL: '/',
MODE: configMode,
DEV: resolvedMode !== 'production',
PROD: resolvedMode === 'production'
});
app.use((ctx, next) => {
if (ctx.path === exports.envPublicPath) {
ctx.type = 'js';
ctx.body = `export default ${env}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginEnv.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginEnv.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginEnv.ts"],"names":[],"mappings":";;;AAEa,QAAA,aAAa,GAAG,WAAW,CAAA;AAE3B,QAAA,SAAS,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;IACzD,4DAA4D;IAC5D,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,IAAI,aAAa,CAAA;IAC/C,qEAAqE;IACrE,8DAA8D;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,UAAU,CAAA;IACvD,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC;QACzB,GAAG,MAAM,CAAC,GAAG;QACb,QAAQ,EAAE,GAAG;QACb,IAAI,EAAE,UAAU;QAChB,GAAG,EAAE,YAAY,KAAK,YAAY;QAClC,IAAI,EAAE,YAAY,KAAK,YAAY;KACpC,CAAC,CAAA;IAEF,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACpB,IAAI,GAAG,CAAC,IAAI,KAAK,qBAAa,EAAE;YAC9B,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,kBAAkB,GAAG,EAAE,CAAA;YAClC,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from '.';
export declare const esbuildPlugin: ServerPlugin;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.esbuildPlugin = void 0;
const esbuildService_1 = require("../esbuildService");
const utils_1 = require("../utils");
exports.esbuildPlugin = ({ app, config, resolver }) => {
const jsxConfig = esbuildService_1.resolveJsxOptions(config.jsx);
app.use(async (ctx, next) => {
// intercept and return vue jsx helper import
if (ctx.path === esbuildService_1.vueJsxPublicPath) {
await ctx.read(esbuildService_1.vueJsxFilePath);
}
await next();
if (!esbuildService_1.tjsxRE.test(ctx.path) ||
!ctx.body ||
ctx.type === 'text/html' ||
resolver.isPublicRequest(ctx.path)) {
return;
}
ctx.type = 'js';
const src = await utils_1.readBody(ctx.body);
const { code, map } = await esbuildService_1.transform(src, resolver.requestToFile(utils_1.cleanUrl(ctx.url)), jsxConfig, config.jsx);
ctx.body = code;
if (map) {
ctx.map = JSON.parse(map);
}
});
};
//# sourceMappingURL=serverPluginEsbuild.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginEsbuild.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginEsbuild.ts"],"names":[],"mappings":";;;AACA,sDAM0B;AAC1B,oCAA6C;AAEhC,QAAA,aAAa,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE;IACvE,MAAM,SAAS,GAAG,kCAAiB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IAE/C,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,6CAA6C;QAC7C,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAgB,EAAE;YACjC,MAAM,GAAG,CAAC,IAAI,CAAC,+BAAc,CAAC,CAAA;SAC/B;QAED,MAAM,IAAI,EAAE,CAAA;QAEZ,IACE,CAAC,uBAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;YACtB,CAAC,GAAG,CAAC,IAAI;YACT,GAAG,CAAC,IAAI,KAAK,WAAW;YACxB,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,EAClC;YACA,OAAM;SACP;QAED,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;QACf,MAAM,GAAG,GAAG,MAAM,gBAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACpC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,0BAAS,CACnC,GAAI,EACJ,QAAQ,CAAC,aAAa,CAAC,gBAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EACzC,SAAS,EACT,MAAM,CAAC,GAAG,CACX,CAAA;QACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;QACf,IAAI,GAAG,EAAE;YACP,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,23 @@
import { ServerPlugin } from '.';
import { FSWatcher } from 'chokidar';
import MagicString from 'magic-string';
import { InternalResolver } from '../resolver';
import LRUCache from 'lru-cache';
import { HMRPayload } from '../../hmrPayload';
export declare const debugHmr: any;
export declare type HMRWatcher = FSWatcher & {
handleVueReload: (filePath: string, timestamp?: number, content?: string) => void;
handleJSReload: (filePath: string, timestamp?: number) => void;
send: (payload: HMRPayload) => void;
};
declare type HMRStateMap = Map<string, Set<string>>;
export declare const hmrAcceptanceMap: HMRStateMap;
export declare const hmrDeclineSet: Set<string>;
export declare const importerMap: HMRStateMap;
export declare const importeeMap: HMRStateMap;
export declare const hmrDirtyFilesMap: LRUCache<string, Set<string>>;
export declare const latestVersionsMap: Map<string, string>;
export declare const hmrPlugin: ServerPlugin;
export declare function ensureMapEntry(map: HMRStateMap, key: string): Set<string>;
export declare function rewriteFileWithHMR(root: string, source: string, importer: string, resolver: InternalResolver, s: MagicString): void;
export {};

296
node_modules/vite/dist/node/server/serverPluginHmr.js generated vendored Normal file
View File

@@ -0,0 +1,296 @@
"use strict";
// How HMR works
// 1. `.vue` files are transformed into `.js` files before being served
// 2. All `.js` files, before being served, are parsed to detect their imports
// (this is done in `./serverPluginModuleRewrite.ts`) for module import rewriting.
// During this we also record the importer/importee relationships which can be used for
// HMR analysis (we do both at the same time to avoid double parse costs)
// 3. When a file changes, it triggers an HMR graph analysis, where we try to
// walk its importer chains and see if we reach a "HMR boundary". An HMR
// boundary is a file that explicitly indicated that it accepts hot updates
// (by calling `import.meta.hot` APIs)
// 4. If any parent chain exhausts without ever running into an HMR boundary,
// it's considered a "dead end". This causes a full page reload.
// 5. If a boundary is encountered, we check if the boundary's current
// child importer is in the accepted list of the boundary (recorded while
// parsing the file for HRM rewrite). If yes, record current child importer
// in the `hmrBoundaries` Set.
// 6. If the graph walk finished without running into dead ends, send the
// client to update all `hmrBoundaries`.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteFileWithHMR = exports.ensureMapEntry = exports.hmrPlugin = exports.latestVersionsMap = exports.hmrDirtyFilesMap = exports.importeeMap = exports.importerMap = exports.hmrDeclineSet = exports.hmrAcceptanceMap = exports.debugHmr = void 0;
const ws_1 = __importDefault(require("ws"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const serverPluginVue_1 = require("./serverPluginVue");
const serverPluginModuleRewrite_1 = require("./serverPluginModuleRewrite");
const babelParse_1 = require("../utils/babelParse");
const lru_cache_1 = __importDefault(require("lru-cache"));
const slash_1 = __importDefault(require("slash"));
const cssUtils_1 = require("../utils/cssUtils");
const utils_1 = require("../utils");
const serverPluginClient_1 = require("./serverPluginClient");
exports.debugHmr = require('debug')('vite:hmr');
exports.hmrAcceptanceMap = new Map();
exports.hmrDeclineSet = new Set();
exports.importerMap = new Map();
exports.importeeMap = new Map();
// files that are dirty (i.e. in the import chain between the accept boundary
// and the actual changed file) for an hmr update at a given timestamp.
exports.hmrDirtyFilesMap = new lru_cache_1.default({ max: 10 });
exports.latestVersionsMap = new Map();
exports.hmrPlugin = ({ root, app, server, watcher, resolver, config }) => {
app.use((ctx, next) => {
if (ctx.query.t) {
exports.latestVersionsMap.set(ctx.path, ctx.query.t);
}
return next();
});
// start a websocket server to send hmr notifications to the client
const wss = new ws_1.default.Server({ noServer: true });
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] === 'vite-hmr') {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
}
});
wss.on('connection', (socket) => {
exports.debugHmr('ws client connected');
socket.send(JSON.stringify({ type: 'connected' }));
});
wss.on('error', (e) => {
if (e.code !== 'EADDRINUSE') {
console.error(chalk_1.default.red(`[vite] WebSocket server error:`));
console.error(e);
}
});
const send = (watcher.send = (payload) => {
const stringified = JSON.stringify(payload, null, 2);
exports.debugHmr(`update: ${stringified}`);
wss.clients.forEach((client) => {
if (client.readyState === ws_1.default.OPEN) {
client.send(stringified);
}
});
});
const handleJSReload = (watcher.handleJSReload = (filePath, timestamp = Date.now()) => {
// normal js file, but could be compiled from anything.
// bust the vue cache in case this is a src imported file
if (serverPluginVue_1.srcImportMap.has(filePath)) {
exports.debugHmr(`busting Vue cache for ${filePath}`);
serverPluginVue_1.vueCache.del(filePath);
}
const publicPath = resolver.fileToRequest(filePath);
const importers = exports.importerMap.get(publicPath);
if (importers || isHmrAccepted(publicPath, publicPath)) {
const hmrBoundaries = new Set();
const dirtyFiles = new Set();
dirtyFiles.add(publicPath);
const hasDeadEnd = walkImportChain(publicPath, importers || new Set(), hmrBoundaries, dirtyFiles);
// record dirty files - this is used when HMR requests coming in with
// timestamp to determine what files need to be force re-fetched
exports.hmrDirtyFilesMap.set(String(timestamp), dirtyFiles);
const relativeFile = '/' + slash_1.default(path_1.default.relative(root, filePath));
if (hasDeadEnd) {
send({
type: 'full-reload',
path: publicPath
});
console.log(chalk_1.default.green(`[vite] `) + `page reloaded.`);
}
else {
const boundaries = [...hmrBoundaries];
const file = boundaries.length === 1 ? boundaries[0] : `${boundaries.length} files`;
console.log(chalk_1.default.green(`[vite:hmr] `) +
`${file} hot updated due to change in ${relativeFile}.`);
send({
type: 'multi',
updates: boundaries.map((boundary) => {
return {
type: boundary.endsWith('vue') ? 'vue-reload' : 'js-update',
path: boundary,
changeSrcPath: publicPath,
timestamp
};
})
});
}
}
else {
exports.debugHmr(`no importers for ${publicPath}.`);
}
});
watcher.on('change', (file) => {
if (!(file.endsWith('.vue') || cssUtils_1.isCSSRequest(file))) {
// everything except plain .css are considered HMR dependencies.
// plain css has its own HMR logic in ./serverPluginCss.ts.
handleJSReload(file);
}
});
};
function walkImportChain(importee, importers, hmrBoundaries, dirtyFiles, currentChain = []) {
if (exports.hmrDeclineSet.has(importee)) {
// module explicitly declines HMR = dead end
return true;
}
if (isHmrAccepted(importee, importee)) {
// self-accepting module.
hmrBoundaries.add(importee);
dirtyFiles.add(importee);
return false;
}
for (const importer of importers) {
if (importer.endsWith('.vue') ||
// explicitly accepted by this importer
isHmrAccepted(importer, importee) ||
// importer is a self accepting module
isHmrAccepted(importer, importer)) {
// vue boundaries are considered dirty for the reload
if (importer.endsWith('.vue')) {
dirtyFiles.add(importer);
}
hmrBoundaries.add(importer);
currentChain.forEach((file) => dirtyFiles.add(file));
}
else {
const parentImpoters = exports.importerMap.get(importer);
if (!parentImpoters) {
return true;
}
else if (!currentChain.includes(importer)) {
if (walkImportChain(importer, parentImpoters, hmrBoundaries, dirtyFiles, currentChain.concat(importer))) {
return true;
}
}
}
}
return false;
}
function isHmrAccepted(importer, dep) {
const deps = exports.hmrAcceptanceMap.get(importer);
return deps ? deps.has(dep) : false;
}
function ensureMapEntry(map, key) {
let entry = map.get(key);
if (!entry) {
entry = new Set();
map.set(key, entry);
}
return entry;
}
exports.ensureMapEntry = ensureMapEntry;
function rewriteFileWithHMR(root, source, importer, resolver, s) {
let hasDeclined = false;
const registerDep = (e) => {
const deps = ensureMapEntry(exports.hmrAcceptanceMap, importer);
const depPublicPath = serverPluginModuleRewrite_1.resolveImport(root, importer, e.value, resolver);
deps.add(depPublicPath);
exports.debugHmr(` ${importer} accepts ${depPublicPath}`);
ensureMapEntry(exports.importerMap, depPublicPath).add(importer);
s.overwrite(e.start, e.end, JSON.stringify(depPublicPath));
};
const checkHotCall = (node, isTopLevel, isDevBlock) => {
if (node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
isMetaHot(node.callee.object)) {
if (isTopLevel) {
const { generateCodeFrame } = utils_1.resolveCompiler(root);
console.warn(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: import.meta.hot.accept() ` +
`should be wrapped in \`if (import.meta.hot) {}\` conditional ` +
`blocks so that they can be tree-shaken in production.`));
console.warn(chalk_1.default.yellow(generateCodeFrame(source, node.start, node.end)));
}
const method = node.callee.property.type === 'Identifier' && node.callee.property.name;
if (method === 'accept' || method === 'acceptDeps') {
if (!isDevBlock) {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: import.meta.hot.${method}() ` +
`cannot be conditional except for \`if (import.meta.hot)\` check ` +
`because the server relies on static analysis to construct the HMR graph.`));
}
// register the accepted deps
const accepted = node.arguments[0];
if (accepted && accepted.type === 'ArrayExpression') {
if (method !== 'acceptDeps') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() only accepts ` +
`a single callback. Use hot.acceptDeps() to handle dep updates.`));
}
// import.meta.hot.accept(['./foo', './bar'], () => {})
accepted.elements.forEach((e) => {
if (e && e.type !== 'StringLiteral') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() deps ` +
`list can only contain string literals.`));
}
else if (e) {
registerDep(e);
}
});
}
else if (accepted && accepted.type === 'StringLiteral') {
if (method !== 'acceptDeps') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() only accepts ` +
`a single callback. Use hot.acceptDeps() to handle dep updates.`));
}
// import.meta.hot.accept('./foo', () => {})
registerDep(accepted);
}
else if (!accepted || accepted.type.endsWith('FunctionExpression')) {
if (method !== 'accept') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.acceptDeps() ` +
`expects a dependency or an array of dependencies. ` +
`Use hot.accept() for handling self updates.`));
}
// self accepting
// import.meta.hot.accept() OR import.meta.hot.accept(() => {})
ensureMapEntry(exports.hmrAcceptanceMap, importer).add(importer);
exports.debugHmr(`${importer} self accepts`);
}
else {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: ` +
`import.meta.hot.accept() expects a dep string, an array of ` +
`deps, or a callback.`));
}
}
if (method === 'decline') {
hasDeclined = true;
exports.hmrDeclineSet.add(importer);
}
}
};
const checkStatements = (node, isTopLevel, isDevBlock) => {
if (node.type === 'ExpressionStatement') {
// top level hot.accept() call
checkHotCall(node.expression, isTopLevel, isDevBlock);
}
// if (import.meta.hot) ...
if (node.type === 'IfStatement') {
const isDevBlock = isMetaHot(node.test);
if (node.consequent.type === 'BlockStatement') {
node.consequent.body.forEach((s) => checkStatements(s, false, isDevBlock));
}
if (node.consequent.type === 'ExpressionStatement') {
checkHotCall(node.consequent.expression, false, isDevBlock);
}
}
};
const ast = babelParse_1.parse(source);
ast.forEach((s) => checkStatements(s, true, false));
// inject import.meta.hot
s.prepend(`import { createHotContext } from "${serverPluginClient_1.clientPublicPath}"; ` +
`import.meta.hot = createHotContext(${JSON.stringify(importer)}); `);
// clear decline state
if (!hasDeclined) {
exports.hmrDeclineSet.delete(importer);
}
}
exports.rewriteFileWithHMR = rewriteFileWithHMR;
function isMetaHot(node) {
return (node.type === 'MemberExpression' &&
node.object.type === 'MetaProperty' &&
node.property.type === 'Identifier' &&
node.property.name === 'hot');
}
//# sourceMappingURL=serverPluginHmr.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from './index';
export declare const htmlRewritePlugin: ServerPlugin;

75
node_modules/vite/dist/node/server/serverPluginHtml.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.htmlRewritePlugin = void 0;
const index_1 = require("./index");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginClient_1 = require("./serverPluginClient");
const es_module_lexer_1 = require("es-module-lexer");
const utils_1 = require("../utils");
const lru_cache_1 = __importDefault(require("lru-cache"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const debug = require('debug')('vite:rewrite');
const rewriteHtmlPluginCache = new lru_cache_1.default({ max: 20 });
exports.htmlRewritePlugin = ({ root, app, watcher, resolver, config }) => {
const devInjectionCode = `\n<script type="module">import "${serverPluginClient_1.clientPublicPath}"</script>\n`;
const scriptRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)([\s\S]*?)<\/script>/gm;
const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/;
async function rewriteHtml(importer, html) {
await es_module_lexer_1.init;
html = await utils_1.transformIndexHtml(html, config.indexHtmlTransforms, 'pre', false);
html = html.replace(scriptRE, (matched, openTag, script) => {
if (script) {
return `${openTag}${index_1.rewriteImports(root, script, importer, resolver)}</script>`;
}
else {
const srcAttr = openTag.match(srcRE);
if (srcAttr) {
// register script as a import dep for hmr
const importee = resolver.normalizePublicPath(utils_1.cleanUrl(path_1.default.posix.resolve('/', srcAttr[1] || srcAttr[2])));
serverPluginHmr_1.debugHmr(` ${importer} imports ${importee}`);
serverPluginHmr_1.ensureMapEntry(serverPluginHmr_1.importerMap, importee).add(importer);
}
return matched;
}
});
const processedHtml = utils_1.injectScriptToHtml(html, devInjectionCode);
return await utils_1.transformIndexHtml(processedHtml, config.indexHtmlTransforms, 'post', false);
}
app.use(async (ctx, next) => {
await next();
if (ctx.status === 304) {
return;
}
if (ctx.response.is('html') && ctx.body) {
const importer = ctx.path;
const html = await utils_1.readBody(ctx.body);
if (rewriteHtmlPluginCache.has(html)) {
debug(`${ctx.path}: serving from cache`);
ctx.body = rewriteHtmlPluginCache.get(html);
}
else {
if (!html)
return;
ctx.body = await rewriteHtml(importer, html);
rewriteHtmlPluginCache.set(html, ctx.body);
}
return;
}
});
watcher.on('change', (file) => {
const path = resolver.fileToRequest(file);
if (path.endsWith('.html')) {
debug(`${path}: cache busted`);
watcher.send({
type: 'full-reload',
path
});
console.log(chalk_1.default.green(`[vite] `) + ` ${path} page reloaded.`);
}
});
};
//# sourceMappingURL=serverPluginHtml.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginHtml.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginHtml.ts"],"names":[],"mappings":";;;;;;AAAA,mCAAsD;AACtD,uDAAyE;AACzE,6DAAuD;AACvD,qDAAmD;AACnD,oCAKiB;AACjB,0DAAgC;AAChC,gDAAuB;AACvB,kDAAyB;AAEzB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAA;AAE9C,MAAM,sBAAsB,GAAG,IAAI,mBAAQ,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAA;AAE3C,QAAA,iBAAiB,GAAiB,CAAC,EAC9C,IAAI,EACJ,GAAG,EACH,OAAO,EACP,QAAQ,EACR,MAAM,EACP,EAAE,EAAE;IACH,MAAM,gBAAgB,GAAG,mCAAmC,qCAAgB,cAAc,CAAA;IAC1F,MAAM,QAAQ,GAAG,8EAA8E,CAAA;IAC/F,MAAM,KAAK,GAAG,4CAA4C,CAAA;IAE1D,KAAK,UAAU,WAAW,CAAC,QAAgB,EAAE,IAAY;QACvD,MAAM,sBAAS,CAAA;QACf,IAAI,GAAG,MAAM,0BAAkB,CAC7B,IAAI,EACJ,MAAM,CAAC,mBAAmB,EAC1B,KAAK,EACL,KAAK,CACN,CAAA;QACD,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;YACzD,IAAI,MAAM,EAAE;gBACV,OAAO,GAAG,OAAO,GAAG,sBAAc,CAChC,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,QAAQ,CACT,WAAW,CAAA;aACb;iBAAM;gBACL,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;gBACpC,IAAI,OAAO,EAAE;oBACX,0CAA0C;oBAC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IAAI,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;gBAC5C,sBAAsB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;aAC3C;YACD,OAAM;SACP;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE;QAC5B,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAC1B,KAAK,CAAC,GAAG,IAAI,gBAAgB,CAAC,CAAA;YAC9B,OAAO,CAAC,IAAI,CAAC;gBACX,IAAI,EAAE,aAAa;gBACnB,IAAI;aACL,CAAC,CAAA;YACF,OAAO,CAAC,GAAG,CAAC,eAAK,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,IAAI,iBAAiB,CAAC,CAAA;SAChE;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from '.';
export declare const jsonPlugin: ServerPlugin;

20
node_modules/vite/dist/node/server/serverPluginJson.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonPlugin = void 0;
const utils_1 = require("../utils");
const pluginutils_1 = require("@rollup/pluginutils");
exports.jsonPlugin = ({ app }) => {
app.use(async (ctx, next) => {
await next();
// handle .json imports
// note ctx.body could be null if upstream set status to 304
if (ctx.path.endsWith('.json') && utils_1.isImportRequest(ctx) && ctx.body) {
ctx.type = 'js';
ctx.body = pluginutils_1.dataToEsm(JSON.parse((await utils_1.readBody(ctx.body))), {
namedExports: true,
preferConst: true
});
}
});
};
//# sourceMappingURL=serverPluginJson.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginJson.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginJson.ts"],"names":[],"mappings":";;;AACA,oCAAoD;AACpD,qDAA+C;AAElC,QAAA,UAAU,GAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IAClD,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,MAAM,IAAI,EAAE,CAAA;QACZ,uBAAuB;QACvB,4DAA4D;QAC5D,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,uBAAe,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE;YAClE,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,uBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,gBAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAE,CAAC,EAAE;gBAC5D,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;aAClB,CAAC,CAAA;SACH;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,5 @@
import { ServerPlugin } from '.';
export declare const moduleIdToFileMap: Map<any, any>;
export declare const moduleFileToIdMap: Map<any, any>;
export declare const moduleRE: RegExp;
export declare const moduleResolvePlugin: ServerPlugin;

View File

@@ -0,0 +1,87 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.moduleResolvePlugin = exports.moduleRE = exports.moduleFileToIdMap = exports.moduleIdToFileMap = void 0;
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const utils_1 = require("../utils");
const url_1 = require("url");
const resolver_1 = require("../resolver");
const debug = require('debug')('vite:resolve');
exports.moduleIdToFileMap = new Map();
exports.moduleFileToIdMap = new Map();
exports.moduleRE = /^\/@modules\//;
const getDebugPath = (root, p) => {
const relative = path_1.default.relative(root, p);
return relative.startsWith('..') ? p : relative;
};
// plugin for resolving /@modules/:id requests.
exports.moduleResolvePlugin = ({ root, app, resolver }) => {
const vueResolved = utils_1.resolveVue(root);
app.use(async (ctx, next) => {
if (!exports.moduleRE.test(ctx.path)) {
return next();
}
// path maybe contain encode chars
const id = decodeURIComponent(ctx.path.replace(exports.moduleRE, ''));
ctx.type = 'js';
const serve = async (id, file, type) => {
exports.moduleIdToFileMap.set(id, file);
exports.moduleFileToIdMap.set(file, ctx.path);
debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`);
await ctx.read(file);
return next();
};
// special handling for vue runtime in case it's not installed
if (!vueResolved.isLocal && id in vueResolved) {
return serve(id, vueResolved[id], 'non-local vue');
}
// already resolved and cached
const cachedPath = exports.moduleIdToFileMap.get(id);
if (cachedPath) {
return serve(id, cachedPath, 'cached');
}
// resolve from vite optimized modules
const optimized = resolver_1.resolveOptimizedModule(root, id);
if (optimized) {
return serve(id, optimized, 'optimized');
}
const referer = ctx.get('referer');
let importer;
// this is a map file request from browser dev tool
const isMapFile = ctx.path.endsWith('.map');
if (referer) {
importer = new url_1.URL(referer).pathname;
}
else if (isMapFile) {
// for some reason Chrome doesn't provide referer for source map requests.
// do our best to reverse-infer the importer.
importer = ctx.path.replace(/\.map$/, '');
}
const importerFilePath = importer ? resolver.requestToFile(importer) : root;
// #829 node package has sub-package(has package.json), should check it before `resolveNodeModuleFile`
const nodeModuleInfo = resolver_1.resolveNodeModule(root, id, resolver);
if (nodeModuleInfo) {
return serve(id, nodeModuleInfo.entryFilePath, 'node_modules');
}
const nodeModuleFilePath = resolver_1.resolveNodeModuleFile(importerFilePath, id);
if (nodeModuleFilePath) {
return serve(id, nodeModuleFilePath, 'node_modules');
}
if (isMapFile && importer) {
// the resolveNodeModuleFile doesn't work with linked pkg
// our last try: infer from the dir of importer
const inferMapPath = path_1.default.join(path_1.default.dirname(importerFilePath), path_1.default.basename(ctx.path));
if (fs_extra_1.default.existsSync(inferMapPath)) {
return serve(id, inferMapPath, 'map file in linked pkg');
}
}
console.error(chalk_1.default.red(`[vite] Failed to resolve module import "${id}". ` +
`(imported by ${importer || 'unknown'})`));
ctx.status = 404;
});
};
//# sourceMappingURL=serverPluginModuleResolve.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginModuleResolve.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginModuleResolve.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,kDAAyB;AACzB,wDAAyB;AAEzB,oCAAqC;AACrC,6BAAyB;AACzB,0CAIoB;AAEpB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAA;AAEjC,QAAA,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,QAAA,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAA;AAE7B,QAAA,QAAQ,GAAG,eAAe,CAAA;AAEvC,MAAM,YAAY,GAAG,CAAC,IAAY,EAAE,CAAS,EAAE,EAAE;IAC/C,MAAM,QAAQ,GAAG,cAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACvC,OAAO,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAA;AACjD,CAAC,CAAA;AAED,+CAA+C;AAClC,QAAA,mBAAmB,GAAiB,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE;IAC3E,MAAM,WAAW,GAAG,kBAAU,CAAC,IAAI,CAAC,CAAA;IAEpC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,IAAI,CAAC,gBAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YAC5B,OAAO,IAAI,EAAE,CAAA;SACd;QAED,kCAAkC;QAClC,MAAM,EAAE,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B,QAAQ,IAAI,SAAS,GAAG,CAC3C,CACF,CAAA;QACD,GAAG,CAAC,MAAM,GAAG,GAAG,CAAA;IAClB,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,5 @@
import { ServerPlugin } from '.';
import { InternalResolver } from '../resolver';
export declare const moduleRewritePlugin: ServerPlugin;
export declare function rewriteImports(root: string, source: string, importer: string, resolver: InternalResolver, timestamp?: string): string;
export declare const resolveImport: (root: string, importer: string, id: string, resolver: InternalResolver, timestamp?: string | undefined) => string;

View File

@@ -0,0 +1,220 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveImport = exports.rewriteImports = exports.moduleRewritePlugin = void 0;
const path_1 = __importDefault(require("path"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const magic_string_1 = __importDefault(require("magic-string"));
const es_module_lexer_1 = require("es-module-lexer");
const resolver_1 = require("../resolver");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginClient_1 = require("./serverPluginClient");
const utils_1 = require("../utils");
const chalk_1 = __importDefault(require("chalk"));
const cssUtils_1 = require("../utils/cssUtils");
const serverPluginEnv_1 = require("./serverPluginEnv");
const fs_extra_1 = __importDefault(require("fs-extra"));
const debug = require('debug')('vite:rewrite');
const rewriteCache = new lru_cache_1.default({ max: 1024 });
// Plugin for rewriting served js.
// - Rewrites named module imports to `/@modules/:id` requests, e.g.
// "vue" => "/@modules/vue"
// - Rewrites files containing HMR code (reference to `import.meta.hot`) to
// inject `import.meta.hot` and track HMR boundary accept whitelists.
// - Also tracks importer/importee relationship graph during the rewrite.
// The graph is used by the HMR plugin to perform analysis on file change.
exports.moduleRewritePlugin = ({ root, app, watcher, resolver }) => {
app.use(async (ctx, next) => {
await next();
if (ctx.status === 304) {
return;
}
// we are doing the js rewrite after all other middlewares have finished;
// this allows us to post-process javascript produced by user middlewares
// regardless of the extension of the original files.
const publicPath = ctx.path;
if (ctx.body &&
ctx.response.is('js') &&
!cssUtils_1.isCSSRequest(ctx.path) &&
!ctx.url.endsWith('.map') &&
!resolver.isPublicRequest(ctx.path) &&
// skip internal client
publicPath !== serverPluginClient_1.clientPublicPath &&
// need to rewrite for <script>\<template> part in vue files
!((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type === 'style')) {
const content = await utils_1.readBody(ctx.body);
const cacheKey = publicPath + content;
const isHmrRequest = !!ctx.query.t;
if (!isHmrRequest && rewriteCache.has(cacheKey)) {
debug(`(cached) ${ctx.url}`);
ctx.body = rewriteCache.get(cacheKey);
}
else {
await es_module_lexer_1.init;
// dynamic import may contain extension-less path,
// (.e.g import(runtimePathString))
// so we need to normalize importer to ensure it contains extension
// before we perform hmr analysis.
// on the other hand, static import is guaranteed to have extension
// because they must all have gone through module rewrite.
const importer = utils_1.removeUnRelatedHmrQuery(resolver.normalizePublicPath(ctx.url));
ctx.body = rewriteImports(root, content, importer, resolver, ctx.query.t);
if (!isHmrRequest) {
rewriteCache.set(cacheKey, ctx.body);
}
}
}
else {
debug(`(skipped) ${ctx.url}`);
}
});
// bust module rewrite cache on file change
watcher.on('change', async (filePath) => {
const publicPath = resolver.fileToRequest(filePath);
// #662 use fs.read instead of cacheRead, avoid cache hit when request file
// and caused pass `notModified` into transform is always true
const cacheKey = publicPath + (await fs_extra_1.default.readFile(filePath)).toString();
debug(`${publicPath}: cache busted`);
rewriteCache.del(cacheKey);
});
};
function rewriteImports(root, source, importer, resolver, timestamp) {
// #806 strip UTF-8 BOM
if (source.charCodeAt(0) === 0xfeff) {
source = source.slice(1);
}
try {
let imports = [];
try {
imports = es_module_lexer_1.parse(source)[0];
}
catch (e) {
console.error(chalk_1.default.yellow(`[vite] failed to parse ${chalk_1.default.cyan(importer)} for import rewrite.\nIf you are using ` +
`JSX, make sure to named the file with the .jsx extension.`));
}
const hasHMR = source.includes('import.meta.hot');
const hasEnv = source.includes('import.meta.env');
if (imports.length || hasHMR || hasEnv) {
debug(`${importer}: rewriting`);
const s = new magic_string_1.default(source);
let hasReplaced = false;
const prevImportees = serverPluginHmr_1.importeeMap.get(importer);
const currentImportees = new Set();
serverPluginHmr_1.importeeMap.set(importer, currentImportees);
for (let i = 0; i < imports.length; i++) {
const { s: start, e: end, d: dynamicIndex } = imports[i];
let id = source.substring(start, end);
let hasLiteralDynamicId = false;
if (dynamicIndex >= 0) {
// #998 remove comment
id = id.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '');
const literalIdMatch = id.match(/^\s*(?:'([^']+)'|"([^"]+)")\s*$/);
if (literalIdMatch) {
hasLiteralDynamicId = true;
id = literalIdMatch[1] || literalIdMatch[2];
}
}
if (dynamicIndex === -1 || hasLiteralDynamicId) {
// do not rewrite external imports
if (utils_1.isExternalUrl(id)) {
continue;
}
const resolved = exports.resolveImport(root, importer, id, resolver, timestamp);
if (resolved !== id) {
debug(` "${id}" --> "${resolved}"`);
s.overwrite(start, end, hasLiteralDynamicId ? `'${resolved}'` : resolved);
hasReplaced = true;
}
// save the import chain for hmr analysis
const importee = utils_1.cleanUrl(resolved);
if (importee !== importer &&
// no need to track hmr client or module dependencies
importee !== serverPluginClient_1.clientPublicPath) {
currentImportees.add(importee);
serverPluginHmr_1.debugHmr(` ${importer} imports ${importee}`);
serverPluginHmr_1.ensureMapEntry(serverPluginHmr_1.importerMap, importee).add(importer);
}
}
else if (id !== 'import.meta' &&
!/\/\*\s*@vite-ignore\s*\*\//.test(id)) {
console.warn(chalk_1.default.yellow(`[vite] ignored dynamic import(${id}) in ${importer}.`));
}
}
if (hasHMR) {
serverPluginHmr_1.debugHmr(`rewriting ${importer} for HMR.`);
serverPluginHmr_1.rewriteFileWithHMR(root, source, importer, resolver, s);
hasReplaced = true;
}
if (hasEnv) {
debug(` injecting import.meta.env for ${importer}`);
s.prepend(`import __VITE_ENV__ from "${serverPluginEnv_1.envPublicPath}"; ` +
`import.meta.env = __VITE_ENV__; `);
hasReplaced = true;
}
// since the importees may have changed due to edits,
// check if we need to remove this importer from certain importees
if (prevImportees) {
prevImportees.forEach((importee) => {
if (!currentImportees.has(importee)) {
const importers = serverPluginHmr_1.importerMap.get(importee);
if (importers) {
importers.delete(importer);
}
}
});
}
if (!hasReplaced) {
debug(` nothing needs rewriting.`);
}
return hasReplaced ? s.toString() : source;
}
else {
debug(`${importer}: no imports found.`);
}
return source;
}
catch (e) {
console.error(`[vite] Error: module imports rewrite failed for ${importer}.\n`, e);
debug(source);
return source;
}
}
exports.rewriteImports = rewriteImports;
exports.resolveImport = (root, importer, id, resolver, timestamp) => {
id = resolver.alias(id) || id;
if (utils_1.bareImportRE.test(id)) {
// directly resolve bare module names to its entry path so that relative
// imports from it (including source map urls) can work correctly
id = `/@modules/${resolver_1.resolveBareModuleRequest(root, id, importer, resolver)}`;
}
else {
// 1. relative to absolute
// ./foo -> /some/path/foo
let { pathname, query } = resolver.resolveRelativeRequest(importer, id);
// 2. resolve dir index and extensions.
pathname = resolver.normalizePublicPath(pathname);
// 3. mark non-src imports
if (!query && path_1.default.extname(pathname) && !resolver_1.jsSrcRE.test(pathname)) {
query += `?import`;
}
id = pathname + query;
}
// 4. force re-fetch dirty imports by appending timestamp
if (timestamp) {
const dirtyFiles = serverPluginHmr_1.hmrDirtyFilesMap.get(timestamp);
const cleanId = utils_1.cleanUrl(id);
// only rewrite if:
if (dirtyFiles && dirtyFiles.has(cleanId)) {
// 1. this is a marked dirty file (in the import chain of the changed file)
id += `${id.includes(`?`) ? `&` : `?`}t=${timestamp}`;
}
else if (serverPluginHmr_1.latestVersionsMap.has(cleanId)) {
// 2. this file was previously hot-updated and has an updated version
id += `${id.includes(`?`) ? `&` : `?`}t=${serverPluginHmr_1.latestVersionsMap.get(cleanId)}`;
}
}
return id;
};
//# sourceMappingURL=serverPluginModuleRewrite.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import { ServerPlugin } from '.';
import { IKoaProxiesOptions } from 'koa-proxies';
export declare type ProxiesOptions = IKoaProxiesOptions & {
ws: boolean;
};
export declare const proxyPlugin: ServerPlugin;

View File

@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.proxyPlugin = void 0;
const url_1 = require("url");
exports.proxyPlugin = ({ app, config, server }) => {
if (!config.proxy) {
return;
}
const debug = require('debug')('vite:proxy');
const proxy = require('koa-proxies');
const options = config.proxy;
Object.keys(options).forEach((path) => {
let opts = options[path];
if (typeof opts === 'string') {
opts = { target: opts };
}
opts.logs = (ctx, target) => {
debug(`${ctx.req.method} ${ctx.req.oldPath} proxy to -> ${new url_1.URL(ctx.req.url, target)}`);
};
app.use(proxy(path, opts));
});
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] !== 'vite-hmr') {
for (const path in options) {
let opts = options[path];
if (typeof opts === 'object' && opts.ws) {
proxy.proxy.ws(req, socket, head, opts);
}
}
}
});
};
//# sourceMappingURL=serverPluginProxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginProxy.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginProxy.ts"],"names":[],"mappings":";;;AACA,6BAAyB;AAKZ,QAAA,WAAW,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE;IACnE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE;QACjB,OAAM;KACP;IAED,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,YAAY,CAAC,CAAA;IAC5C,MAAM,KAAK,GAAG,OAAO,CAAC,aAAa,CAAC,CAAA;IACpC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAA;IAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACpC,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;QACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,IAAI,GAAG,EAAE,MAAM,EAAE,IAAI,EAAoB,CAAA;SAC1C;QACD,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YAC1B,KAAK,CACH,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,IAAK,GAAG,CAAC,GAAW,CAAC,OAAO,gBAAgB,IAAI,SAAG,CAClE,GAAG,CAAC,GAAG,CAAC,GAAI,EACZ,MAAM,CACP,EAAE,CACJ,CAAA;QACH,CAAC,CAAA;QACD,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;IAC5B,CAAC,CAAC,CAAA;IAEF,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;QACzC,IAAI,GAAG,CAAC,OAAO,CAAC,wBAAwB,CAAC,KAAK,UAAU,EAAE;YACxD,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;gBAC1B,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;gBACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE,EAAE;oBACvC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;iBACxC;aACF;SACF;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,3 @@
import { ServerPlugin } from '.';
export declare const seenUrls: Set<unknown>;
export declare const serveStaticPlugin: ServerPlugin;

View File

@@ -0,0 +1,77 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.serveStaticPlugin = exports.seenUrls = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const send = require('koa-send');
const debug = require('debug')('vite:history');
exports.seenUrls = new Set();
exports.serveStaticPlugin = ({ root, app, resolver, config }) => {
app.use(async (ctx, next) => {
// short circuit requests that have already been explicitly handled
if (ctx.body || ctx.status !== 404) {
return;
}
// warn non-root references to assets under /public/
if (ctx.path.startsWith('/public/') && resolver.isAssetRequest(ctx.path)) {
console.error(chalk_1.default.yellow(`[vite] files in the public directory are served at the root path.\n` +
` ${chalk_1.default.blue(ctx.path)} should be changed to ${chalk_1.default.blue(ctx.path.replace(/^\/public\//, '/'))}.`));
}
// handle possible user request -> file aliases
const expectsHtml = ctx.headers.accept && ctx.headers.accept.includes('text/html');
if (!expectsHtml) {
const filePath = resolver.requestToFile(ctx.path);
if (filePath !== ctx.path &&
fs_1.default.existsSync(filePath) &&
fs_1.default.statSync(filePath).isFile()) {
await ctx.read(filePath);
}
}
await next();
// the first request to the server should never 304
if (exports.seenUrls.has(ctx.url) && ctx.fresh) {
ctx.status = 304;
}
exports.seenUrls.add(ctx.url);
});
app.use(require('koa-etag')());
app.use(require('koa-static')(root));
app.use(require('koa-static')(path_1.default.join(root, 'public')));
// history API fallback
app.use(async (ctx, next) => {
if (ctx.status !== 404) {
return next();
}
if (ctx.method !== 'GET') {
debug(`not redirecting ${ctx.url} (not GET)`);
return next();
}
const accept = ctx.headers && ctx.headers.accept;
if (typeof accept !== 'string') {
debug(`not redirecting ${ctx.url} (no headers.accept)`);
return next();
}
if (accept.includes('application/json')) {
debug(`not redirecting ${ctx.url} (json)`);
return next();
}
if (!accept.includes('text/html')) {
debug(`not redirecting ${ctx.url} (not accepting html)`);
return next();
}
debug(`redirecting ${ctx.url} to /index.html`);
try {
await send(ctx, `index.html`, { root });
}
catch (e) {
ctx.url = '/index.html';
ctx.status = 404;
return next();
}
});
};
//# sourceMappingURL=serverPluginServeStatic.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginServeStatic.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginServeStatic.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AAE,CAAA;SACd;QAED,IAAI,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;YACvC,KAAK,CAAC,mBAAmB,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;YAC1C,OAAO,IAAI,EAAE,CAAA;SACd;QAED,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE;YACjC,KAAK,CAAC,mBAAmB,GAAG,CAAC,GAAG,uBAAuB,CAAC,CAAA;YACxD,OAAO,IAAI,EAAE,CAAA;SACd;QAED,KAAK,CAAC,eAAe,GAAG,CAAC,GAAG,iBAAiB,CAAC,CAAA;QAC9C,IAAI;YACF,MAAM,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;SACxC;QAAC,OAAO,CAAC,EAAE;YACV,GAAG,CAAC,GAAG,GAAG,aAAa,CAAA;YACvB,GAAG,CAAC,MAAM,GAAG,GAAG,CAAA;YAChB,OAAO,IAAI,EAAE,CAAA;SACd;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,6 @@
import { ServerPlugin } from '.';
import { ExistingRawSourceMap } from 'rollup';
import { RawSourceMap } from 'source-map';
export declare type SourceMap = ExistingRawSourceMap | RawSourceMap;
export declare function mergeSourceMap(oldMap: SourceMap | null | undefined, newMap: SourceMap): SourceMap;
export declare const sourceMapPlugin: ServerPlugin;

View File

@@ -0,0 +1,32 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sourceMapPlugin = exports.mergeSourceMap = void 0;
const merge_source_map_1 = __importDefault(require("merge-source-map"));
function mergeSourceMap(oldMap, newMap) {
if (!oldMap) {
return newMap;
}
// merge-source-map will overwrite original sources if newMap also has
// sourcesContent
newMap.sourcesContent = [];
return merge_source_map_1.default(oldMap, newMap);
}
exports.mergeSourceMap = mergeSourceMap;
function genSourceMapString(map) {
if (typeof map !== 'string') {
map = JSON.stringify(map);
}
return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')}`;
}
exports.sourceMapPlugin = ({ app }) => {
app.use(async (ctx, next) => {
await next();
if (typeof ctx.body === 'string' && ctx.map) {
ctx.body += genSourceMapString(ctx.map);
}
});
};
//# sourceMappingURL=serverPluginSourceMap.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginSourceMap.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginSourceMap.ts"],"names":[],"mappings":";;;;;;AACA,wEAAoC;AAMpC,SAAgB,cAAc,CAC5B,MAAoC,EACpC,MAAiB;IAEjB,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,MAAM,CAAA;KACd;IACD,sEAAsE;IACtE,iBAAiB;IACjB,MAAM,CAAC,cAAc,GAAG,EAAE,CAAA;IAC1B,OAAO,0BAAK,CAAC,MAAM,EAAE,MAAM,CAAc,CAAA;AAC3C,CAAC;AAXD,wCAWC;AAED,SAAS,kBAAkB,CAAC,GAAmC;IAC7D,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAA;KAC1B;IACD,OAAO,uDAAuD,MAAM,CAAC,IAAI,CACvE,GAAG,CACJ,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;AACxB,CAAC;AAEY,QAAA,eAAe,GAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IACvD,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,MAAM,IAAI,EAAE,CAAA;QACZ,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,EAAE;YAC3C,GAAG,CAAC,IAAI,IAAI,kBAAkB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;SACxC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,20 @@
import { ServerPlugin } from '.';
import { SFCDescriptor, SFCStyleCompileResults, BindingMetadata } from '@vue/compiler-sfc';
import LRUCache from 'lru-cache';
import { SourceMap } from './serverPluginSourceMap';
export declare const srcImportMap: Map<any, any>;
interface CacheEntry {
descriptor?: SFCDescriptor;
template?: ResultWithMap;
script?: ResultWithMap;
styles: SFCStyleCompileResults[];
customs: string[];
}
interface ResultWithMap {
code: string;
map: SourceMap | null | undefined;
bindings?: BindingMetadata;
}
export declare const vueCache: LRUCache<string, CacheEntry>;
export declare const vuePlugin: ServerPlugin;
export {};

527
node_modules/vite/dist/node/server/serverPluginVue.js generated vendored Normal file
View File

@@ -0,0 +1,527 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.vuePlugin = exports.vueCache = exports.srcImportMap = void 0;
const querystring_1 = __importDefault(require("querystring"));
const chalk_1 = __importDefault(require("chalk"));
const path_1 = __importDefault(require("path"));
const compiler_sfc_1 = require("@vue/compiler-sfc");
const resolveVue_1 = require("../utils/resolveVue");
const hash_sum_1 = __importDefault(require("hash-sum"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const serverPluginHmr_1 = require("./serverPluginHmr");
const utils_1 = require("../utils");
const esbuildService_1 = require("../esbuildService");
const resolver_1 = require("../resolver");
const serverPluginServeStatic_1 = require("./serverPluginServeStatic");
const serverPluginCss_1 = require("./serverPluginCss");
const cssUtils_1 = require("../utils/cssUtils");
const serverPluginModuleRewrite_1 = require("./serverPluginModuleRewrite");
const serverPluginSourceMap_1 = require("./serverPluginSourceMap");
const debug = require('debug')('vite:sfc');
const getEtag = require('etag');
exports.srcImportMap = new Map();
exports.vueCache = new lru_cache_1.default({
max: 65535
});
exports.vuePlugin = ({ root, app, resolver, watcher, config }) => {
const etagCacheCheck = (ctx) => {
ctx.etag = getEtag(ctx.body);
ctx.status =
serverPluginServeStatic_1.seenUrls.has(ctx.url) && ctx.etag === ctx.get('If-None-Match') ? 304 : 200;
serverPluginServeStatic_1.seenUrls.add(ctx.url);
};
app.use(async (ctx, next) => {
// ctx.vue is set by other tools like vitepress so that vite knows to treat
// non .vue files as vue files.
if (!ctx.path.endsWith('.vue') && !ctx.vue) {
return next();
}
const query = ctx.query;
const publicPath = ctx.path;
let filePath = resolver.requestToFile(publicPath);
// upstream plugins could've already read the file
const descriptor = await parseSFC(root, filePath, ctx.body);
if (!descriptor) {
return next();
}
if (!query.type) {
// watch potentially out of root vue file since we do a custom read here
utils_1.watchFileIfOutOfRoot(watcher, root, filePath);
if (descriptor.script && descriptor.script.src) {
filePath = await resolveSrcImport(root, descriptor.script, ctx, resolver);
}
ctx.type = 'js';
const { code, map } = await compileSFCMain(descriptor, filePath, publicPath, root);
ctx.body = code;
ctx.map = map;
return etagCacheCheck(ctx);
}
if (query.type === 'template') {
const templateBlock = descriptor.template;
if (templateBlock.src) {
filePath = await resolveSrcImport(root, templateBlock, ctx, resolver);
}
ctx.type = 'js';
const cached = exports.vueCache.get(filePath);
const bindingMetadata = cached && cached.script && cached.script.bindings;
const vueSpecifier = resolver_1.resolveBareModuleRequest(root, 'vue', publicPath, resolver);
const { code, map } = compileSFCTemplate(root, templateBlock, filePath, publicPath, descriptor.styles.some((s) => s.scoped), bindingMetadata, vueSpecifier, config);
ctx.body = code;
ctx.map = map;
return etagCacheCheck(ctx);
}
if (query.type === 'style') {
const index = Number(query.index);
const styleBlock = descriptor.styles[index];
if (styleBlock.src) {
filePath = await resolveSrcImport(root, styleBlock, ctx, resolver);
}
const id = hash_sum_1.default(publicPath);
const result = await compileSFCStyle(root, styleBlock, index, filePath, publicPath, config);
ctx.type = 'js';
ctx.body = serverPluginCss_1.codegenCss(`${id}-${index}`, result.code, result.modules);
return etagCacheCheck(ctx);
}
if (query.type === 'custom') {
const index = Number(query.index);
const customBlock = descriptor.customBlocks[index];
if (customBlock.src) {
filePath = await resolveSrcImport(root, customBlock, ctx, resolver);
}
const result = resolveCustomBlock(customBlock, index, filePath, publicPath);
ctx.type = 'js';
ctx.body = result;
return etagCacheCheck(ctx);
}
});
const handleVueReload = (watcher.handleVueReload = async (filePath, timestamp = Date.now(), content) => {
const publicPath = resolver.fileToRequest(filePath);
const cacheEntry = exports.vueCache.get(filePath);
const { send } = watcher;
serverPluginHmr_1.debugHmr(`busting Vue cache for ${filePath}`);
exports.vueCache.del(filePath);
const descriptor = await parseSFC(root, filePath, content);
if (!descriptor) {
// read failed
return;
}
const prevDescriptor = cacheEntry && cacheEntry.descriptor;
if (!prevDescriptor) {
// the file has never been accessed yet
serverPluginHmr_1.debugHmr(`no existing descriptor found for ${filePath}`);
return;
}
// check which part of the file changed
let needRerender = false;
const sendReload = () => {
send({
type: 'vue-reload',
path: publicPath,
changeSrcPath: publicPath,
timestamp
});
console.log(chalk_1.default.green(`[vite:hmr] `) +
`${path_1.default.relative(root, filePath)} updated. (reload)`);
};
if (!isEqualBlock(descriptor.script, prevDescriptor.script) ||
!isEqualBlock(descriptor.scriptSetup, prevDescriptor.scriptSetup)) {
return sendReload();
}
if (!isEqualBlock(descriptor.template, prevDescriptor.template)) {
// #748 should re-use previous cached script if only template change
// so that the template is compiled with the correct binding metadata
if (prevDescriptor.scriptSetup && descriptor.scriptSetup) {
exports.vueCache.get(filePath).script = cacheEntry.script;
}
needRerender = true;
}
let didUpdateStyle = false;
const styleId = hash_sum_1.default(publicPath);
const prevStyles = prevDescriptor.styles || [];
const nextStyles = descriptor.styles || [];
// css modules update causes a reload because the $style object is changed
// and it may be used in JS. It also needs to trigger a vue-style-update
// event so the client busts the sw cache.
if (prevStyles.some((s) => s.module != null) ||
nextStyles.some((s) => s.module != null)) {
return sendReload();
}
// force reload if CSS vars injection changed
if (prevStyles.some((s, i) => {
const next = nextStyles[i];
if (s.attrs.vars && (!next || next.attrs.vars !== s.attrs.vars)) {
return true;
}
})) {
return sendReload();
}
// force reload if scoped status has changed
if (prevStyles.some((s) => s.scoped) !== nextStyles.some((s) => s.scoped)) {
return sendReload();
}
// only need to update styles if not reloading, since reload forces
// style updates as well.
nextStyles.forEach((_, i) => {
if (!prevStyles[i] || !isEqualBlock(prevStyles[i], nextStyles[i])) {
didUpdateStyle = true;
const path = `${publicPath}?type=style&index=${i}`;
send({
type: 'style-update',
path,
changeSrcPath: path,
timestamp
});
}
});
// stale styles always need to be removed
prevStyles.slice(nextStyles.length).forEach((_, i) => {
didUpdateStyle = true;
send({
type: 'style-remove',
path: publicPath,
id: `${styleId}-${i + nextStyles.length}`
});
});
const prevCustoms = prevDescriptor.customBlocks || [];
const nextCustoms = descriptor.customBlocks || [];
// custom blocks update causes a reload
// because the custom block contents is changed and it may be used in JS.
if (nextCustoms.some((_, i) => !prevCustoms[i] || !isEqualBlock(prevCustoms[i], nextCustoms[i]))) {
return sendReload();
}
if (needRerender) {
send({
type: 'vue-rerender',
path: publicPath,
changeSrcPath: publicPath,
timestamp
});
}
let updateType = [];
if (needRerender) {
updateType.push(`template`);
}
if (didUpdateStyle) {
updateType.push(`style`);
}
if (updateType.length) {
console.log(chalk_1.default.green(`[vite:hmr] `) +
`${path_1.default.relative(root, filePath)} updated. (${updateType.join(' & ')})`);
}
});
watcher.on('change', (file) => {
if (file.endsWith('.vue')) {
handleVueReload(file);
}
});
};
function isEqualBlock(a, b) {
if (!a && !b)
return true;
if (!a || !b)
return false;
// src imports will trigger their own updates
if (a.src && b.src && a.src === b.src)
return true;
if (a.content !== b.content)
return false;
const keysA = Object.keys(a.attrs);
const keysB = Object.keys(b.attrs);
if (keysA.length !== keysB.length) {
return false;
}
return keysA.every((key) => a.attrs[key] === b.attrs[key]);
}
async function resolveSrcImport(root, block, ctx, resolver) {
const importer = ctx.path;
const importee = utils_1.cleanUrl(serverPluginModuleRewrite_1.resolveImport(root, importer, block.src, resolver));
const filePath = resolver.requestToFile(importee);
block.content = (await ctx.read(filePath)).toString();
// register HMR import relationship
serverPluginHmr_1.debugHmr(` ${importer} imports ${importee}`);
serverPluginHmr_1.ensureMapEntry(serverPluginHmr_1.importerMap, importee).add(ctx.path);
exports.srcImportMap.set(filePath, ctx.url);
return filePath;
}
async function parseSFC(root, filePath, content) {
let cached = exports.vueCache.get(filePath);
if (cached && cached.descriptor) {
debug(`${filePath} parse cache hit`);
return cached.descriptor;
}
if (!content) {
try {
content = await utils_1.cachedRead(null, filePath);
}
catch (e) {
return;
}
}
if (typeof content !== 'string') {
content = content.toString();
}
const start = Date.now();
const { parse } = resolveVue_1.resolveCompiler(root);
const { descriptor, errors } = parse(content, {
filename: filePath,
sourceMap: true
});
if (errors.length) {
console.error(chalk_1.default.red(`\n[vite] SFC parse error: `));
errors.forEach((e) => {
logError(e, filePath, content);
});
}
cached = cached || { styles: [], customs: [] };
cached.descriptor = descriptor;
exports.vueCache.set(filePath, cached);
debug(`${filePath} parsed in ${Date.now() - start}ms.`);
return descriptor;
}
async function compileSFCMain(descriptor, filePath, publicPath, root) {
let cached = exports.vueCache.get(filePath);
if (cached && cached.script) {
return cached.script;
}
const id = hash_sum_1.default(publicPath);
let code = ``;
let content = ``;
let map;
let script = descriptor.script;
const compiler = resolveVue_1.resolveCompiler(root);
if ((descriptor.script || descriptor.scriptSetup) && compiler.compileScript) {
try {
script = compiler.compileScript(descriptor);
}
catch (e) {
console.error(chalk_1.default.red(`\n[vite] SFC <script setup> compilation error:\n${chalk_1.default.dim(chalk_1.default.white(filePath))}`));
console.error(chalk_1.default.yellow(e.message));
}
}
if (script) {
content = script.content;
map = script.map;
if (script.lang === 'ts') {
const res = await esbuildService_1.transform(content, publicPath, {
loader: 'ts'
});
content = res.code;
map = serverPluginSourceMap_1.mergeSourceMap(map, JSON.parse(res.map));
}
}
code += compiler_sfc_1.rewriteDefault(content, '__script');
let hasScoped = false;
let hasCSSModules = false;
if (descriptor.styles) {
descriptor.styles.forEach((s, i) => {
const styleRequest = publicPath + `?type=style&index=${i}`;
if (s.scoped)
hasScoped = true;
if (s.module) {
if (!hasCSSModules) {
code += `\nconst __cssModules = __script.__cssModules = {}`;
hasCSSModules = true;
}
const styleVar = `__style${i}`;
const moduleName = typeof s.module === 'string' ? s.module : '$style';
code += `\nimport ${styleVar} from ${JSON.stringify(styleRequest + '&module')}`;
code += `\n__cssModules[${JSON.stringify(moduleName)}] = ${styleVar}`;
}
else {
code += `\nimport ${JSON.stringify(styleRequest)}`;
}
});
if (hasScoped) {
code += `\n__script.__scopeId = "data-v-${id}"`;
}
}
if (descriptor.customBlocks) {
descriptor.customBlocks.forEach((c, i) => {
const attrsQuery = attrsToQuery(c.attrs, c.lang);
const blockTypeQuery = `&blockType=${querystring_1.default.escape(c.type)}`;
let customRequest = publicPath + `?type=custom&index=${i}${blockTypeQuery}${attrsQuery}`;
const customVar = `block${i}`;
code += `\nimport ${customVar} from ${JSON.stringify(customRequest)}\n`;
code += `if (typeof ${customVar} === 'function') ${customVar}(__script)\n`;
});
}
if (descriptor.template) {
const templateRequest = publicPath + `?type=template`;
code += `\nimport { render as __render } from ${JSON.stringify(templateRequest)}`;
code += `\n__script.render = __render`;
}
code += `\n__script.__hmrId = ${JSON.stringify(publicPath)}`;
code += `\ntypeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(__script.__hmrId, __script)`;
code += `\n__script.__file = ${JSON.stringify(filePath)}`;
code += `\nexport default __script`;
const result = {
code,
map,
bindings: script ? script.bindings : undefined
};
cached = cached || { styles: [], customs: [] };
cached.script = result;
exports.vueCache.set(filePath, cached);
return result;
}
function compileSFCTemplate(root, template, filePath, publicPath, scoped, bindingMetadata, vueSpecifier, { vueCompilerOptions, vueTransformAssetUrls = {}, vueTemplatePreprocessOptions = {} }) {
let cached = exports.vueCache.get(filePath);
if (cached && cached.template) {
debug(`${publicPath} template cache hit`);
return cached.template;
}
const start = Date.now();
const { compileTemplate } = resolveVue_1.resolveCompiler(root);
if (typeof vueTransformAssetUrls === 'object') {
vueTransformAssetUrls = {
base: path_1.default.posix.dirname(publicPath),
...vueTransformAssetUrls
};
}
const preprocessLang = template.lang;
let preprocessOptions = preprocessLang && vueTemplatePreprocessOptions[preprocessLang];
if (preprocessLang === 'pug') {
preprocessOptions = {
doctype: 'html',
...preprocessOptions
};
}
const { code, map, errors } = compileTemplate({
source: template.content,
filename: filePath,
inMap: template.map,
transformAssetUrls: vueTransformAssetUrls,
compilerOptions: {
...vueCompilerOptions,
scopeId: scoped ? `data-v-${hash_sum_1.default(publicPath)}` : null,
bindingMetadata,
runtimeModuleName: vueSpecifier
},
preprocessLang,
preprocessOptions,
preprocessCustomRequire: (id) => require(utils_1.resolveFrom(root, id))
});
if (errors.length) {
console.error(chalk_1.default.red(`\n[vite] SFC template compilation error: `));
errors.forEach((e) => {
if (typeof e === 'string') {
console.error(e);
}
else {
logError(e, filePath, template.map.sourcesContent[0]);
}
});
}
const result = {
code,
map: map
};
cached = cached || { styles: [], customs: [] };
cached.template = result;
exports.vueCache.set(filePath, cached);
debug(`${publicPath} template compiled in ${Date.now() - start}ms.`);
return result;
}
async function compileSFCStyle(root, style, index, filePath, publicPath, { cssPreprocessOptions, cssModuleOptions }) {
let cached = exports.vueCache.get(filePath);
const cachedEntry = cached && cached.styles && cached.styles[index];
if (cachedEntry) {
debug(`${publicPath} style cache hit`);
return cachedEntry;
}
const start = Date.now();
const { generateCodeFrame } = resolveVue_1.resolveCompiler(root);
const resource = filePath + `?type=style&index=${index}`;
const result = (await cssUtils_1.compileCss(root, publicPath, {
source: style.content,
filename: resource,
id: ``,
scoped: style.scoped != null,
vars: style.vars != null,
modules: style.module != null,
preprocessLang: style.lang,
preprocessOptions: cssPreprocessOptions,
modulesOptions: cssModuleOptions
}));
cssUtils_1.recordCssImportChain(result.dependencies, resource);
if (result.errors.length) {
console.error(chalk_1.default.red(`\n[vite] SFC style compilation error: `));
result.errors.forEach((e) => {
if (typeof e === 'string') {
console.error(e);
}
else {
const lineOffset = style.loc.start.line - 1;
if (e.line && e.column) {
console.log(chalk_1.default.underline(`${filePath}:${e.line + lineOffset}:${e.column}`));
}
else {
console.log(chalk_1.default.underline(filePath));
}
const filePathRE = new RegExp('.*' +
path_1.default.basename(filePath).replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&') +
'(:\\d+:\\d+:\\s*)?');
const cleanMsg = e.message.replace(filePathRE, '');
console.error(chalk_1.default.yellow(cleanMsg));
if (e.line && e.column && cleanMsg.split(/\n/g).length === 1) {
const original = style.map.sourcesContent[0];
const offset = original
.split(/\r?\n/g)
.slice(0, e.line + lineOffset - 1)
.map((l) => l.length)
.reduce((total, l) => total + l + 1, 0) +
e.column -
1;
console.error(generateCodeFrame(original, offset, offset + 1)) + `\n`;
}
}
});
}
result.code = await cssUtils_1.rewriteCssUrls(result.code, publicPath);
cached = cached || { styles: [], customs: [] };
cached.styles[index] = result;
exports.vueCache.set(filePath, cached);
debug(`${publicPath} style compiled in ${Date.now() - start}ms`);
return result;
}
function resolveCustomBlock(custom, index, filePath, publicPath) {
let cached = exports.vueCache.get(filePath);
const cachedEntry = cached && cached.customs && cached.customs[index];
if (cachedEntry) {
debug(`${publicPath} custom block cache hit`);
return cachedEntry;
}
const result = custom.content;
cached = cached || { styles: [], customs: [] };
cached.customs[index] = result;
exports.vueCache.set(filePath, cached);
return result;
}
// these are built-in query parameters so should be ignored
// if the user happen to add them as attrs
const ignoreList = ['id', 'index', 'src', 'type'];
function attrsToQuery(attrs, langFallback) {
let query = ``;
for (const name in attrs) {
const value = attrs[name];
if (!ignoreList.includes(name)) {
query += `&${querystring_1.default.escape(name)}=${value ? querystring_1.default.escape(String(value)) : ``}`;
}
}
if (langFallback && !(`lang` in attrs)) {
query += `&lang=${langFallback}`;
}
return query;
}
function logError(e, file, src) {
const locString = e.loc ? `:${e.loc.start.line}:${e.loc.start.column}` : ``;
console.error(chalk_1.default.underline(file + locString));
console.error(chalk_1.default.yellow(e.message));
if (e.loc) {
console.error(compiler_sfc_1.generateCodeFrame(src, e.loc.start.offset, e.loc.end.offset) + `\n`);
}
}
//# sourceMappingURL=serverPluginVue.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from '.';
export declare const wasmPlugin: ServerPlugin;

18
node_modules/vite/dist/node/server/serverPluginWasm.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wasmPlugin = void 0;
const utils_1 = require("../utils");
exports.wasmPlugin = ({ app }) => {
app.use((ctx, next) => {
if (ctx.path.endsWith('.wasm') && utils_1.isImportRequest(ctx)) {
ctx.type = 'js';
ctx.body = `export default (opts = {}) => {
return WebAssembly.instantiateStreaming(fetch(${JSON.stringify(ctx.path)}), opts)
.then(obj => obj.instance.exports)
}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginWasm.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginWasm.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginWasm.ts"],"names":[],"mappings":";;;AACA,oCAA0C;AAE7B,QAAA,UAAU,GAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IAClD,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACpB,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,uBAAe,CAAC,GAAG,CAAC,EAAE;YACtD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG;wDACuC,IAAI,CAAC,SAAS,CAC5D,GAAG,CAAC,IAAI,CACT;;QAED,CAAA;YACF,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -0,0 +1,2 @@
import { ServerPlugin } from '.';
export declare const webWorkerPlugin: ServerPlugin;

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.webWorkerPlugin = void 0;
exports.webWorkerPlugin = ({ app }) => {
app.use((ctx, next) => {
if (ctx.query.worker != null) {
ctx.type = 'js';
ctx.body = `export default function WrappedWorker() {
return new Worker(${JSON.stringify(ctx.path)}, { type: 'module' })
}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginWebWorker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"serverPluginWebWorker.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginWebWorker.ts"],"names":[],"mappings":";;;AAEa,QAAA,eAAe,GAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IACvD,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACpB,IAAI,GAAG,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,EAAE;YAC5B,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG;4BACW,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC;QAC5C,CAAA;YACF,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}